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 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: 30Enter the Name: ramEnter the Fee: 2000030 ram 20000
How constructors are different from a normal member function?
C++
#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
// 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: 10b: 20
Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.
C++
// 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.
Note: when the parameterized constructor is defined and no default constructor is defined explicitly, the compiler will not implicitly call the default constructor and hence creating a simple object as
Student s;Will flash an error
CPP
// 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
C++
// 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:
- 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.
- 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; }
CPP
// 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
C++
// 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=10ID=10
C++
// 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=10ID=10
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
{
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.
Q: What are the functions that are generated by the compiler by default, if we do not provide them explicitly?
Ans: he 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
Related Articles :
- Destructors in C++
- quiz on constructors in C++
- Output of C++ programs | Set 26 (Constructors)
- Output of C++ programs | Set 27(Constructors and Destructors)
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
My Personal Notesarrow_drop_up
FAQs
What are the constructors in C++? ›
A constructor in C++ is a special method that is automatically called when an object of a class is created.
What are the 3 types of constructor? ›...
Let's learn about them.
- Default Constructor. ...
- Parameterized Constructor. ...
- Copy Constructor.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
What is the use of constructor? ›Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.
What are the 4 types of constructor? ›- Default Constructor.
- Parameterized Constructor.
- Copy Constructor.
- Static Constructor.
- Private Constructor.
In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure.
What is the difference between constructor and function in C++? ›A Constructor helps in initialising an object that doesn't exist. A Method performs functions on pre-constructed or already developed objects.
What is the syntax of constructor? ›A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
How many constructors can a class have? ›Explanation: A class can have any number of constructors. If a class have more than one constructor, we call it as the constructor is overloaded.
Can you have two constructors in C++? ›In c++, there are multiple constructors in a class under the same name but a different list of arguments. This concept of constructor overloading in c++ is quite similar to function overloading. Usually, you should create more than one constructor in a class to initialize member variables differently for objects.
How many constructors can an object have? ›
You can have 65535 constructors in a class(According to Oracle docs).
How do you overload a constructor? ›Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.
What is the advantages of constructor? ›These are the benefits of constructors. Automatic initialization of objects at the time of their declaration. Multiple ways to initialize objects according to the number of arguments passes while declaration. The objects of child class can be initialised by the constructors of base class.
What is constructor with example? ›A constructor in Java is similar to a method that is invoked when an object of the class is created. Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return type.
Can you override a constructor? ›It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
What are the 2 types of constructors? ›- Default constructor (no-arg constructor)
- Parameterized constructor.
Default constructor is created by compiler when the programmer doesn't write any constructor in the class. Parameterized constructor is specifically written by the programmer while creating a class.
What are the types of constructor in OOP? ›Constructors are of three types: Default Constructor. Parametrized Constructor. Copy COnstructor.
What happens if we don't use constructor in C++? ›If on the other hand you don't declare any constructor, the compiler will (must!) create a default constructor on your behalf. This is what happens with a POD class. In the case of a POD class, that automatically-generated constructor is not called under certain circumstances.
What is the difference between constructors and destructors? ›A constructor allows an object to initialize some of its value before it is used. A destructor allows an object to execute some code at the time of its destruction.
Why do you need two constructors? ›
That's the purpose for multiple constructors. To give the programmer flexibility on saying what an object can be created from and which variables need to be initialized in the first place.
What are the disadvantages of constructor in C++? ›In a default constructor, every object in the class is initialized to the same set of values. It is not possible to initialize different objects with different initial values. This is one of the disadvantages of a default constructor.
Is constructor a class or function? ›A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
Is it mandatory to use constructor in a class? ›Users do not need to write constructors for every class. A constructor can be declared using any of the access modifiers. It is mandatory to have a constructor with the right access modifier. However, the compiler supplies a default if an access modifier is not defined in the class and a constructor is not declared.
How constructor is executed? ›Constructors of Virtual base classes are executed, in the order that they appear in the base list. Constructors of nonvirtual base classes are executed, in the declaration order. Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
What is this () constructor? ›Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .
Can we call two constructors in a class? ›There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.
Does every class have a constructor? ›All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Can a class have 2 constructors? ›A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.
Can a constructor be private? ›A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.
Can constructor be inherited? ›
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
How many times a constructor is called in C++? ›Explanation: As the object is defined ony once in the program at line A B::a, so the constructor of A is called only once.
How do you name a constructor? ›You declare and implement a constructor just like you would any other method in your class. The name of the constructor must be the same as the name of the class and, if you provide more than one constructor, the arguments to each constructor must differ in number or in type from the others.
How do we invoke a constructor in C++? ›Constructors are invoked automatically when we create objects. Constructors should be declared in the public section of the Class. Constructors cannot return values to the calling program because they do not have return types. Constructors should always be non-virtual.
Do constructors have a return type? ›A constructor cannot have a return type (not even a void return type). A common source of this error is a missing semicolon between the end of a class definition and the first constructor implementation. The compiler sees the class as a definition of the return type for the constructor function, and generates C2533.
Can constructors be static? ›A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor.
Which constructor Cannot be overloaded? ›A default constructor cannot be overloaded in the same class. This is because once a constructor is defined in a class, the compiler will not create the default constructor. Thus, an attempt to overload the default constructor will effectively remove it from the class.
What is constructor overloading vs overriding? ›When the method signature (name and parameters) are the same in the superclass and the child class, it's called overriding. When two or more methods in the same class have the same name but different parameters, it's called overloading.
What are the disadvantages of a constructor? ›The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values. The default constructor initializes: All numeric fields in the class to zero.
What is constructor in C++ with real time example? ›Constructor is a method that is called when instance of an object is created. They have the same name as a class. In our example default constructor is to be set with values such as eye color, skin color and mouse color. A constructor with at least one parameter is called parameterized constructor.
What is a constructor in programming for dummies? ›
A constructor is a block of code similar to a method that's called when an instance of an object is created. Here are the key differences between a constructor and a method: A constructor doesn't have a return type. The name of the constructor must be the same as the name of the class.
Can constructor be final or private? ›No, a constructor can't be made final. A final method cannot be overridden by any subclasses.
Can I have an empty constructor? ›Having an empty constructor (whether static or not) in a class is redundant, and ReSharper issues a warning to that effect. In the above, an empty static constructor is, in fact, a necessary detail that guarantees lazy initialization.
Why can't we declare constructor as final? ›The child class inherits all the members of the superclass except the constructors. In other words, constructors cannot be inherited in Java therefore you cannot override constructors. So, writing final before constructors makes no sense. Therefore, java does not allow final keyword before a constructor.
What are the constructors and destructors in C++? ›Constructor and Destructor in C++ Constructor and Destructor are the special member functions of the class which are created by the C++ compiler or can be defined by the user. Constructor is used to initialize the object of the class while destructor is called by the compiler when the object is destroyed.
What are the examples of constructors? ›Example 1: Java Constructor
Main obj = new Main(); Here, when the object is created, the Main() constructor is called. And, the value of the name variable is initialized. Hence, the program prints the value of the name variables as Programiz .
Difference between Constructor and Destructor in C++ programming. To allocate memory to the object, we used a constructor in C++. To deallocate the memory that the constructor allocated to an object for this purpose, we use the concept of destructor in C++. It may or may not contain arguments.
What is a constructor in OOP? ›In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.
What's the difference between a constructor and a destructor? ›Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object.
What is constructor in simple words? ›What Does Constructor Mean? A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.
What is the role of constructor in classes? ›
The constructor method is a special method of a class for creating and initializing an object instance of that class.
Why constructors and destructors are required? ›Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.