Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Unit 5 Classes and objects 06.04.2022

This document covers the concepts of classes and objects in C++, including limitations of C structures, class declaration, member functions, memory allocation, static members, and friend functions. It provides examples of creating objects, using arrays of objects, and passing objects as function arguments. Additionally, it explains access specifiers, nesting member functions, and the use of static member functions and variables.

Uploaded by

23it062
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 5 Classes and objects 06.04.2022

This document covers the concepts of classes and objects in C++, including limitations of C structures, class declaration, member functions, memory allocation, static members, and friend functions. It provides examples of creating objects, using arrays of objects, and passing objects as function arguments. Additionally, it explains access specifiers, nesting member functions, and the use of static member functions and variables.

Uploaded by

23it062
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit 5 Classes and objects

 Limitation of C structure,
 Declaring class and defining member function
 making outside function inline
 Nesting member function
 Private member function
 arrays within a class
 memory allocation of objects
 Static data members and Member functions
 Arrays of Objects
 Object as a function argument
 Friend functions
 Returning objects
 const Member functions.
Limitation of C structure
No Data Hiding: C Structures do not permit data hiding. Structure members can be
accessed by any function, anywhere in the scope of the Structure.
Functions inside Structure: C structures do not permit functions inside Structure
Static Members: C Structures cannot have static members inside their body
Access Modifiers: C Programming language do not support access modifiers. So
they cannot be used in C Structures.

Declaring class and defining member function

Here, the keyword class specifies that we are using a new data type and is followed
by the class name. The body of the class has two keywords namely : (i) private (ii)
public In C++, the keywords private and public are called access specifiers. The data
hiding concept in C++ is achieved by using the keyword private. Private data and
functions can only be accessed from within the class itself. Public data and functions
are accessible outside the class also.
class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Create an Object

class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main()
{
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

Multiple Objects
// Create a Car class with some attributes
class Car
{
public:
string brand;
string model;
int year;
};

int main()
{
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}

Member Function Definition

The class specification can be done in two part :


(i) Class definition. It describes both data members and member
functions.
(ii) Class method definitions. It describes how certain class
member functions are coded.

In C++, the member functions can be coded in two ways :


(a) Inside class definition
(b) Outside class definition using scope resolution operator
(::)
The code of the function is same in both the cases, but the
function header is
different as explained below

Inside class definition Example


class MyClass
{ // The class
public: // Access specifier
void myMethod()
{ // Method/function defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Outside class definition using scope resolution operator
class MyClass
{ // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
You can also add parameters
Example
#include <iostream>
using namespace std;

class Car
{
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed)


{
return maxSpeed;
}

int main() {

Car myObj; // Create an object of Car


cout << myObj.speed(200); // Call the method with an argument
return 0;
}
Read and print details of a student using class program in C++
/*C++ program to create class for a student.*/
#include <iostream>
using namespace std;
class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};
//member function definition, outside of the class
void student::getDetails(void)
{
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;
perc=(float)total/500*100;
}
//member function definition, outside of the class
void student::putDetails(void)
{
cout << "Student details:\n";
cout << "Name:"<< name << ",Roll Number:" << rollNo <<
",Total:" << total << ",Percentage:" << perc;
}
int main()
{
student std; //object creation
std.getDetails();
std.putDetails();
return 0;
}

Nesting member function


A member function of a class can be called only by an object
of that class using a dot operator. However, there is an
exception to this. A member function can be called by using
its name inside another member function of the same class.
This is known as nesting of member functions.
#include <iostream>
using namespace std;
class NestingMemberFunction
{
private :
int myint;
public :
void set();
int get();
};
void NestingMemberFunction :: set()
{
myint = -1;
}
int NestingMemberFunction :: get()
{
set();
return myint;
}
int main ()
{
int printvariable;
NestingMemberFunction NestingMemberFunction1;
printvariable = NestingMemberFunction1.get();
cout << "The variable is : " << printvariable;
return 0;
}

Arrays within a class


#include<iostream.h>
class arraydemo
{
int a[6];
public:
void getelts()
{
cout<<”Enter 6 numbers in the array:”<<endl;
for(int i=0;i<6;i++)
{
cin>>a[i];
}
}
void show()
{
cout<<”\nArray elements are”<<endl;
for(int i=0;i<6;i++)
{
cout<<a[i]<<endl;
}
}
};
void main()
{
arraydemo obj;
obj.getelts();
obj.show(); }
C++ program to store and calculate the sum of 5 numbers entered by
the user using arrays.
#include <iostream>
using namespace std;

int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";

// Storing 5 number entered by user in an array


// Finding the sum of numbers entered
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i];
sum += numbers[i];
}

cout << "Sum = " << sum << endl;

return 0;}

