Constructor in C
Constructor in C
a class is created. 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. It constructs the values i.e.
provides data for the object which is why it is known as a constructor.
<class-name> (){
...
Constructors are mostly declared in the public section of the class though they 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.
<class-name> (list-of-parameters) {
// constructor definition
<class-name> {
<class-name>: :<class-name>(list-of-parameters) {
// constructor definition
}
Example:
#include <iostream>
// Class definition
class student {
int rno;
char name[50];
double fee;
public:
/*
*/
student()
}
// Function to display the data
void display()
cout << endl << rno << "\t" << name << "\t" << fee;
};
int main()
student s;
/*
*/
s.display();
return 0;
Output:
11 Aman 10111
Note: We can make the constructor defined outside the class as inline to make it equivalent
to the in class definition. But note that inline is not an instruction to the compiler, it is only
the request which compiler may or may not implement depending on the circumstances.
Types of Constructors in C++
Constructors can be classified based on in which situations they are being used. There are 4
types of constructors in C++:
Default Constructor: No parameters. They are used to create an object with default values.
Parameterized Constructor: Takes parameters. Used to create an object with specific initial
values.
Copy Constructor: Takes a reference to another object of the same class. Used to create a
copy of an object.
Move Constructor: Takes an rvalue reference to another object. Transfers resources from a
temporary object.
1. Default Constructor
A default constructor is a constructor that doesn’t take any argument. It has no parameters.
It is also called a zero-argument constructor.
className() {
// body_of_constructor
The compiler automatically creates an implicit default constructor if the programmer does
not define one.
2. Parameterized Constructor
className (parameters...) {
// body
If we want to initialize the data members, we can also use the initializer list as shown:
A copy constructor is a member function that initializes an object using another object of the
same class.
// body_containing_logic
Just like the default constructor, the C++ compiler also provides an implicit copy constructor
if the explicit copy constructor definition is not present.
Here, it is to be noted that, unlike the default constructor where the presence of any type of
explicit constructor results in the deletion of the implicit default constructor, the implicit
copy constructor will always be created by the compiler if there is no explicit copy
constructor or explicit move constructor is present.
4. Move Constructor
The move constructor is a recent addition to the family of constructors in C++. It is like a
copy constructor that constructs the object from the already existing objects., but instead of
copying the object in the new memory, it makes use of move semantics to transfer the
ownership of the already created object to the new object without creating extra copies.
The move constructor takes the value reference of the object of the same class and transfers
the ownership of this object to the newly created object.
Constructors
To create a constructor, use the same name as the class, followed by parentheses ():
Example
Constructor Parameters
Constructors can also take parameters (just like regular functions), which can be useful for
setting initial values for attributes.
The following class have brand, model and year attributes, and a constructor with different
parameters. Inside the constructor we set the attributes equal to the constructor parameters
(brand=x, etc). When we call the constructor (by creating an object of the class), we pass
parameters to the constructor, which will set the value of the corresponding attributes to
the same:
Example
Example
C++ Constructors
In C++, a constructor has the same name as that of the class, and it does not have a return
type. For example,
class Wall {
public:
// create a constructor
Wall() {
// code
};
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
is public
#include <iostream>
// declare a class
class Wall {
private:
double length;
public:
Wall()
: length{5.5} {
};
int main() {
Wall wall1;
return 0;
Run Code
Output
Creating a Wall
Length = 5.5
Here, when the wall1 object is created, the Wall() constructor is called. length{5.5} is invoked
when the constructor is called, and sets the length variable of the object to 5.5.
Note: If we have not defined any constructor, copy constructor, or move constructor in our
class, then the C++ compiler will automatically create a default constructor with no
parameters and empty body.
Defaulted Constructor
When we have to rely on default constructor to initialize the member variables of a class, we
should explicitly mark the constructor as default in the following way:
Wall() = default;
If we want to set a default value, then we should use value initialization. That is, we include
the default value inside braces in the declaration of member variables in the follwing way.
#include <iostream>
class Wall {
private:
public:
Wall() = default;
void print_length() {
};
int main() {
Wall wall1;
wall1.print_length();
return 0;
Run Code
Output:
length = 5.5
// declare a class
class Wall {
private:
double length;
double height;
public:
: length{len}
, height{hgt} {
double calculateArea() {
};
int main() {
return 0;
Run Code
Output
Here, we have defined a parameterized constructor Wall() that has two parameters: double
len and double hgt. The values contained in these parameters are used to initialize the
member variables length and height.
length{len} initializes the member variable length with the value of the parameter len
height{hgt} initializes the member variable height with the value of the
parameter hgt.
When we create an object of the Wall class, we pass the values for the member variables as
arguments. The code for this is:
With the member variables thus initialized, we can now calculate the area of the wall with
the calculateArea() method.
Note: A constructor is primarily used to initialize objects. They are also used to run a default
code when an object is created.
: length{len}
, height{hgt} {
}
Here,
: length{len}
, height{hgt}
The member initializer list is used to initialize the member variables of a class.
The order or initialization of the member variables is according to the order of their
declaration in the class rather than their declaration in the member initializer list.
Since the member variables are declared in the class in the following order:
double length;
double height;
The length variable will be initialized first even if we define our constructor as following:
: height{hgt}
, length{len} {
The copy constructor in C++ is used to copy data from one object to another. For example,
#include <iostream>
// declare a class
class Wall {
private:
double length;
double height;
public:
// initialize variables with parameterized constructor
: length{len}
, height{hgt} {
: length{obj.length}
, height{obj.height} {
double calculateArea() {
};
int main() {
return 0;
Run Code
Output
In this program, we have used a copy constructor to copy the contents of one object of
the Wall class to another. The code of the copy constructor is:
: length{obj.length}
, height{obj.height} {
Notice that the parameter of this constructor has the address of an object of the Wall class.
We then assign the values of the variables of the obj object to the corresponding variables of
the object, calling the copy constructor. This is how the contents of the object are copied.
In main(), we then create two objects wall1 and wall2 and then copy the contents
of wall1 to wall2:
Here, the wall2 object calls its copy constructor by passing the reference of the wall1 object
as its argument.
If we don't define any copy constructor, move constructor, or move assignment in our class,
then the C++ compiler will automatically create a default copy constructor that does
memberwise copy assignment. It suffices in most cases. For example,
Explain
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
: length{len}
, height{hgt} {
double calculateArea() {
};
int main() {
return 0;
Run Code
Output
In this program, we have not defined a copy constructor. The compiler used the default copy
constructor to copy the contents of one object of the Wall class to another.
Destructors in C++
In this article, we will learn about the destructors in C++, how they work, how and why to
create the user defined destructors with the code examples. At the end, we will look at some
commonly used questions about C++ destructors.
~ <class-name>() {
// some instructions
}
Just like any other member function of the class, we can define the destructor outside the
class too:
<class-name> {
public:
~<class-name>();
}
<class-name> :: ~<class-name>() {
// some instructions
}
But we still need to at least declare the destructor inside the class.
Characteristics of a Destructor
Destructor has the same name as their class name preceded by a tilde (~) symbol.
The destructor is only one way to destroy the object created by the constructor.
Hence, destructor cannot be overloaded.
The thing is to be noted here if the object is created by using new or the constructor uses
new to allocate memory that resides in the heap memory or the free store, the destructor
should use delete to free the memory.
Examples of Destructor
The below programs demonstrate the behaviour of the destructor in different cases:
Example 1
The below code demonstrates the automatic execution of constructors and destructors
when objects are created and destroyed, respectively.
// and destructor
#include <iostream>
class Test {
public:
// User-Defined Constructor
10
11
12
// User-Defined Destructor
13
14
};
15
main()
16
17
Test t;
18
19
return 0;
20
Output
Constructor executed
Destructor executed
Example 2
The below C++ program demonstrates the number of times constructors and destructors are
called.
#include <iostream>
// value
class Test {
10
public:
11
// User-Defined Constructor
12
Test()
13
14
15
16
Count++;
17
cout << "No. of Object created: " << Count << endl;
18
19
20
// User-Defined Destructor
21
~Test()
22
23
24
25
<< endl;
26
Count--;
27
28
29
};
30
31
// driver code
32
int main()
33
34
36
return 0;
37
Output
Note: Objects are destroyed in the reverse order of their creation. In this case, t3 is the first
to be destroyed, while t is the last.
A destructor function is called automatically when the object goes out of scope or is deleted.
Following are the cases where destructor is called:
Destructor can also be called explicitly for an object. We can call the destructors explicitly
using the following statement:
object_name.~class_name()
If we do not write our own destructor in class, the compiler creates a default destructor for
us. The default destructor works fine unless we have dynamically allocated memory or
pointer in class. When a class contains a pointer to memory allocated in the class, we should
write a destructor to release memory before the class instance is destroyed. This must be
done to avoid memory leaks.
Destructors have the same name as the class preceded by a tilde (~).
No, there can only be one destructor in a class with a class name preceded by ~, no
parameters, and no return type.
Yes, In fact, it is always a good idea to make destructors virtual in the base class when we
have a virtual function. See virtual destructor for more details.
Yes, destructor can be defined as private when we want to control the deletion of the object
manually. See Private Destructor in C++ for details.