Unit - 3
Unit - 3
Syllabus
Classes and Objects – Member Functions – Private and Public Member function – Nesting of
Member Functions – Array of Objects – Pointer to Members – Constructors – Destructors –
Type Conversions
3.1 Classes and Objects
Class is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can
be accessed and used by creating an instance of that class.
For Example: Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range, etc.
Data members are the data variables and member functions are the functions used to
manipulate these variables together, these data members and member functions define
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage, etc, and
member functions can be applying brakes, increasing speed, etc.
A class is defined using the keyword class followed by the name of the class. The body
of the class is defined inside the curly brackets and terminated by a semicolon at the end.
Declaring Objects
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need
to create objects.
Syntax
ClassName ObjectName;
Accessing data members and member functions:
The data members and member functions of the class can be accessed using the
dot(‘.’) operator with the object.
For example, if the name of the object is obj and you want to access the member
function with the name printName() then you will have to write obj.printName().
Let us take previously defined class to access the members of the class using a member
function instead of directly accessing them −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Member functions can be defined within the class definition or separately using scope
resolution operator, : −. Defining a member function within the class definition
declares the function inline, even if you do not use the inline specifier. So either you can
define Volume() function as below −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope resolution
operator (::) as follows −
double Box::getVolume(void) {
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before ::
operator. A member function will be called using a dot operator (.) on a object where it
will manipulate data related to that object only as follows −
Let us put above concepts to set and get the value of different class members in a class –
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Note: If we do not specify any access modifiers for the members inside the class, then
by default the access modifier for the members will be Private.
1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be accessed
by other classes and functions too. The public members of a class can be accessed from
anywhere in the program using the direct member access operator (.) with the object of
that class.
Example:
#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
// main function
int main()
{
Circle obj;
2. Private: The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any object or
function outside the class. Only the member functions or the friend functions are allowed to
access the private data members of the class.
However, we can access the private data members of a class indirectly using the public
member functions of the class.
Example:
// C++ program to demonstrate private access modifier
#include<iostream>
using namespace std;
class Circle
{ // private data member
private:
double radius;
// public member function
public:
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}
};
// main function
int main()
{
// creating object of the class
Circle obj;
// trying to access private data member
// directly outside the class
obj.radius = 1.5;
cout << "Area is:" << obj.compute_area();
return 0;
}
Output:
Radius is: 1.5
Area is: 7.065
3. Protected: The protected access modifier is similar to the private access modifier in the
sense that it can’t be accessed outside of its class unless with the help of a friend class. The
difference is that the class members declared as Protected can be accessed by any subclass
(derived class) of that class as well.
3.4 Nesting of member Functions
Whenever we call a member function inside another member function of one class by
using dot operator it is known as Nesting of the member function.
Normally, the member function which is called by another member function is kept
private so that it cannot be called directly using the dot operator.
Example
#include<iostream.h>
//nested member function
class squarenumb
{
int number;
public:
long square();
void getnumber();
void display();
};
void squarenumb:getnumber()
{
cout<<"Please enter an integer number:";
cin>>number;
}
long squarenumber::square()
{
number=number*number;
return (number);
}
void squarenumb::display()
{
cout<<"Square of the number:"<<square();
int main ()
{
squarenumb square;
square.getnumber();
square.display();
return 0;
}
Output:
Please enter an integer number:10
10
Square of the number:100
3.5 Array of Objects
An array in C/C++ or be it in any programming language is a collection of
similar data items stored at contiguous memory locations and elements can be
accessed randomly using indices of an array.
They can be used to store the collection of primitive data types such as int,
float, double, char, etc of any particular type.
To add to it, an array in C/C++ can store derived data types such as structures,
pointers, etc. Given below is the picture representation of an array.
Example:
Let’s consider an example of taking random integers from the user.
Array of Objects
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need
to create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array
of objects.
Example
Storing more than one Employee data. Let’s assume there is an array of objects for
storing employee data emp[50].
// C++ program to implement the above approach
#include<iostream>
using namespace std;
class Employee
{
int id;
char name[30];
public:
// Declaration of function
void getdata();
// Declaration of function
void putdata();
};
// Defining the function outside the class
void Employee::getdata()
{
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
}
// Defining the function outside the class
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}
// Driver code
int main()
{
// This is an array of objects having maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;
Explanation:
In this example, more than one Employee’s details with an Employee id and name can be
stored.
Employee emp[30] – This is an array of objects having a maximum limit of 30
Employees.
Two for loops are being used-
First one to take the input from user by calling emp[i].getdata() function.
Second one to print the data of Employee by calling the function
emp[i].putdata() function.
Pointer to members allows you to store and manipulate pointers to class or struct
members.
We can assign the address(using the &) of a class member (variables or functions) and
assign it to a pointer variable.
It is a powerful feature that enables you to work with class members in a dynamic and
flexible way.
A class member pointer can be declared using the operator ::* with the class name.
class MyClass{
private:
int data;
public:
void show();
};
We can define the pointer to a member e.g. data using operator ::* as follows
Important Note!
Let’s say obj is an object of MyClass, we can access the data using the pointer ptr as
follows.
cout<<obj.*ptr;
cout<<obj.data; //It is same as above
//PointerToMemberEx1.cpp
#include <iostream>
using namespace std;
class MyClass
{
public:
int myData;
MyClass(int data) : myData(data) {}
};
int main()
{
MyClass obj(10);
int MyClass::*ptr = &MyClass::myData; // Define a pointer to a data member
Output
Value of myData: 10
3.7 Constructors
Constructor is a member function of a class; whose name is the same as the class
name.
Constructor is a special type of member function that is used to initialize the
data members for an object of a class automatically when an object of the same
class is created.
Constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as a constructor.
Constructors do not return value; hence they do not have a return type.
A constructor gets called automatically when we create the object of the class.
Constructors can be overloaded.
A constructor cannot be declared virtual.
Syntax of Constructors
The prototype of the constructor looks like this:
<class-name> (list-of-parameters);
The constructor can be defined inside the class declaration or outside the class
declaration
Examples of Constructors
The below examples demonstrate how to declare constructors for a class :
public:
// constructor
student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}
void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};
int main()
{
student s; // constructor gets called automatically when
// we create the object of the class
s.display();
return 0;
}
Output
Enter the RollNo: 121
Enter the Name: SSN
Enter the Fee: 5000
121 SSN 5000
// driver code
int main()
{
student s;
s.display();
return 0;
}
Output
Enter the RollNo:11
Enter the Name: Ani
Enter the Fee:10111
11 Ani 10111
Characteristics of Constructors
The following are some main characteristics of the constructors:
The name of the constructor is the same as its class name.
Constructors are mostly declared in the public section of the class though they can be
declared in the private section of the class.
Constructors do not return values; hence they do not have a return type.
A constructor gets called automatically when we create the object of the class.
Constructors can be overloaded.
A constructor cannot be declared virtual.
A constructor cannot be inherited.
The addresses of the Constructor cannot be referred to.
The constructor makes implicit calls to new and delete operators during memory
allocation.
Types of Constructor
Constructors can be classified based on in which situations they are being used.
There are 4 types of constructors:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Move Constructor
1. Default Constructor
A default constructor is a constructor that doesn’t take any argument.
It has no parameters.
It is also called a zero-argument constructor.
Example:
class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
Output
a: 10
b: 20
2. Parameterized Constructor
Parameterized Constructors make it possible to pass arguments to constructors.
Typically, these arguments help initialize an object when it is created.
To create a parameterized constructor, simply add parameters to it the way you
would to any other function.
When you define the constructor’s body, use the parameters to initialize the object.
Syntax of Parameterized Constructor
className (parameters...) {
// body
}
Example
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int main()
{
// Constructor called
Point p1(10, 15);
return 0;
}
Output
p1.x = 10,
p1.y = 15
Defining Parameterized Constructor Outside the Class.
// C++ Program to illustrate how to define the parameterized constructor outside the class
#include <iostream>
#include <string.h>
using namespace std;
// class definition
class student {
int rno;
char name[50];
double fee;
public:
student(int, char[], double);
void display();
};
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
// driver code
int main()
{
student s(1001, "Ram", 10000);
s.display();
return 0;
}
Output
1001 Ram 10000
// class
class GFG {
private:
int data;
public:
// parameterized constructor with default values
GFG(int x = 0) { data = x; }
int main()
{
GFG obj2(25);
cout << "First Object Data: " << obj1.getData() << endl;
cout << "Second Object Data: " << obj2.getData()
<< endl;
return 0;
}
Output
First Object Data: 0
Second Object Data: 25
3. Copy Constructor
A copy constructor is a member function that initializes an object using another object of
the same class.
Syntax of Copy Constructor
Copy constructor takes a reference to an object of the same class as an argument.
ClassName (ClassName &obj)
{
// body_containing_logic
}
Just like the default constructor, the C++ compiler also provides an implicit copy constructor
if the explicit copy constructor definition is not present. Here, it is to be noted that, unlike
the default constructor where the presence of any type of explicit constructor results in the
deletion of the implicit default constructor, the implicit copy constructor will always be
created by the compiler if there is no explicit copy constructor or explicit move constructor
is present.
class Sample {
int id;
public:
// parameterized constructor
Sample(int x) { id = x; }
void display() { cout << "ID=" << id; }
};
int main()
{
Sample obj1(10);
obj1.display();
cout << endl;
class Sample {
int id;
public:
// default constructor with empty body
Sample() {}
// parameterized constructor
Sample(int x) { id = x; }
// copy constructor
Sample(Sample& t) { id = t.id; }
// driver code
int main()
{
Sample obj1(10);
obj1.display();
cout << endl;
return 0;
}
Output
ID=10
ID=10
4. Move Constructor
The move constructor is a recent addition to the family of constructors . It is like a copy
constructor that constructs the object from the already existing objects., but instead of
copying the object in the new memory, it makes use of move semantics to transfer the
ownership of the already created object to the new object without creating extra copies.
It can be seen as stealing the resources from other objects.
The move constructor takes the rvalue reference of the object of the same class and transfers
the ownership of this object to the newly created object.
Like a copy constructor, the compiler will create a move constructor for each class that does
not have any explicit move constructor .
Example 1: Defining Move Constructor
class Box {
public:
int* data; // Pointer to an integer value
// Constructor
Box(int value)
{
data = new int;
*data = value;
}
// Move constructor
Box(Box&& other) noexcept
{
cout << "Move Constructor Called" << endl;
// Destructor
~Box() { delete data; }
};
int main()
{
// Create a Box with value 42
Box originalBox(42);
return 0;
}
Output
Move Constructor Called
newBox.data: 42
Uses of Move Constructor
Instead of making copies, move constructors efficiently transfer ownership of these
resources.
This prevents unnecessary memory copying and reduces overhead.
You can define your own move constructor to handle specific resource transfers.
3.8 Destructors
A destructor is also a special member function as a constructor. Destructor destroys
the class objects created by the constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object created by the constructor.
Hence destructor can-not be overloaded.
Destructor neither requires any argument nor returns any value.
It is automatically called when the object goes out of scope.
Destructors release memory space occupied by the objects created by the
constructor.
In destructor, objects are destroyed in the reverse of object creation.
Syntax of Destructors
Like constructors, destructors can also be defined either inside or outside of the class.
class Test {
public:
Test() { cout << "\n Constructor executed"; }
return 0;
}
Output
Constructor executed
Destructor executed
Example 2: Counting the Number of Times Object is Created and Destroyed
// class definition
class Test {
public:
Test()
{
count++;
cout << "No. of Object created: " << count << endl;
}
~Test()
{
cout << "No. of Object destroyed: " << count
<< endl;
--count;
}
};
// driver code
int main()
{
Test t, t1, t2, t3;
return 0;
}
Output
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1
Characteristics of Destructors
The following are some main characteristics of destructors:
Destructor is invoked automatically by the compiler when its corresponding constructor
goes out of scope and releases the memory space that is no longer required by the
program.
Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
Destructor cannot be declared as static and const;
Destructor should be declared in the public section of the program.
Destructor is called in the reverse order of its constructor invocation.
Properties of Destructor
The following are the main properties of Destructor:
The destructor function is automatically invoked when the objects are destroyed.
It cannot be declared static or const.
The destructor does not have arguments.
It has no return type not even void.
An object of a class with a Destructor cannot become a member of the union.
A destructor should be declared in the public section of the class.
The programmer cannot access the address of the destructor.
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
2. Explicit Type Conversion: This process is also called type casting and it is user
defined. Here the user can typecast the result to make it of a particular data type.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
// C++ program to demonstrate explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
return 0;
}
Output:
Sum = 2
Conversion using Cast operator:
A Cast operator is an unary operator which forces one data type to be converted
into another data type.
Example
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
// using cast operator
int b = static_cast<int>(f);
cout << b;
}
Output:
3