memory allocation of objects


Memory for Objects in c++

class book
{
II body of the class
};
int main ()
{
book bookl, book2, book3; //objects of class book
return 0;
}
The memory space is allocated to the data members of a class only when an object
of the class is declared, and not when the data members are declared inside the class.
Since a single data member can have different values for different objects at the same
time, every object declared for the class has an individual copy of all the data
members.
On the other hand, the memory space for the member functions is allocated only
once when the class is defined. In other words, there is only a single copy of each
member function, which is shared among all the objects. For instance, the three
objects, namely, book1, book2 and book3 of the class book have individual copies
of the data members title and price. However, there is only one copy of the member
functions getdata () and putdata () that is shared by all the three objects
Arrays of Objects

suppose we have 50 students in a class and we have to input the name and marks
of all the 50 students. Then creating 50 different objects and then inputting the
name and marks of all those 50 students is not a good option. In that case, we will
create an array of objects as we do in case of other data-types.
an example of taking the input of name and marks of 5 students by creating an
array of the objects of students.

#include <iostream>
#include <string>
using namespace std;
class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
} };
int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
return 0; }
Static data members and Member functions
Static Data Member: It is generally used to store value common to the whole
class. The static data member differs from an ordinary data member in the
following
ways :
(i) Only a single copy of the static data member is used by all the objects.
(ii) It can be used within the class but its lifetime is the whole program.

For making a data member static, we require :

(a) Declare it within the class.


(b) Define it outside the class.
For example

Class student
{
Static int count; //declaration within class
-----------------
-----------------
-----------------
};

The static data member is defined outside the class as :


int student :: count; //definition outside class
The definition outside the class is a must.
We can also initialize the static data member at the time of its definition as:

int student :: count = 0;


If we define three objects as : sudent obj1, obj2, obj3
/ C++ program to demonstrate // the use of static Static variables in a Function
#include <iostream>
#include <string>
using namespace std;

void demo()
{
// static variable
static int count = 0;
cout << count << " ";

// value is updated and


// will be carried to next
// function calls
count++;
}

int main()
{
for (int i=0; i<5; i++)
demo();
return 0;
}

Output:
0 1 2 3 4

You can see in the above program that the variable count is declared as static. So, its value is
carried through the function calls. The variable count is not getting initialized for every time the
function is called.
Static Member Function: A static member function can access only
the static members of a class. We can do so by putting the keyword
static before the name of
the function while declaring it for example,
Class student
{
Static int count;
-----------------
public :
-----------------
-----------------
static void showcount (void) //static member function
{
Cout<<”count=”<<count<<”\n”;
}
};
int student ::count=0;

Here we have put the keyword static before the name of the function
shwocount ().
In C++, a static member function fifers from the other member
functions in the following ways:
(i) Only static members (functions or variables) of the same class can be
accessed by a static member function.
(ii) It is called by using the name of the class rather than an object as
given below:
Name_of_the_class :: function_name
For example,
student::showcount();

C++ program to demonstrate static member function in a class

#include<iostream>
using namespace std;

class GfG
{
public:

// static member function


static void printMsg()
{
cout<<"Welcome to GfG!";
}
};

// main function
int main()
{
// invoking a static member function
GfG::printMsg();
}

Welcome to GfG!
#include <iostream>
using namespace std;

class Demo
{
private:
static int X;

public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};

//defining
int Demo :: X =10;

int main()
{
Demo X;

X.fun();

return 0;
}

O/P :- Value of X is 10
Accessing static data member without static member
function

A static data member can also be accessed through the class name without using
the static member function (as it is a class member), here we need an Scope
Resolution Operator (SRO) :: to access the static data member without static member
function.

Syntax:

class_name :: static_data_member;

#include <iostream>
using namespace std;
class Demo
{
public:
static int ABC;
};
//defining
int Demo :: ABC =10;

int main()
{

cout<<"\nValue of ABC: "<<Demo::ABC;


return 0;
}
Objects as Function Arguments: -

Objects as Function Arguments in c++ The objects of a class can be passed asarguments to
member functions as well as nonmember functions either by value or by reference. When
an object is passed by value, a copy of the actual object is created inside the function. This
copy is destroyed when the function terminates

Example : Pass Objects to Function

#include <iostream>
using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
} };
int main()
{
Demo d1;
Demo d2;
Demo d3;
//assigning values to the data member of objects
d1.set(10);
d2.set(20);
//passing object d1 and d2
d3.sum(d1,d2);
//printing the values
d1.print();
d2.print();
d3.print();
return 0;}

