0% found this document useful (0 votes)
54 views36 pages

UNIT 3 OOP Notes

Unit 3 of object oriented programming notes handwriting notes oop for programming and programming fundamentals

Uploaded by

sammholder547
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)
54 views36 pages

UNIT 3 OOP Notes

Unit 3 of object oriented programming notes handwriting notes oop for programming and programming fundamentals

Uploaded by

sammholder547
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/ 36

Unit-3

Classes and objects in C++:


Types of classes and its use
What are classes?
A class is a user-defined data type. It holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.

// C++ program to demonstrate


// declaration of classes
#include <bits/stdc++.h>
using namespace std;
class OpenGenus
{
public: // Access specifier
string str; // Data Members
void printheading() // Member Functions()
{
cout << "This article describes the: " << str;
}
};
int main()
{
OpenGenus obj; // Declaring an object of class OpenGenus
obj.str = "Types Of Classes"; // Initializing data member
// accessing member function
obj.printheading();
return 0;
}

Types of classes
There are four distinct types of classes which are differentiated based on implementation.
They are:
 Stand Alone Classes
 Base Classes
 Derived Classes
 Friend Classes
There are six distinct types of classes which are differentiated based on definition and use.
They are:
 Stand Alone Classes
 Base Classes
 Abstract Base Class
 Concrete Base Class
 Derived Classes
 Abstract Derived Class
 Concrete Derived Class
 Friend Classes
Let us see what each type is in brief.
Stand Alone Classes
As the name suggests, these classes are neither child classes (i.e they are not derived out of
any classes) nor are they parent classes (i.e they do not act as a base class)

Stand Alone Classes

Object of the class


// C++ program to demonstrate
// stand-alone classes
#include <bits/stdc++.h>
using namespace std;
class StandAlone
{
public: // Access specifier
string str; // Data Members
void printheading() // Member Functions()
{
cout << "This section of the article describes the: " << str;
}
};
int main() {
StandAlone obj; // Declaring an object of class OpenGenus
obj.str = "Stand alone classes"; // Initializing data member
// accessing member function
obj.printheading();
return 0;
}

Concrete Base Classes and Concrete Derived Classes


A concrete class has well defined member functions. Their functions are not virtual or pure
virtual.A concrete bases class, as the name suggests, is a class which has well defined data
members and functions and acts as a base for another class to derive from. A concrete derived
class is a concrete class which is derived from the existing base class. It inherits the
properties of the base class.
In the above diagram, notice that the base class Animal has well defined member functions (
eat(), sleep(), move() ). These functions are common to all animals. This class can also be
used as a stand alone class. The concrete derived classes are dog and cat. They inherit the
data members and functions of the base class animal.

#include <iostream>
using namespace std;
// Concrete Base Class
class Base {
public:
int a;
};
// Concrete Derived Class
class Derived : public Base {
public:
int b;
};
// Driver Code
int main()
{
Derived obj;// Initialise an object of derived class
obj.b = 3;// Assign value to Derived class variable
obj.a = 4; // Assign value to Base class variable via derived class
cout << "Value from derived class: "<< obj.b << endl;
cout << "Value from base class: "<< obj.a << endl;
return 0;
}

Output:
Value from derived class: 3
Value from derived class: 4
Differences between Concrete Base class and Concrete Derived class

CONCRETE BASE CLASS CONCRETE DERIVED CLASS

Helps to derive or create new classes Derived out of base class

Also called parent class Also called child class

Cannot inherit properties and methods of Can inherit properties and methods of
child class parent class

Can be used as stand-alone class Cannot be used as a stand-alone class

Abstract Base Classes and Abstract Derived Classes


Before we dive into the definition of the class, let us first understand what virtual functions
and pure virtual functions are:
Virtual functions
Need for virtual functions:
Consider the example given below which has a concrete base and concrete derived class:

