Unit 1.3
Unit 1.3
It is a member function
having same name as it’s
class and Why
which is used to initialize The purpose of constructor is to
the objects of that class initialize the object of a class while
type with a the purpose of a method is to
legal initial value. perform a task by executing java
Constructor is code. Constructors cannot be
automatically called when abstract, final, static and
object is created. synchronised while methods can
be. Constructors do not have
return types while methods do.
1
CONTENT
S
• Need for Constructors
• Types of Constructors
6
Construc
• A constructor is a member function of a class which initializes objects of a
tor
class. In C++, Constructor is automatically called when object(instance of
class) create. It is special member function of the class.
Syntax of Constructor:-
class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
3
How constructors are different from a normal member
function?
• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• If we do not specify a constructor, C++ compiler generates a default constructor for us
(expects no parameters and has an empty body).
4
Types of Constructors
1) Default Constructors:
Default constructor is the constructor which doesn’t take any argument. It has no parameters.
#include <iostream> int main()
using namespace std; {
// Default constructor called automatically
class construct // when the object is created
{ construct c;
public: cout << "a: " << c.a << endl
int a, b; << "b: "
<< c.b;
// Default Constructor return 1;
construct() }
{ Output:-
a = 10; a: 10
b = 20; b: 20
}
}; Note: Even if we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly. 9
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.
class Point
{
private:
int x, y;
6
public:
int main()
// Parameterized Constructor
{
Point(int x1, int y1)
// Constructor called
{
Point p1(10, 15);
x = x1;
y=
// Access values assigned by constructor
y1;
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
}
int getX()
return 0;
{
}
return x;
}
int getY()
Output:
{
return y;
p1.x = 10, p1.y = 15
}
};
7
3) 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. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy
Constructor to all the classes.
As it is used to create an object, hence it is called a constructor. And, it creates a new object,
which is exact copy of the existing copy, hence it is called copy constructor.
8
#include<iostream> void display()
using namespace std; {
class cout<<x<<" "<<y<<endl;
copyconstructor }
{ };
private: /* main function */
int x, y; //data int main()
members {
copyconstructor obj1(10, 15); // Normal constructor
public: copyconstructor obj2 = obj1; // Copy constructor
copyconstructor(in cout<<"Normal constructor : ";
t x1, int y1) obj1.display();
{ cout<<"Copy constructor : ";
x = x1; obj2.display();
y = constructor */
/* Copy return 0;
y1;
copyconstructor (copyconstructor &sam) }
}{ Output:-
x = sam.x;
y= Normal constructor : 10 15
sam.y; Copy constructor : 10 15
} 9
Shallow Copy Constructor
Shallow copy copies references to original objects. The compiler provides a default copy constructor. Default copy
constructor provides a shallow copy. It is a bit-wise copy of an object.
Shallow copy constructor is used when class is not dealing with any dynamically allocated memory.
Example:-
10
void display()
#include<string>
{
using namespace std;
cout<<s_copy<<endl;
class CopyConstructor
}
{
};
char *s_copy;
/* main function */
public:
int main()
CopyConstructor(const char *str)
{
{
CopyConstructor c1("Copy");
//Dynamic memory allocation
CopyConstructor c2 = c1; //Copy constructor
s_copy = new char[16];
c1.display();
strcpy(s_copy, str);
c2.display();
}
c1.concatenate("Constructor") //c1 is invoking concatenate()
/* concatenate method */
; c1.display();
void concatenate(const char
c2.display();
*str)
return 0;
{
}
//Concatenating two strings
strcat(s_copy, str);
}
Output:-
Copy
/* copy constructor */
CopyConstructor
~CopyConstructor ()
{
CopyConstructo
delete [] s_copy; 15
r
Deep Copy Constructor
Deep copy allocates separate memory for copied information. So the source and copy are different. Any
changes made in one memory location will not affect copy in the other location. When we allocate dynamic
memory using pointers we need user defined copy constructor. Both objects will point to different memory
locations.
Example:-
16
~CopyConstructor()
#include<iostream> {
#include<string.h> delete [] s_copy;
using namespace std; }
class CopyConstructor
{ void display()
char *s_copy; {
public: cout<<s_copy<<endl;
CopyConstructor }
(char *str) };
{ /* main function */
//Dynamic memory alocation int main()
s_copy = new char[16]; {
strcpy(s_copy, str); CopyConstructor c1("Copy");
} CopyConstructor c2 = c1; //copy constructor
CopyConstructor c1.display();
(CopyConstructor &str) c2.display();
{ c1.concatenate("Constructor"); //c1 is invoking concatenate()
//Dynamic memory alocation c1.display();
s_copy = new char[16]; c2.display(); Output:-
strcpy(s_copy, str.s_copy); return 0; Copy
} } CopyConstructor
void concatenate(char *str) Copy
{ 17
Destruct
ors
Destructor is a special class function which destroys the object as soon as
the scope of object ends. The destructor is called automatically by the
compiler when the object goes out of scope.
Syntax for destructor
The class name is used for the name of destructor, with a tilde ~ sign as
prefix to it.
class A
{
Note:-
public:
// defining destructor for class Destructors will never have any arguments.
~A()
{
// statement
} 18
};
Example to see how Constructor and
Destructor are called
int main()
class A {
{ A obj1; // Constructor Called
// constructor int x = 1
A() if(x) Output:-
{ { Constructor called
cout << "Constructor called"; A obj2; // Constructor Called Constructor
} } // Destructor Called for obj2 called Destructor
} // Destructor called for obj1 called Destructor
// destructor called
~A() When an object is created the constructor of that class is called. The
{ object reference is destroyed when its scope ends, which is generally
cout << "Destructor called"; after the closing curly bracket } for the code block in which it is created.
}
}; The object obj2 is destroyed when the if block ends because it was
created inside the if block. And the object obj1 is destroyed when
the main() function ends.
15
What
Destructor is a special
member function that
works just opposite to Why
constructor, Destructors usually used to de-
unlike constructors that are
allocate memory and do other clean-up
are used for initializing an for a class object and its class members
object, destructors when the object is destroyed. A
destructor is called for a class object
destroy (or delete) the
when that object passes out of scope or
object. is explicitly deleted.
16
CONTENT
S
• Destructors and its needs
• Order of execution
21
Destructors and its needs
Destructor is a special class function which destroys the object as soon as
the scope of object ends. The destructor is called automatically by the
compiler when the object goes out of scope.
Syntax for destructor
The class name is used for the name of destructor, with a tilde ~ sign as
prefix to it.
class A
{
public: Note:-
// defining destructor for class
Destructors will never have any arguments.
~A()
{
// statement
}
}; 22
Example to see how Constructor and Destructor are called
int main()
class A {
{ A obj1; // Constructor Called
// constructor int x = 1
A() if(x) Output:-
{ { Constructor called
cout << "Constructor called"; A obj2; // Constructor Called Constructor
} } // Destructor Called for obj2 called Destructor
} // Destructor called for obj1 called Destructor
// destructor called
~A()
When an object is created the constructor of that class is called. The
{
object reference is destroyed when its scope ends, which is generally
cout << "Destructor called";
after the closing curly bracket } for the code block in which it is created.
}
};
The object obj2 is destroyed when the if block ends because it was
created inside the if block. And the object obj1 is destroyed when
the main() function ends.
19
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.
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.
20
Order of Execution of constructor and destructor
21
Example 1
#include<iostream>
using namespace std; int main()
{
class parent //parent class
{ parent c;
public: //automatically executes
parent() //constructor //parent class
{ //constructors and destructors
cout<<"Parent class Constructor\n"; // because of inheritance
}
return 0;
~parent()//destructor }
{
cout<<"Parent class Destructor\n"; Output:-
} Parent class Constructor
}; Parent class Destructor
22
Example 2 using Inheritance
#include<iostream> class child : public parent//child class
using namespace std; { int main()
{
class parent//parent class public:
{ child() //constructor child c;
public: { //automatically executes both
parent()//constructo cout<<"Child class Constructor\n"; //child and parent class
r } //constructors and destructors
{ // because of inheritance
cout<<"Parent class ~ child() //destructor
Constructor\n"; { return 0;
}~parent()//destructor cout<<"Child class Destructor\n"; }
{ }
cout<<"Parent class Destructor\n"; }; Output:-
} Parent class Constructor
}; Child class Constructor
Child class Destructor
Parent class Destructor 27
Summary
28