Call by value :-
Arguments are passed by value, the function create its own copy of the objects and
works with it. Any modification made to the object in the function does not affect
the object used to call the functions.
#include <iostream>
using namespace std;
class Convert
{
public :
int i;
void increment(Convert obj)
{
obj.i=obj.i*2;
cout << "Value of i in member function : " << obj.i;
}
};
int main ()
{
Convert obj1;
obj1.i=3;
obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
return 0;
}
Call by reference: -

If arguments are passed by reference, the memory address is passed directly to the
function. And the function works directly works directly with the original object.

#include <iostream>
using namespace std;
class Convert
{
public :
int i;
void increment(Convert &obj)
{
obj.i=obj.i*2;
cout << "Value of i in member function : " << obj.i;
}
};
int main ()
{
Convert obj1;
obj1.i=3;
obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
return 0;
}

Friend Function in C++

a nonmember function cannot access an object's private or protected data.

But, sometimes this restriction may force programmer to write long and
complex codes. So, there is mechanism built in C++ programming to access
private or protected data from non-member functions.

This is done using a friend function or/and a friend class.

For accessing the data, the declaration of a friend function should be made
inside the body of the class (can be anywhere inside class either in private
or public section) starting with keyword friend.

Declaration of friend function in C++


class class_name

... .. ...

friend return_type function_name(argument/s);

... .. ...

}
class className

... .. ...

friend return_type functionName(argument/s);

... .. ...

return_type functionName(argument/s)

... .. ...

// Private and protected data of className can be accessed from

// this function because it is a friend function of className.

... .. ...

}
Example 1: Working of friend Function Distance: 5

/* C++ program to demonstrate the working of friend function.*/


#include <iostream>
using namespace std;

class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};

// friend function definition


int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D); return 0;}

Example 2: Addition of members of two different classes


using friend Function
#include <iostream>
using namespace std;
// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};

class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};
// Function add() is the friend function of classes A and B
// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}

int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
#include<iostream>
using namespace std;
class c;
class f
{
float temp;
public:
void getdata();
friend void compare(f,c);
};
class c
{
float temperature;
public:
void get();
friend void compare(f,c);
};
void f ::getdata()
{
cout<<"Enter temperature in Fahrenheit: ";
cin>>temp;
}
void c ::get()
{
cout<<"Enter temperature in Celsius: ";
cin>>temperature;
}
void compare(f f1, c c1)
{
float tem;
tem=(9*c1.temperature/5)+32;
if(tem>f1.temp)
cout<<"Celsius is greater";
else
cout<<"Fahrenheit is greater";
}
int main()
{
f f2;
f2.getdata();
c c2;
c2.get();
compare(f2,c2);
return 0;
}

#include<iostream>
using namespace std;
class far;
class cel
{
float t1;
void read1();
void print1();
friend void comp(far f,cel c);
}c1;
class far
{
float t2;
void read2();
void print2();
friend void comp(far f,cel c);
}f1;
void cel::read1()
{
cout<<"Enter temp in Celsius:";
cin>>t1;
}
void cel::print1()
{
cout<<"Temperature in Celsius:"<<t1;
}
void far::read2()
{
cout<<"Enter temp in Fahrenheit:";
cin>>t2;
}
void far::print2()
{
cout<<"Temperature in Fahrenheit:"<<t2;
}
void comp(far f,cel c)
{
f.read2();
c.read1();
int n=(((9*(c.t1))/5)+32);
if(f.t2>n)
cout<<"Temperature in Fahrenheit is greater.";
else
cout<<"Temperature in Celsius is greater.";
}

int main()
{
comp(f1,c1);
}

Const member functions in C++

A function becomes const when const keyword is used


in function's declaration. The idea of const functions is not allow them to
modify the object on which they are called.

A constant (const) member function can be declared by


using const keyword, it is used when we want a function that should not
be used to change the value of the data members i.e. any type of
modification is not allowed with the constant member function

#include<iostream>
using namespace std;

class Test
{
int value;
public:
Test(int v = 0)
{
value = v;
}
// We get compiler error if we add a line
like "value = 100;"
// in this function.
int getValue()
const
{return value;}
};
int main()
{
Test t(20);
cout<<t.getValue();
return 0; }
Example 2 C++ Return Object from a Function
#include <iostream>
using namespace std;

class Student {
public:
double marks1, marks2;
};

// function that returns object of Student


Student createStudent() {
Student student;

// Initialize member variables of Student


student.marks1 = 96.5;
student.marks2 = 75.0;

// print member variables of Student


cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;

return student;
}

int main() {
Student student1;

// Call function
student1 = createStudent();
return 0;
}

References:

https://www.programiz.com/cpp-programming/
https://www.geeksforgeeks.org/
https://www.includehelp.com/cpp-tutorial
http://www.trytoprogram.com/cplusplus-programming/
https://www.studytonight.com/cpp/

You might also like