Chapter 02. Classes & Objects Class
Chapter 02. Classes & Objects Class
Class
Class is a way to bind data and its associated functions together. Class
can also be defined as user defined data type that contains data members
and member functions in it. So, class is a blueprint for object. That is, it
defines what an object of the class will consist of and what operations can
be performed on such an object.
Specifying a Class
Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions
Class declaration syntax:
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
Objects
Objects are the basic unit of OOP. They are instances of class, in which
data members and various member functions that operate on data are
bundled as a unit called as object.
Creating Objects
Once a class is declared, we can create variables of that type by using the
class name, like any other built-in type variable.
Objects can also be created when a class is defined by placing their
names immediately after the closing brace, as we do in structures.
For example, let’s say we have a class Car which has data members
(variables) such as speed, weight, price and functions such as
gearChange(), slowDown(), brake() etc. Now let’s say I create a object of
this class named FordFigo which uses these data members and functions
and give them its own values. Similarly we can create as many objects as
we want using the blueprint (class).
class Car
{
//Data members
char name[20];
int speed;
int weight;
public:
//Functions
void brake(){
}
void slowDown(){
}
};
int main()
{
//ford is an object
Car ford;
}
Access Specifiers
Access specifiers in C++ class defines the access control rules. C++ has 3
new keywords introduced, namely,
1. public
2. private
3. protected
Public
Public, means all the class members declared under public will be
available to everyone. The data members and member functions declared
public can be accessed by other classes too. That means, public members
can be accessed from outside the class also.
class PublicAccess
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Private
Private members can be accessed only from within the class. That means,
the class members declared private cannot be accessed outside that
class. If someone tries to access the private member, they will get a
compile time error. By default class variables and member functions are
private.
class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Protected
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
class Cube
{
public:
int side;
int getVolume();
}
The main function for both the function definition will be same. Inside
main() we will create object of class, and will call the member function
using dot . operator.
int main()
{
Cube C1;
C1.side=4; // setting side value
cout<< "Volume of cube C1 ="<< C1.getVolume();
}
Once you define class it will not allocate memory space for the data
member of the class. data member of the class can contain different value
for the different object thus memory allocation is performed separately
for each data member for different object at the time of creating an
object. Member function remains common for all objects. Memory
allocation is done only once for member function at the time of defining
it. The memory allocation of class members is shown below:
Common to all Objects
Any changes in the static data member through one member function will
reflect in all other object’s member functions.
Declaration
Consider the example, here static data member is accessing through the
static member function:
#include <iostream.h>
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;
}
Output
Value of X: 10
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.h>
class Demo
{
public:
static int ABC;
};
//defining
int Demo :: ABC =10;
int main()
{
Value of ABC: 10
class_name:: function_name(perameter);
#include <iostream.h>
class Demo
{
private:
//static data members
static int X;
static int Y;
public:
//static member function
static void Print()
{
cout <<"Value of X: " << X << endl;
cout <<"Value of Y: " << Y << endl;
}
};
int main()
{
Demo OB;
//accessing class name with object name
cout<<"Printing through object name:"<<endl;
OB.Print();
return 0;
}
Output
In above program X and Y are two static data members and print() is a
static member function. According to the rule of static in C++, only static
member function can access static data members. Non-static data
member can never be accessed through static member functions.
friend Function
By using the keyword friend compiler knows the given function is a friend
function.
For accessing the data, the declaration of a friend function should be done
inside the body of a class starting with the keyword friend.
Example,
#include <iostream.h>
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Output:
Length of box: 10
Array of Objects
class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;
method1();
method2();
----------
methodN();
};
#include<iostream.h>
#include<conio.h>
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;
cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary
;
}
};
void main()
{
int i;
for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
E[i].GetData();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
Output :
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
Object as function arguments
Like any other data type, Objects of a class can be passed as Function
Arguments.
#include <iostream.h>
#include <conio.h>
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
clrscr();
getch();
return 0;
}
Output
Value of A : 10
Value of A : 20
Value of A : 30
Concepts of Constructors
Constructor is a special function used to initialize class data members or
we can say constructor is used to initialize the object of class.
Characteristics constructor.
Types of Constructor
• Default Constructor
• Parameterize Constructor
Default Constructor
Construct without parameter is called default constructor.
#include<iostream.h>
#include<string.h>
class Student
{
int Roll;
char Name[25];
float Marks;
public:
Student() //Default Constructor
{
Roll = 1;
strcpy(Name,"Kumar");
Marks = 78.42;
}
void Display()
{
cout<<"\n\tRoll : "<<Roll;
cout<<"\n\tName : "<<Name;
cout<<"\n\tMarks : "<<Marks;
}
};
void main()
{
Output :
Roll : 1
Name : Kumar
Marks : 78.42
Parameterize Constructor
Constructor with parameter is called parameterize constructor.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Student
{
int Roll;
char Name[25];
float Marks;
public:
void Display()
{
cout<<"\n\tRoll : "<<Roll;
cout<<"\n\tName : "<<Name;
cout<<"\n\tMarks : "<<Marks;
}
};
void main()
{
Student S(2,"Sumit",89.63);
//Creating Object and passing values to Constructor
S.Display();
//Displaying Student Details
Output :
Roll : 2
Name : Sumit
Marks : 89.63
Copy Constructor
Initialization of an object through another object is called copy
constructor. In other words, copying the values of one object into another
object is called copy constructor.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Student
{
int Roll;
char Name[25];
float Marks;
public:
Student(int r,char nm[],float m)//Constructor 1: Parameterize
{
Roll = r;
strcpy(Name,nm);
Marks = m;
}
void main()
{
Student S1(2,"Suman",89.63);
Output :
Values in object S1
Roll : 2
Name : Suman
Marks : 89.63
Values in object S2
Roll : 2
Name : Suman
Marks : 89.63
#include<iostream.h>
#include<conio.h>
class Example
{
int a, b;
public:
Example()
{
a = 50;
b = 100;
cout << "\nIn Constructor";
}
Example(int x, int y)
{
a = x;
b = y;
cout << "\nIn Constructor";
}
void Display()
{
cout << "\nValues :" << a << "\t" << b;
}
};
int main()
{
Example Object(10, 20);
Example Object2;
Object.Display();
Object2.Display();
getch();
return 0;
}
Sample Output
Im Constructor
Im Constructor
Values :10 20
Values :50 100
#include <iostream.h>
class Demo
{
private:
int X,Y;
public
Demo()
{
X = 0;
Y = 0;
~Demo()
{
cout << endl << "Destructor Called" << endl;
}
void putValues()
{
cout << endl << "Value of X : " << X;
cout << endl << "Value of Y : " << Y << endl;
}
};
int main()
{
Demo d1= Demo(10);
return 0;
}
Output
Constructor Called
D1 Value Are :
Value of X : 10
Value of Y : 20
Constructor Called
D2 Value Are :
Value of X : 30
Value of Y : 40
Destructor Called
Destructor Called
Destructors
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Student
{
int Roll;
char Name[25];
float Marks;
public:
void Display()
{
cout<<"\n\tRoll : "<<Roll;
cout<<"\n\tName : "<<Name;
cout<<"\n\tMarks : "<<Marks;
}
~Student() //Destructor
{
cout<<"\n\tEnd of program.";
}
};
void main()
{
Student S;
S.Display();
Output :
Roll : 4
Name : Sumit
Marks : 89.56
End of program.