0% found this document useful (0 votes)
40 views23 pages

Session 13

Constructor and destructor are special member functions of a class. Constructors initialize objects and allocate memory when an object is created. Destructors deallocate memory when an object is destroyed. Constructors are called automatically upon object creation while destructors are called automatically upon object destruction, such as when an object goes out of scope. A class can have multiple constructors but only one destructor with the same name as the class preceded by a tilde symbol.

Uploaded by

yadvji568
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)
40 views23 pages

Session 13

Constructor and destructor are special member functions of a class. Constructors initialize objects and allocate memory when an object is created. Destructors deallocate memory when an object is destroyed. Constructors are called automatically upon object creation while destructors are called automatically upon object destruction, such as when an object goes out of scope. A class can have multiple constructors but only one destructor with the same name as the class preceded by a tilde symbol.

Uploaded by

yadvji568
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/ 23

18CSC202J - OBJECT ORIENTED DESIGN

AND PROGRAMMING

Session 12

Topic : Constructor and Destructor


Constructor and Destructor
• Both constructors and destructors are the member function of the class.
• A constructor is a function that

– initializes the object of the class and allocates the memory location for an
object,
– the function has the name as the class name, known for creating the object,
called when the instance of the class created.
• Destructor also has the same name as the class name,

– denoted by tilted ~ symbol,


– known for destroying the constructor,

– deallocates the memory location for created by the constructor.


• One class can have more than one constructor but have one destructor.
• The destructor is called

– automatically by the compiler and


– gets executed whenever the object of that particular class goes out of
the scope or
– it is deleted by using delete expression to the pointer of that object.
• Whenever the object is destroyed by a compiler, the destructor is called.
• In destructor, we can execute statements which may be anything that we
want to perform when the object goes out of the scope.
Object Initialization
By Constructor

• Default constructor

• Copy constructor

• Constructor with parameters

4
Constructor
• It is a special kind of class member function that is automatically called when an
object of that class is instantiated.
• Constructors are typically used to initialize member variables of the class to
appropriate default or user-provided values.

Constructors have specific rules for how they must be named:


• Constructors must have the same name as the class (with the same capitalization).
• Constructors have no return type (not even void)

• The constructor is like normal function within the class and the compiler calls it
automatically when we create a new object of that class.

• The constructor is like a special member function of a class. Whenever we create a


new object the constructor is executed.
Constructors – Special
Characteristics
• They should be declared in the public section
• They are invoked automatically when the objects are created
• They do not have return types, not even void
• They cannot be inherited. But a derived class can call the base class
constructor
• They can have default arguments
• They cannot be virtual
• We cannot refer to their addresses
• An object with a constructor (or destructor) cannot be used as a member
of a union
• They make implicit calls to the operators new and delete when memory
allocation is required
Constructor
• Constructor can be defined either inside the class or outside of the class
using scope resolution operator ::
Example
class A
{
int a;
public:
A(); // constructor declaration
};
A::A() // constructor definition
{
a = 10;
}
7
Methods
• A method is a function that is part of the class definition. The methods of a class specify
how its objects will respond to any particular message.

• A method is a collection of statements that perform some specific task and return the
result to the caller. A method can perform some specific task without returning anything.

• Methods allow us to reuse the code without retyping the code.

• A message is a request, sent to an object, that activates a method (i.e., a member


function).

9
Method Vs Constructor
• Used to define particular task for
• Used to initialize the data members
execution
• Constructor has same name as the class
• Method can have same name as class name
name or different name based on the • Constructor is automatically called when
requirement an object is created

• Explicit call statement required to call a • There is always default constructor


provide by compiler
method
• Return type is not required in constructor
• There is no default method provided by

compiler

• Return data type must be declared


Example for default constructor:

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Parameterized Constructors
• A constructor that takes
arguments are called
parameterized constructors

• When an object is declared, we


must pass the initial values as
arguments to the constructor

• This can be done in two ways:

– By calling the constructor


explicitly

– By calling the constructor


implicitly
Parameterized Constructors -
Example
Example for constructor with parameter
Creating an
#include <iostream> object of
using namespace std; Employee
class Employee {
public: int main(void) {
int id;//data member (also instance Employee e1 =Employee(101, "Sonoo", 890000);
variable)
string name;//data member(also e2=Employee(102, "Nakul", 59000);
instance variable) e1.display();
float salary;
e2.display();
Employee(int i, string n, float s)
{ return 0;
id = i;
}
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<"
"<<salary<<endl;
}
};
Copy Constructor


Copy constructor:

• Copy Constructor is a type of constructor which is used to create a copy of an


already existing object of a class type.
• The compiler provides a default Copy Constructor to all the classes.

Copy Constructor is called in the following scenarios:

• 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 for copy constructor

#include <iostream> int main()


using namespace std; {
class A
{ A a1(20);
public: // Calling the parameterized
int x; constructor.
A(int a) // parameterized constructor
{ A a2(a1);
x=a; // Calling the copy constructor.
}
A(A &i) // copy constructor cout<<a2.x;
{ return 0;
x = i.x; }
}
};
Destructor:
• Destructors have the same name as their class and their name is preceded
by a tilde(~).
• Destructors in C++ are members functions in a class that delete an object.
• They are called when the class object goes out of scope such as when the
function ends, the program ends, a delete variable is called etc.
• Destructors are don’t take any argument and don’t return anything.
When does the destructor get called?

A destructor is automatically called when:


1) The program finished execution.
2) When a scope (the { } parenthesis) containing local variable ends.
3) When you call the delete operator.
Example program for destructor

Constructor #include <iostream>


using namespace std;
class HelloWorld
{ int main()
public: {
HelloWorld()
{ HelloWorld obj; //Object created
cout<<"Constructor is called"<<endl;
} obj.display(); //Member function called

~HelloWorld() return 0;
{ }
cout<<"Destructor is called"<<endl;
}
output
//Member function
void display() Constructor is called
{ Hello World!
cout<<"Hello World!"<<endl; Destructor is called
Destructor }
};
Destructor rules

1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any
parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a
default destructor and inserts it into your code.
Example Program
class Student // copy constructor
{ Student (const Student &s)
public: {
int rollno; rollno = s.rollno;
string name; name = s.name;
Student() //Default constructor }
{ rollno = 0; }; // end of class
name = "None";
} int main()
Student(int x) // parameterized {
{ rollno = x; Student A1();
name = "None"; Student A(10);
} Student B=A;
}

You might also like