#include <iostream>
using namespace std;
class A //concrete base class
{
int x=10;
public:
void display()
{
cout << "Value of x is : " << x<<endl;
}
};
class B: public A //concrete derived class
{
int y = 15;
public:
void display()
{
cout << "Value of y is : " <<y<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display();
return 0;
}

In the program above, the output is: Value of x is : 10.


a is the concrete base class pointer. * a can only access the base class data members but not
the members of the derived class. Although C++ permits the base pointer to point to any
object derived from the base class, it cannot directly access the members of the derived class.
Therefore, there is a need for a special type of function which allows the base pointer to
access the members of the derived class. this type of function is called as a virtual function.
An example for virtual functions:

#include <iostream>
using namespace std;
class A //concrete base class
{
int x=10;
public:
virtual void display()
{
cout << "Value of x is : " << x<<endl;
}
};
class B: public A //concrete derived class
{
int y = 15;
public:
void display()
{
cout << "Value of y is : " <<y<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display();
return 0;
}
C++
Copy

In the above example, the output is: Value of y is : 15


Pure Virtual functions
Need for pure virtual functions:
A pure virtual function (or a "do-nothing" function) is not used for performing any task.A
pure virtual function is a function declared in the base class that has no definition in the base
class. The below example shows a pure virtual function.

virtual void show() = 0;


C++
Copy

Abstract base class


A class containing the pure virtual function cannot be used to declare the objects of its own
.Such classes are known as abstract base classes.
The main objective of the abstract base class is to provide the features to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.
Abstract derived class
A class which is derived from an abstract base class is called as an abstract derived class.The
main objective of the abstract derived class is to inherit the features of the abstract base class.
The remaining functions are all virtual functions. It is still an abstract class and hence objects
of the class cannot be defined.
Note: The derived class is abstract only if its member functions are virtual.

In the above diagram, arithmetic operations is an abstract base class with pure virtual
functions add(), subtract(), multiply() , divide(). It references integer, matrix and other
operations derived classes.
The reason for this implementation is that although we can perform the same 4 arithmetic
operations on both integers and matrices, the definition for the operations differ for both
classes. Since the four functions add(), subtract(), multiply() , divide() are overwritten in
integers and multiply, they are concrete derived classes
In the derived class, other operations, the four base pure virtual functions are not overwritten
although it is derived out of Operations class. Rather other virtual functions are introduced.
Therefore Other Operations is an abstract derived class and an object of this class cannot be
created.
An example to show the working of abstract classes

#include <iostream>
using namespace std;
class A //abstract base class
{
public:
virtual void show() = 0; //pure virtual function
};

class B : public A // derived class


{
public:
void show()
{
cout << "This is the derived class" << endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->show();
return 0;
}
C++
Copy

Output: This is the derived class


Differences between Abstract Base class and Abstract Derived class

ABSTRACT BASE CLASS ABSTRACT DERIVED CLASS

Helps to derive or create new classes Derived out of base class

Also called parent class Also called child class

This class contains pure virtual functions This class contains virtual functions

Let us consider an example to understand the differences between abstract and concrete
derived classes.

class abstract_base {
public:
virtual void abstract_method1() = 0;
virtual void abstract_method2() = 0;
};

class concrete_base {
public:
void concrete_method1() {
/* random code */
}
};
class abstract_derived1 : public abstract_base {
public:
virtual void abstract_method3() = 0;
};
class abstract_derived2 : public concrete_base {
public:
virtual void abstract_method3() = 0;
};
class abstract_derived3 : public abstract_base {
public:
virtual abstract_method1() {
/* random code */
}
};
class concrete_derived1 : public concrete_base {
public:
virtual void abstract_method1() {
/* random code */
}
virtual void abstract_method2() {
/* random code */
}
/* This class is now concrete because no abstract methods remain */
};
class example : public abstract_base {
public:
virtual void abstract_method2() {
/* random code */
}
};
C++
Copy

Note that we do not provide an implementation for abstract_method1 and abstract_method2,


so the abstract_derived classes are still abstract and objects of this class cannot be created.
Friend Classes
Need for friend classes
Data encapsulation is an important concept of object-oriented programming. It restricts the
access of private members from outside of the class.
Similarly, protected members can only be accessed by derived classes and are inaccessible
from outside. For example,

class A {
private:
int num;
}
int main() {
A obj;
A.num = 5;// Private data members cannot be accessed from here
}
C++
Copy

Friend Functions
A friend function can access the private and protected data of a class. We declare a friend
function using the friend keyword inside the body of the class. Below is an example of a
friend functions

class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
C++
Copy

Similar to friend functions, We can also use a friend Class in C++ using the friend keyword.
For example,

class ClassFriend;
class ClassA {
// ClassFriend is a friend class of ClassA
friend class ClassFriend;
... .. ...
}
class ClassFriend {
... .. ...
}
C++
Copy
When a class is declared a friend class, all the member functions of the friend class become
friend functions.Since ClassFriend is a friend class, we can access all members of ClassA
from inside ClassFriend.
Note: We cannot access members of ClassFriend from inside ClassA. It is because friend
relation in C++ is only given, not taken.
An example depicting the use of friend class

#include <iostream>
using namespace std;
class Square
{
protected:
int side;
friend class Rectangle;
public:
Square (int s) // parameterised constructor
{
side = s;
}
};
class Rectangle{
int length;
int breadth;
public:
int getArea(){
return length*breadth;
}
void shape(Square a){
length = a.side;
breadth = a.side;
}
};
int main(){
Square square(5);
Rectangle rectangle;
rectangle.shape(square);
cout<<rectangle.getArea()<<endl;
return 0;
}
C++
Copy

Output: 25
In the above program, Rectangle is the friend function of the class Square. side is a protected
member of the class Square. It is accessed by Rectangle. When square(5) object of class
Square is created, side is initialized to 5. Then we create object rectangle of class Rectangle.
It then accesses side of Square and initializes length and breadth to 5. When function
getArea() is called, length * breadth = 25 is returned.
What is an Object in C++?
A class is merely a blueprint of data. An object is a data structure that is an instance of a
class. So when a class is created no memory is allocated but when an instance is created by
declaring an object, memory is then allocated to store data and perform required functions on
them. We can visualize trees, birds, and dogs as different classes and their instances like
neem tree, peacock, and german shepherd dog respectively. Hence, class and object
in C++ are the main ingredients of object-oriented programming.
Declaring Objects in C++
When a class is defined only the blueprint of data structure is defined as no memory is
allocated. To use data and its member function we can declare objects. We can declare
objects by mentioning the class followed by the user-defined object name.
Syntax:
Class ObjectName;
Example:
Dog d;
Significance of Class and Object in C++
The concept of class and object in C++ allows real-life analogies to be included in the
programming. Using classes, data is given the highest importance. The following are some of
the significant points to keep in mind:
 Data hiding: Using access specifiers, a class stops data from being accessed from the
outside world. Classes have the ability to set permissions to limit who has access to
the data.
 Code Reusability: With the aid of inheritance, you may reduce code redundancy by
employing reusable code. Similar functionality and features can be inherited by other
classes, making the code cleaner.
 Data binding: The data elements and their associated operations are bonded together
under one umbrella, increasing the data's security.
 Flexibility: The principle of polymorphism allows you to use a class in a variety of
ways. This increases the flexibility of a program.
Array of Objects
An array in C++ is a collection of data stored in contagious memory locations in the memory.
An array can be of int, string, or char as well as of some derived data types like structures,
pointers, etc. An array of objects is a collection of objects of some class type.
We can declare an array of objects by providing the total number of objects in closed brackets
after the object name.
Syntax:
ClassName ObjectName[number of objects];
Example:
Dog dog[5]; //array of 5 objects of class Dog
Objects as Function Arguments
To pass an object to a function we pass the object in the same way as we pass any other
primitive data(int, string, etc). We just mention the object in the function's argument and call
the function. Syntax:
function_name(object_name);
Example: Here, we are printing all the properties(breed, color) of object dog by passing it
to printProperties() function.
printProperties(Dog dog)
{
cout<<dog.breed<<" "<<dog.color<<endl;
}
void main {
Dog dog;
dog.breed="Pug"; // we access data members by putting '.'
//after object name followed by data member.
dog.color="Brown"
printProperties(dog);
}
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor
in C++ has the same name as the class or structure. Constructor is invoked at the time of
object creation. It constructs the values i.e. provides data for the object which is why it is
known as constructors.
• Constructor is a member function of a class, whose name is 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 constructor.
• Constructor do not return value, hence they do not have a return type.
The prototype of the constructor looks like
<class-name> (list-of-parameters);
Constructor can be defined inside the class declaration or outside the class declaration
a. Syntax for defining the constructor within the class
<class-name>(list-of-parameters)
{
//constructor definition
}
b. Syntax for defining the constructor outside the class
<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}
// Example: defining the constructor within the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
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;
}
// Example: defining the constructor outside the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s;
s.display();
return 0;
}
Characteristics of constructor
• The name of the constructor is same as its class name.
• Constructors are mostly declared in the public section of the class though it 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.
• Constructor can not be declared virtual.
Types of constructor
• Default constructor
• Parameterized constructor
• Overloaded constructor
• Constructor with default value
• Copy constructor
• Inline constructor
Constructor does not have a return value, hence they do not have a return type.
The prototype of Constructors is as follows:
<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-
The syntax for defining the constructor within the class:
<class-name> (list-of-parameters) { // constructor definition }
The syntax for defining the constructor outside the class:
<class-name>: :<class-name> (list-of-parameters){ // constructor definition}
Example

 C++

// defining the constructor within the class


#include <iostream>
using namespace std;
class student {
int rno;
char name[10];
double fee;
public:
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:Enter the Name:Enter the Fee:
0 6.95303e-310
Example

 C++

// defining the constructor outside the class


#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
int main()
{
student s;
s.display();
return 0;
}

Output:
Enter the RollNo: 30
Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
How constructors are different from a normal member function?

#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line( double len ); //This is the constructor
private:
double length;
};
//Member function definition including constructor
Line::Line( double len ) {
cout<<"Object is being created , length ="<< len <<endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
//Main function for the program
int main() {
Line line(10.0);
//get initially set length
cout<<"Length of line :" << line.getLength() << endl;
//set line length again
line.setLength(6.0);
cout<<"Length of line :" << line.getLength() << endl;
return 0;
}

A constructor is different from normal functions in following ways:


 Constructor has same name as the class itself
 Default Constructors don’t have input argument however, Copy and Parameterized
Constructors have input arguments
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 It must be placed in public section of class.
 If we do not specify a constructor, C++ compiler generates a default constructor for
object (expects no parameters and has an empty body).

Let us understand the types of constructors in C++ by taking a real-world example.


Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the
options. The first one you go to a shop and say give me a marker. So just saying give me a
marker mean that you did not set which brand name and which color, you didn’t mention
anything just say you want a marker. So when we said just I want a marker so whatever the
frequently sold marker is there in the market or in his shop he will simply hand over that.
And this is what a default constructor is! The second method is you go to a shop and say I
want a marker a red in color and XYZ brand. So you are mentioning this and he will give
you that marker. So in this case you have given the parameters. And this is what a
parameterized constructor is! Then the third one you go to a shop and say I want a marker
like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay,
and he will give a new marker for you. So copy of that marker. And that’s what a copy
constructor is!
Characteristics of the constructor:
 The name of the constructor is the same as its class name.
 Constructors are mostly declared in the public section of the class though it 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.
 Constructor can not be declared virtual.
 Constructor cannot be inherited.
 Addresses of Constructor cannot be referred.
 Constructor make implicit calls to new and delete operators during memory allocation.
Types of Constructors
1. Default Constructors: Default constructor is the constructor which doesn’t take any
argument. It has no parameters. It is also called a zero-argument constructor.
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;
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
// Example
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student() // Explicit Default constructor
{
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;
s.display();
return 0;
}
2. Parameterized Constructors: It is 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.
// CPP program to illustrate
// parameterized constructors
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX() { return x; }
int getY() { return y; }
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
return 0;
}
Output
p1.x = 10, p1.y = 15

// Example
#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
void display();
};
student::student(int no,char n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s(1001,"Ram",10000);
s.display();
return 0;
}
When an object is declared in a parameterized constructor, the initial values have to be
passed as arguments to the constructor function. The normal way of object declaration may
not work. The constructors can be called explicitly or implicitly.
Example e = Example(0, 50); // Explicit call
Example e(0, 50); // Implicit call
 Uses of Parameterized constructor:
1. It is used to initialize the various data elements of different objects with different
values when they are created.
2. It is used to overload constructors.
 Can we have more than one constructor in a class?
Yes, It is called Constructor Overloading.
3. Copy Constructor:
A copy constructor is a member function that initializes an object using another object of
the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class, a
default constructor( without parameters ) should also be explicitly defined as the compiler
will not provide a default constructor in this case. However, it is not necessary but it’s
considered to be the best practice to always define a default constructor.
Copy constructor takes a reference to an object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}

