0% found this document useful (0 votes)
11 views

Notes_CSE2001_OOP_with_C++_Unit II

The document covers Object Oriented Programming concepts in C++ focusing on classes, access specifiers, constructors, destructors, and copy constructors. It defines key terms, illustrates the differences between classes and structures, and provides examples of syntax and usage. The learning objectives include understanding class definitions, access rights, and the importance of constructors and destructors in managing object lifecycles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Notes_CSE2001_OOP_with_C++_Unit II

The document covers Object Oriented Programming concepts in C++ focusing on classes, access specifiers, constructors, destructors, and copy constructors. It defines key terms, illustrates the differences between classes and structures, and provides examples of syntax and usage. The learning objectives include understanding class definitions, access rights, and the importance of constructors and destructors in managing object lifecycles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Class Notes: Object Oriented Programming with C++ (CSE2001)

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:

• To define, understand and demonstrate the classes in C++.


• To elaborate and demonstrate the access specifiers in C++.
• To distinguish between class and structure.
• To demonstrate the concepts of various constructors and destructor in OOP.
• To demonstrate the concept of dynamic object.
• To demonstrate the concept of friend function, friend class and container class.

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

Figure 2.1. Class

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

int var1, var2;


User-defined data type (Class)

PetrolPump P1, P2;

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:

// private member functions and data members (variables)


data_type var1;

data_type function_name1(parameter list);

public:

// public member functions and data members (variables)


data_type var3 ;

data_type function_name2 (parameter list);

protected:

// protected member functions and data members (variables)


data_type var5 ;

Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
data_type function_name3 (parameter list) ;

} object_list ;

The example of class declaration based on general syntax is shown below:

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;

Kindly Refer the programs performed as practical

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.)

Example program to demonstrate the concept of access specifier

//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 C++ syntax defines a set of special functions called constructors.


Constructors are used to initialize the objects’ member variables and are
automatically called each time the object is created. These functions have the
same name as class name and do not return any value, not even void.

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.

Constructors have following special characteristics:

o They are automatically called each time the object is created.

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 They do not explicitly return any value, not even void.

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 The object of constructor cannot be used as union member.

o They cannot be inherited, but they can be called by derived class.

o Constructors cannot be virtual.

o The addresses of the constructors cannot be referred.

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:

When an only constructor has been parameterized, the statement:


Book b1 ;
may not create the object. To create object initial values must be passed as arguments to
constructor function.

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 .

On declaring our own constructor for a class:

o No default constructor is provided by the compiler.

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:

As we know that, the constructor is used to initialize an object when it is created, a


destructor is automatically called to clean up the object just before it is destroyed. The
destructor always has the same name as the class, but preceded with a tilde sign (~).A
destructor has no explicit return type and never takes any arguments.

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.

Destructors have following special characteristics:

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.

o They do not explicitly return any value, not even void.

o They cannot be inherited, but they can be called by derived class.

o The destructors neither have default values nor can be overloaded.

o Destructors can be virtual.

o The addresses of the destructors cannot be referred.

The example Program 4 below is demonstrating the concept of destructor function also.

Example program to demonstrate the concept of destructor and constructor


calling

//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++; }

Circle(int) ; //constructor-2 overloaded constructor


Circle(float) ; //constructor-3 overloaded constructor
~ Circle ( ) ; // Destructor

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:

The copy constructor is a constructor which creates an object by initializing it with an


object of the same class, which has been created previously. The copy constructor is
used to −

• Initialize one object from another of the same type.

• Copy an object to pass it as an argument to a function.

• Copy an object to return it from a function.

• 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 −

classname (const classname &obj) {

// 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.

• User Defined constructor: The programmer defines the user-defined


constructor.

Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University
Copy constructor can be called in the following ways:

Refer example Program -5 to understand the concept of copy constructor

• 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.

Example program to demonstrate the concept of Copy constructor

//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:

The values in object are: 5 and 27.6


The values in object are: 5 and 27.6

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] ;

To understand the concept of an array of objects, consider this example program – 6.


Example program to demonstrate the concept of array of objects
//Program - 6
using namespace std;
#include<iostream>
class Car
{
int model;
public:
getmodel()
{
int x;
cout<<"Enter the model no.:";
cin>>x;
model = x;
}
printmodel()
{
cout<<"printing the model no.:"<<model<<endl;
}
};
int main()
{
Car c[3];
//use for loop to get and show the values through objects / instances of class
int i;
for(i=0; i<3; i++)
{
c[i].getmodel();
c[i].printmodel();
}

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;

Refer below the Program 7 to understand the concept of dynamic object.

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:

o A friend function can be declared in the private or public or protected section of


the class.
o It can be called like a normal function without using the object.
o A friend function is not in the scope of the class, of which it is a friend.
o A friend function is not invoked using the class object as it is not in the scope of
the class.
o A friend function cannot access the private and protected data members of the
class directly. It needs to make use of a class object and then access the members
using the dot operator.
o A friend function can be a global function or a member of another class.
o Friend functions are useful with operator overloading and the creation of some
I/O functions.

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;
}

10. Friend Class:

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.

Example program to demonstrate the concept of friend class

//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;
}

friend class printClass;


};
class printClass{

public:
void printArea(Area a){
cout<<"Area = "<<a.area;
}
};
int main() {
Area a(10,15);
a.calcArea();
printClass p;
p.printArea(a);
return 0; }

Refer the example program 9 to understand the concept of friend class

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.

11. Container Class

A container class is a class that can hold a collection of items.

Container classes can be implemented with a C++ class.

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:

1. Program to demonstrate the concept of class and objects.

(Instantiate the objects of class Student or Person.)

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.

5. Program to demonstrate the concept of constructor functions.

6. Program to demonstrate the concept of default and overloaded constructor.

7. Program to demonstrate the concept of concept of destructor and constructor calling.

8. Program to demonstrate the concept of Copy constructor.

9. Program to demonstrate the concept of array of objects.

10. Program to demonstrate the concept of dynamic objects.

11. Program to demonstrate the concept of friend function.

12. Program to demonstrate the concept of friend class.

13. Program to demonstrate the concept of container class.

Additionally the topics which are discussed in Class are:

 Default constructor and parameterized constructor.


 new and delete operators .

Prepared by: Prof. Anand Motwani, Faculty, SCSE, VIT Bhopal University

You might also like