Notes_CSE2001_OOP_with_C++_Unit II
Notes_CSE2001_OOP_with_C++_Unit II
UNIT – II
Syllabus:
Classes and objects: Definition of classes – access specifier – class versus structure – constructor –
destructor – copy constructor and its importance – array of objects – dynamic objects- friend
function-friend class – container class
Learning Objectives:
1. Definition of Classes:
To put the idea of structures (grouping of different type of logically related data
items) and functions (grouping of instructions to carry specific tasks) together
into one entity, which we call class is introduced. Figure 2.1 depicts the idea that
the class encapsulates both data and functions. C++ introduces class construct
for defining new data types (also known as abstract data types). A blueprint for a
house design is like a class description. All the houses built from that blueprint
are objects of that class. A given house is an instance.
Class
Data Members
Member
functions
In C++, the “object” is the fundamental idea in the conception of C++ programs
whereas the “class” concept is used for defining new types that can be used
exactly as built-in types (int, float etc.). A data type comprises of: “representation
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
of variables or objects of that type” along with “set of allowable operations on
them”.
To perform these operations on user-defined types, these operators ‘+’, ‘*’ etc.
must be overloaded. Overloading Operators and functions is case of
Polymorphism.
Example:
Built-in type
A class definition consists of two parts: header and body. The class header specifies the
class-name that becomes a new type name and is used to declare objects of the class and
its base classes. Soon we’ll discuss base class while discussing inheritance (one of the
OOP concept).
The class body defines the class members. The class members are of two types: data
members (variables) and member functions.
Syntax of Class
class Class-name
{
private:
public:
protected:
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
data_type function_name3 (parameter list) ;
…
} object_list ;
class Circle
{
private:
int radius; // radius is private data member
public: // public member functions
void set_values (int);
float area ( )
{
return (3.14*radius*radius);
}
} c1, c2, c3;
2. Access specifier:
Classes are declared using the keyword class. The Class-name is any valid identifier
for the class; object-list is an optional list of names for objects of this class. The
words private, public and protected are three different access rights (specifiers)
that the class members have. Let us define access rights:
o private: private members are only accessible from within other members of the
same class or from their friends. All member functions and variables are private
to that class by default, which means that they are accessible by other members
of that class. To implement the concept of data hiding private keyword is used.
o public: public members are accessible by all class users from outside the class
where the object is visible.
o protected: protected members are accessible by the class members and from
their friends as well as the members of a derived class.
To declare class members with access specifier: the keyword private, public or
protected followed by a colon is used before the class member(s). Given below the
table specifying the access.
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Refer the Programs (1 & 2) performed in practical.
Here are some example to access private and public member/s of class. Here, we cannot
obtain direct access to private variable using (.) dot operator rather we can set and get
the value/s of private variables through specially written set and get method. (read the
program comments carefully.)
//Program - 1
using namespace std;
#include<iostream>
class MyClass {
private: // Private access specifier
int y; // Private attribute
public: // Public access specifier
int x; // Public attribute
void show()
{
cout<<x;
}
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.show();
myObj.y = 50; // Not allowed (private)
return 0;
}
Output:
25
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Example program to demonstrate the Private access specifier
//Program -2
#include<iostream>
using namespace std;
class Student
{
private: // private data member
int rollno;
public:
// public function to set value for rollno - setter
void setRollno(int i)
{
rollno=i;
}
// public function to get value of rollno - getter
int getRollno()
{
return rollno;
}
};
int main()
{
Student A;
//A.rollno=1; //Compile time error
//cout<<A.rollno; //Compile time error
A.setRollno(101); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}
Output:
101
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
3. Class v/s structure:
In C++, a structure is the same as a class except for a few differences. Following
are some important differences:
Structure Class
A structure generally groups the variables A class is a collection of data as well as
having different data types methods. The property is known as
encapsulation.
A Structure cannot hide its implementation A class can hide its programming and
details from the end user thus not secure. designing details (abstraction), (i.e. only
showing essential ones and hiding
background details) and thus secure.
By default structure members are public. By default class members are private.
struct Test { class Test {
int x; // x is public int x; // x is private
}; };
int main() int main()
{ {
Test t; Test t;
t.x = 20; t.x = 20;
// works fine because x is public // compiler error because x is
return 0; private
} return 0;
}
Keyword struct is used Keyword class is used
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
4. Constructor:
The compiler recognizes the constructors in two ways: First by the name of
constructor which is same as its class name. Secondly it should not have any
return type.
o These functions have the same name as class name and should be declared in
public section.
o They can be defined inside the class or outside the class using scope resolution
operator ‘::’.
o A class may have more than one constructor function but each with different
arguments i.e. they can be overloaded. Also they can have default arguments.
o When dynamic memory allocation is required, they can make implicit calls to
‘new’ and ‘delete’ operators. (refer topic and example of dynamic object)
Parameterized Constructors
C++ permits argument passing to the constructor function just like normal
function, while creating the objects of class. The constructor that can take
arguments are called parameterized constructor. Such constructors may be used
to initialize various data elements of different objects of same class with different
values, while creating.
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Example program to demonstrate the concept of Constructor
//Program - 3
#include<iostream>
using namespace std;
class Book {
float price;
int pages;
public:
Book() //Constructor providing default values
{
cout<<"I am the constructor and I am called on creation of object"<<endl;
pages=0;
price=0.0;
cout<<"No. of pages: "<<pages<<endl;
cout<<"Price of Book: "<<price<<endl;
}
Book(int pg, float pri) //This is parameterized constructor
{
pages = pg;
price = pri;
cout<<"No. of pages: "<<pages<<endl;
cout<<"Price of Book: "<<price<<endl;
}
};
int main()
{
Book b1;
cout<<"Now next object is created with parameters"<<endl;
Book b2(200, 99);
return 0;
}
Output:
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
The default values to b1 object is provided by Book( ) constructor and values to b2 are
provided by Book(int, flaot) parameterized constructor.
Constructor Overloading
Constructor overloading means defining more than one constructor functions that have
the same name but have different types or number of parameters. Similar to the
function, it is possible to overload a constructor. Recall that the compiler will call the
overloaded functions whose parameters match the arguments used in the function call.
In case of constructors, which are automatically called when an object is created, the
function executed is one that matches the arguments passed on the object declaration.
Refer example Program – 4.
Default Constructor
If we do not declare any constructors in a class definition, the compiler supplies the
class a default constructor with no arguments. It’s this constructor that is responsible for
creation of the objects, even though we didn’t define it in the class. Refer example
Program – 4 .
o The way of declaring all objects of that class must be as per constructor
prototypes we defined.
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
5. Destructor:
The reason of destruction of global and automatic objects is end of program and end of
scope respectively. The dynamically created object is destroyed when delete operator is
applied to it. The destructors are commonly used to de-allocate the memory that was
allocated by the constructor.
o They are automatically called to clean up the objects just before their destruction.
o These functions have the same name as class name and should be declared in public
section preceded with a tilde (~) sign.
The example Program 4 below is demonstrating the concept of destructor function also.
//Program – 4
# include <iostream>
using namespace std;
# include <conio.h>
int count = 0 ;
class Circle
{
private: //private data members
float radius ;
public: // public member functions
Circle ( ) //constructor-1
{ cout <<"I am constructor. " ; count++; }
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
float area ( ) //member function
{
return (3.14*radius*radius) ;
}
};
Circle :: Circle( int r ) //function definition
{
radius = r ;
count ++ ;
}
Circle::Circle( float r )
{
radius = r ;
count++;
}
Circle :: ~ Circle( ) // Destructor definition
{
cout << "I am destructor. " << count;
}
int main() //main program begins here
{
int x = 2 ;
float y = 5.0 ;
cout <<"Scope-1"<<endl ;
{
Circle c1 ; //calls first constructor
}
cout << endl ;
cout << "Scope-2" << endl ;
{
Circle c2 ( y ) ; // calls third constructor, float value passed
cout <<"The area is = " << c2.area ( ) ; // function call
cout << endl ;
}
cout << endl ;
cout << "Scope-3"<< endl ;
{
Circle c3 ( x ) ; //calls second constructor, int value passed
cout << "The area is = " << c3.area ( ) ; // function call
cout<<endl ;
}
return 0;
}
Output:
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
6. Copy Constructor and its importance:
• If a copy constructor is not defined in a class, the compiler itself defines one. If
the class has pointer variables and has some dynamic memory allocations, then
it is a must to have a copy constructor. The most common form of copy
constructor is shown here −
// body of constructor
• Here, obj is a reference to an object that is being used to initialize another object.
• Default Copy constructor: The compiler defines the default copy constructor. If
the user defines no copy constructor, compiler supplies its constructor.
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Copy constructor can be called in the following ways:
• When we initialize the object with another existing object of the same class type.
For example, Student s1 = s2, where Student is the class.
• When the object of the same class type is passed by value as an argument.
• When the function returns the object of the same class type by value.
//Program – 5
using namespace std;
#include<iostream>
class A
{
int a;
float b;
public:
//A(){ } //default constructor
//A(int x=0,float y=1000.0) { }; //constructor with default arguments
A(int x, float y) //parameterized constructor
{
a=x;
b=y;
}
A(A &i) //copy constructor
{
a = i.a;
b= i.b;
}
void display()
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
{
cout<<"The values in object are:"<<a<<" and "<<b<<endl;
}
};
int main()
{
A o1(5, 27.6); //parameterized constructor
A o2(o1); //copy constructor
o2.display();
A o3 = o1; //copy constructor
o3.display();
return 0;
}
Output:
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
7. Array of Objects:
Like array of other user-defined data types, an array of type class can also be created.
The array of type class contains the objects of the class as its individual elements.
Thus, an array of a class type is also known as an array of objects. An array of objects
is declared in the same way as an array of any built-in data type.
The syntax for declaring an array of objects is
class_name array_name [size] ;
return 0;
}
Output:
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Figure demonstrating the array of objects
8. Dynamic Objects:
C++ allocates memory and initializes the member variables. An object can be created at
run time; such an object is called a dynamic object. The construction and destruction of
the dynamic object is explicitly done by the programmer. The new and delete operators
are used to dynamically create and delete the object dynamically.
The new operator returns the address of the object created, and it is stored in pointer
(ptr). The variable ptr should be object of same class.
The member variable of the object can be accessed using -> (arrow) operator.
The delete operator destroys the object pointed by pointer (ptr). The dynamic object
can be destroyed using the delete operator as follows:
delete ptr;
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Example program to demonstrate the concept of dynamic object.
//Program – 7
using namespace std;
#include<iostream>
class A
{
int p;
public:
A()
{
int q;
cout<<"Enter p:";
cin>>q;
p=q;
}
~A()
{
cout<<"\nDeleting object" ;
}
void display()
{
cout<<"You entered:"<<p;
}
};
int main()
{
int *p;
A *ptr; // pointer of type class
ptr = new A; //use of new keyword to create dynamic object
//see the following statement
ptr->display(); //calling function through pointer to object
delete ptr;
//we can't access object after this within main
cout<<"BYe Bye.";
}
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
9. Friend Function:
C++ provides a facility for accessing private and protected data by means of a special
feature called “friend” function or class which we will discuss here.
C++ supports the feature of encapsulation in which the data is bundled together with
the functions operating on it to form a single unit. By doing this C++ ensures that data is
accessible only by the functions operating on it and not to anyone outside the class.
This is one of the distinguishing features of C++ that preserves the data and prevents it
from leaking to the outside world. But in some real-time applications, sometimes we
might want to access data outside the bundled unit. For example, an outsider class
might want to access private and protected data of a C++ class.
A friend function in C++ is a function that is preceded by the keyword “friend”. When
the function is declared as a friend, then it can access the private and protected data
members of the class.
A friend function is declared inside the class with a friend keyword preceding as shown
below. Refer the program – 8 to understand the concept of friend function.
class className{
…………..
friend returnType functionName(arg list);
};
As shown above, the friend function is declared inside the class whose private and
protected data members are to be accessed. The function can be defined anywhere in
the code file and we need not use the keyword friend or the scope resolution, operator.
There are some points to remember while implementing friend functions in our
program:
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Example program to demonstrate the concept of friend function
//Program – 8
#include <iostream>
using namespace std;
class XYZ {
private:
int num;
char ch;
public:
XYZ()
{
num = 100;
ch = 'Z';
}
friend void disp(XYZ obj); //declaration for friend function
};
//Global Function
void disp(XYZ obj){
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
int main() {
XYZ obj;
disp(obj);
return 0;
}
Just like friend functions, we can also have a friend class. Friend class can access private
and protected members of the class to which it is a friend. The syntax is:
class A{
……
friend class B;
};
class B{
……..
};
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
As depicted above, class B is a friend of class A. So class B can access the private and
protected members of class A.
But this does not mean that class A can access private and protected members of the
class B. Note that the friendship is not mutual unless we make it so.
Similarly, the friendship of the class is not inherited. This means that as class B is a
friend of class A, it will not be a friend of the subclasses of class A.
//Program – 9
using namespace std;
# include <iostream>
#include <string>
class Area{
int length, breadth, area;
public:
Area(int length, int breadth):length(length),breadth(breadth)
{}
void calcArea(){
area = length * breadth;
}
public:
void printArea(Area a){
cout<<"Area = "<<a.area;
}
};
int main() {
Area a(10,15);
a.calcArea();
printClass p;
p.printArea(a);
return 0; }
In this program, we have two classes. The Class “Area” which calculates the area using
the length and breadth parameters. Note that the fields, area, length, and breadth are all
private members of the class Area.
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
The next class that is used is the “printClass” that prints the area calculated by a
function calcArea in the Area class. As the members are private, we need to make
printClass a friend of Area class.
Once that is done, in the main function we create an object of the Area class, calculate
the area and pass the object to printArea function of printClass class to display the area.
The class is implemented with a header file (containing documentation and the class
definition) and an implementation file (containing the implementations of the member
functions).
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
List of Programs covered in class:
2. Write a program that defines a class Circle to instantiate the objects of class Circle
and calculates the area using a function.
3. Write a program to demonstrate the concept of public and private access specifier of
class.
4. Write a program for Petrol Pump Machine using the concept of class, object and
constructor. The methods in class must take either the quantity to be dispensed and
calculates the total amount to be paid or amount in (Rs.) and calculates the quantity to
be dispensed.
Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University