// Illustration
#include <iostream>
using namespace std;
class point {
private:
double x, y;
public:
// Non-default Constructor &
// default Constructor
point(double px, double py) { x = px, y = py; }
};
int main(void)
{
// Define an array of size
// 10 & of type point
// This line will cause error
point a[10];
// Remove above line and program
// will compile without error
point b = point(5, 6);
}
Output:
Error: point (double px, double py): expects 2 arguments, 0 provided
// Implicit copy constructor
#include<iostream>
using namespace std;
class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1;
obj2.display();
return 0;
}
Output
ID=10
ID=10
// Example: Explicit copy constructor
#include <iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body
Sample(Sample &t) //copy constructor
{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
return 0;
}
Output
ID=10
ID=10

#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor
{
rno=t.rno;
strcpy(name,t.name);
fee=t.fee;
}
void display();
};
student::student(int no,char n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s(1001,"Manjeet",10000);
s.display();

student manjeet(s); //copy constructor called


manjeet.display();
return 0;
}

 C++

#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor (member wise initialization)
{
rno=t.rno;
strcpy(name,t.name);
}
void display();
void disp()
{
cout<<endl<<rno<<"\t"<<name;
}
};
student::student(int no, char n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s(1001,"Manjeet",10000);
s.display();
student manjeet(s); //copy constructor called
manjeet.disp();
return 0;
}

Destructor:
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.
The syntax for defining the destructor within the class
~ <class-name>()
{
}
The syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>(){}

 C++

#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }
~Test() { cout << "\n Destructor executed"; }
};
main()
{
Test t;
return 0;
}

Output
Constructor executed
Destructor executed

 C++

#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }
~Test() { cout << "\n Destructor executed"; }
};

main()
{
Test t, t1, t2, t3;
return 0;
}

Output
Constructor executed
Constructor executed
Constructor executed
Constructor executed
Destructor executed
Destructor executed
Destructor executed
Destructor executed

 C++

#include <iostream>
using namespace std;
int count = 0;
class Test {
public:
Test()
{
count++;
cout << "\n No. of Object created:\t" << count;
}
~Test()
{
cout << "\n No. of Object destroyed:\t" << count;
--count;
}
};

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 a destructor:-
1. 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.
2. Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation.

You might also like