Unit 5 Classes and objects 06.04.2022
Unit 5 Classes and objects 06.04.2022
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.
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
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;
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
};
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 main() {
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
return 0;}
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.
Class student
{
Static int count; //declaration within class
-----------------
-----------------
-----------------
};
void demo()
{
// static variable
static int count = 0;
cout << 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();
#include<iostream>
using namespace std;
class GfG
{
public:
// 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()
{
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
#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;
}
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.
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.
... .. ...
... .. ...
}
class className
... .. ...
... .. ...
return_type functionName(argument/s)
... .. ...
... .. ...
}
Example 1: Working of friend Function Distance: 5
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
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);
}
#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;
};
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/