Lecture 1 Constructor
Lecture 1 Constructor
Course Objectives
2
Course Outcomes
CO Title Level
Number
Sr. Type of Assessment Weightage of actual Frequency of Task Final Weightage in Internal Remarks
No. Task conduct Assessment (Prorated
Marks)
6
Constructor
• A constructor is a member function of a class which initializes objects of a 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
}
};
7
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).
8
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;
return 1;
// Default Constructor }
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;
10
public:
int main()
// Parameterized Constructor
{
Point(int x1, int y1)
// Constructor called
{
Point p1(10, 15);
x = x1;
y = y1;
// Access values assigned by constructor
}
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
}
};
11
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.
12
#include<iostream> void display()
using namespace std; {
class copyconstructor cout<<x<<" "<<y<<endl;
{ }
private: };
int x, y; //data members /* main function */
int main()
public: {
copyconstructor(int x1, int y1) copyconstructor obj1(10, 15); // Normal constructor
{ copyconstructor obj2 = obj1; // Copy constructor
x = x1; cout<<"Normal constructor : ";
y = y1; obj1.display();
} cout<<"Copy constructor : ";
obj2.display();
/* Copy constructor */ return 0;
copyconstructor (copyconstructor &sam) }
{ Output:-
x = sam.x;
y = sam.y; Normal constructor : 10 15
} Copy constructor : 10 15
13
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:-
14
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 *str)
c2.display();
{
return 0;
//Concatenating two strings
}
strcat(s_copy, str);
}
/* copy constructor */
Output:-
Copy
~CopyConstructor ()
CopyConstructor
{
CopyConstructor
delete [] s_copy;
} 15
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) }
{ };
//Dynamic memory alocation /* main function */
s_copy = new char[16]; int main()
strcpy(s_copy, str); {
} CopyConstructor c1("Copy");
CopyConstructor (CopyConstructor &str) CopyConstructor c2 = c1; //copy constructor
{ c1.display();
//Dynamic memory alocation c2.display();
s_copy = new char[16]; c1.concatenate("Constructor"); //c1 is invoking concatenate()
strcpy(s_copy, str.s_copy); c1.display();
} c2.display(); Output:-
void concatenate(char *str) return 0; Copy
{ } CopyConstructor
strcat(s_copy, str); //Concatenating two strings Copy
} 17
Destructors
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 called
} } // Destructor Called for obj2 Destructor called
} // Destructor called for obj1 Destructor called
// destructor
~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
Summary
20
Frequently Asked question
Q1 What is the use of a constructor?
Constructor is a special function having same name as class name. Constructor is called at
the time of creating object to your class. Constructor is used to initialize the instance
variables of an object while creating it. Constructor is also used to create virtual tables for
virtual functions.
First base class constructor is executed and then derived class constructor, so execution
happens from top to bottom in inheritance tree.
21
Q3 What is the order of destructor execution in C++?
Generally derived class destructor, and then base class destructor. Except in
case if we are taking a derived class object into a base class pointer (or
reference variable), and we forget to give virtual keyword for base class
destructor. See virtual destructor for details.
a) Because user may forget to call init() using that object leading segmentation fault
b) Because user may call init() more than once which leads to overwriting values
c) Because user may forget to define init() function
d) All of the mentioned
a) A constructor that allows a user to move data from one object to another
b) A constructor to initialize an object with the values of another object
c) A constructor to check the whether to objects are equal or not
d) A constructor to kill other copies of a given object.
23
3. What happens if a user forgets to define a constructor inside a class?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a default constructor to avoid faults/errors
4. How constructors are different from other member functions of the class?
24
5. State whether the following statements about the constructor are True or False.
i) constructors should be declared in the private section.
ii) constructors are invoked automatically when the objects are created.
A. True,True
B. True,False
C. False,True
D. False,False
6. Destructors __________ for automatic objects if the program terminates with a call to function exit
or function abort
A. Are called
B. Are not called
C. Are inherited
D. Are created
25
Discussion forum.
Order of Execution of Constructors and Destructors in Inheritance in C+
+?
https://www.youtube.com/watch?v=fCK7sLu0G0Y
26
REFERENCES
Reference Books
[1] Programming in C++ by Reema Thareja.
[2] Programming in ANSI C++ by E. Balaguruswamy, Tata McGraw Hill.
[3] Programming with C++ (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
Websites:
https://en.wikipedia.org/wiki/Constructor_(object-oriented_programm
ing)
https://www.programiz.com/cpp-programming/constructors
https://en.wikipedia.org/wiki/Destructor_(computer_programming)
YouTube Links:
What is Constructor? https://www.youtube.com/watch?
v=q7aWkjH3UUI
What is destructor?
https://www.youtube.com/watch?v=D8cWquReFqw 27
THANK YOU