Object Oriented Programming (OE-EC604C)
DEPT- ECE, 6TH SEM
SYLLABUS:
Constructors - default constructor, parameterized constructor, constructor with dynamic
allocation, copy constructor, destructors.
A constructor in C++ is a special 'MEMBER FUNCTION' having the same name as that of
its class which is used to initialize some valid values to the data members of an object. It
is executed automatically whenever an object of a class is created.
NOTE: Constructor does not have a return value, hence they do not have a return type.
Syntax for defining the constructor within the class
<class-name>(list-of-parameters)
{
//constructor definition
}
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.
Purpose of constructor:
In C++, constructors are special member functions that are automatically called when an
object of a class is created. Their main purpose is to initialize the object's data members
and prepare the object for use. Constructors can be used to set default values, allocate
memory, and perform other initialization tasks. They play a crucial role in the process of
creating and initializing objects in C++ classes.
// 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;
Types of constructor:
• Default constructor
• Parameterized constructor
• Copy constructor
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.
Syntax of default constructor:
<class_name>()
{
….………
}
//Example
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
Output
// Default constructor called automatically
a: 10
// when the object is created b: 20
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
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.
// 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
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:
It is used to initialize the various data elements of different objects with different values
when they are created.
It is used to overload constructors.
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;
}
// 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
Overloaded constructor: In C++, We can have more than one constructor in a class with
same name, as long as each has a different list of arguments.This concept is known as
Constructor Overloading and is quite similar to function overloading.
Overloaded constructors essentially have the same name (exact name of the class) and
different by number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
// Constructor overloading
#include <iostream>
using namespace std;
class construct
{
public:
float area;
// Constructor with no parameters
construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}
void disp()
{
cout<< area<< endl;
}
};
int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);
o.disp();
o2.disp();
return 1;
}
Output:
0
200
Constructor with dynamic allocation:
When allocation of memory is done dynamically using dynamic memory allocator new in
a constructor, it is known as dynamic constructor. By using this, we can dynamically
initialize the objects.
#include <iostream>
using namespace std;
class geeks {
const char* p;
public:
// default constructor
geeks()
{
// allocating memory at run time
p = new char[6];
p = "SOURAV BANIK";
}
void display() { cout << p << endl; }
};
int main()
{
geeks obj;
obj.display();
}
Output
SOURAV BANIK
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>(){}
#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
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.
QUESTIONS WITH ANSWER
What is a constructor?
A constructor is a function of a class that has the same name as the class. The constructor
is called at the time of the initialization of object.
There are three types of constructors −
Default constructor
Parameterized constructor
Copy constructor
Syntax
class cl_name{
cl_name(){
//This is constructor..
}
}
What is a destructor?
A destructor is a method of a class that has the same name as the class preceded by a tild
~ symbol. It is called at the end of code or when the object is destroyed or goes out of
scope.
Syntax
class cl_name{
~ cl_name(){} //destructor
}
What is the use of constructor?
A constructor is a method that has the same name as a class. And the use of a constructor
is to initialize the object when it is created using a new keyword.
When an object is created, the variables are initialized chunks of memory and base values
if there are any.
What is the use of destructor?
A destructor is a method that has the same name as a class preceding a ~ symbol. The use
of a destructor is to deallocate the memory chunks one the code goes out of the scope of
the object or deleted using the delete keyword.
When the object is deleted the destructor is called and it deallocated all the memory
blocks that were created when an object was created.
What is the order of constructor execution in C++?
A constructor is invoked when the object of a class is created. The order in which a
constructor is invoked is the same as the hierarchy of the inheritance. This means that
first the object of a base class is invoked then the objects of the child class are invoked
and so on.
What is the order of destructor execution in C++?
A destructor is invoked in the reverse order as the constructor and is invoked when the
object of the class is deleted. The order in which a destructor is invoked is just the
opposite of the hierarchy of the inheritance. This means that first the object of child class
is destroyed then the objects of the parent class are destroyed and so on.
Is the default constructor created even if we create any other constructor?
Constructors are created by default by the compiler if a programmer doesn’t define any
constructor explicitly. If the programmer defines a constructor then compiler holds its
work and does not define any of it.
Define Copy Constructor.
If we have an object of a class and we want to create its copy in a new declared object of
the same class, then a copy constructor is used. The compiler provides each class a default
copy constructor and users can define it also. It takes a single argument which is an object
of the same class.
Syntax
class class_name{
private:
// private members
public:
// declaring copy constructor
class_name(const class_name& obj)
{
// constructor body
}
};
Define Dynamic Constructor.
When memory is allocated dynamically to the data members at the runtime using a new
operator, the constructor is known as the dynamic constructor. This constructor is similar
to the default or parameterized constructor; the only difference is it uses a new operator
to allocate the memory.
Syntax
class class_name{
private:
// private members
public:
// declaring dynamic constructor
class_name({parameters})
{
// constructor body where data members are initialized using new operator
}
};
Q. How Constructor and Destructor are called when the object is created and
destroyed.
As constructor is the first function called by the compiler when an object is created and
the destructor is the last class member called by the compiler for an object. If the
constructor and destructor are not declared by the user, the compiler defines the default
constructor and destructor of a class object.
Let’s see a code to get the proper idea of how constructor and destructor are called:
First, we will create a class with single parametrized constructors and a destructor. Both
of them contain print statements to give an idea of when they are called.
#include <iostream>
using namespace std;
class class_name{
// declaring private class data members
private:
int a,b;
public:
// declaring Constructor
class_name(int aa, int bb)
{
cout<<"Constructor is called"<<endl;
a = aa;
b = bb;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
cout<<endl;
}
// declaring destructor
~class_name()
{
cout<<"Destructor is called"<<endl;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of b: "<<b<<endl;
}
};
int main()
{
class_name obj(5,6);
return 0;
}
Output
Constructor is called
Value of a: 5
Value of b: 6
Destructor is called
Value of a: 5
Value of b: 6
In the above code, we have created a class with constructor and destructor. In the main
function, an object uses a parametric constructor, and when the program ends the
destructor is automatically called by the compiler and we get the values of our variables.
Q: What are the functions that are generated by the compiler by default, if we do not
provide them explicitly?
Ans: The functions that are generated by the compiler by default if we do not provide
them explicitly are:
I. Default constructor
II. Copy constructor
III. Assignment operator
IV. Destructor
Multiple Choice Questions & Answers (MCQs) focuses on “Constructors and Destructors”.
1. What is the role of a constructor in classes?
a) To modify the data whenever required
b) To destroy an object
c) To initialize the data members of an object when it is created
d) To call private functions from the outer world
2. What is a copy constructor?
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.
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 many parameters does a default constructor require?
a) 1
b) 2
c) 0
d) 3
5. How constructors are different from other member functions of the class?
a) Constructor has the same name as the class itself
b) Constructors do not return anything
c) Constructors are automatically called when an object is created
d) All of the mentioned
6. How many types of constructors are there in C++?
a) 1
b) 2
c) 3
d) 4
7. What is the role of destructors in Classes?
a) To modify the data whenever required
b) To destroy an object when the lifetime of an object ends
c) To initialize the data members of an object when it is created
d) To call private functions from the outer world
8. What is syntax of defining a destructor of class A?
a) A(){}
b) ~A(){}
c) A::A(){}
d) ~A(){};
9. When destructors are called?
a) When a program ends
b) When a function ends
c) When a delete operator is used
d) All of the mentioned
10. Which among the following is called first, automatically, whenever an object is created?
a) Class
b) Constructor
c) New
d) Trigger
11. Which among the following is correct?
a) class student{ public: int student(){} };
b) class student{ public: void student (){} };
c) class student{ public: student{}{} };
d) class student{ public: student(){} };
12. In which access should a constructor be defined, so that object of the class can be created in
any function?
a) Public
b) Protected
c) Private
d) Any access specifier will work
13. If class C inherits class B. And B has inherited class A. Then while creating the object of class
C, what will be the sequence of constructors getting called?
a) Constructor of C then B, finally of A
b) Constructor of A then C, finally of B
c) Constructor of C then A, finally B
d) Constructor of A then B, finally C
14. If the object is passed by value to a copy constructor?
a) Only public members will be accessible to be copied
b) That will work normally
c) Compiler will give out of memory error
d) Data stored in data members won’t be accessible
15. Which among the following helps to create a temporary instance?
a) Implicit call to a default constructor
b) Explicit call to a copy constructor
c) Implicit call to a parameterized constructor
d) Explicit call to a constructor
Fill in the blanks:
16. A constructor name is the same as....................
17. A constructor is executed automatically when an object is.....................
18. Destructor is executed....................at the end of the program.
19. A class can have any number of constructors but only.................... destructor at a time.
20. The name of the destructor function is same as that of class but preceded with a
symbol....................
21. The constructor which accepts value from outside is called.................... constructor.