0% found this document useful (0 votes)
10 views

Constructor in C

The document provides an overview of constructors in C++, detailing their purpose, syntax, and types including default, parameterized, copy, and move constructors. It explains how constructors are automatically invoked when an object is created and highlights the significance of member initializer lists for initializing class attributes. Additionally, it includes code examples to illustrate the implementation of different types of constructors.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Constructor in C

The document provides an overview of constructors in C++, detailing their purpose, syntax, and types including default, parameterized, copy, and move constructors. It explains how constructors are automatically invoked when an object is created and highlights the significance of member initializer lists for initializing class attributes. Additionally, it includes code examples to illustrate the implementation of different types of constructors.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Constructor in C++ is a special method that is invoked automatically at the time an object of

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.

Syntax of Constructors in C++

The prototype of the constructor looks like this:

<class-name> (){

...

Characteristics of Constructors in C++

The name of the constructor is the same as its 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.

Types of Constructor Definitions in C++

In C++, there are 2 methods by which a constructor can be declared:

1. Defining the Constructor Within the Class

<class-name> (list-of-parameters) {

// constructor definition

2. Defining the Constructor Outside the Class

<class-name> {

// Declaring the constructor

// Definiton will be provided outside

<class-name>(); // Defining remaining class

<class-name>: :<class-name>(list-of-parameters) {

// constructor definition
}

Example:

Constructor within Class

// Example to show defining

// the constructor within the class

#include <iostream>

using namespace std;

// Class definition

class student {

int rno;

char name[50];

double fee;

public:

/*

Here we will define a constructor

inside the same class for which

we are creating it.

*/

student()

// Constructor within the class

cout << "Enter the RollNo:";

cin >> rno;

cout << "Enter the Name:";

cin >> name;

cout << "Enter the Fee:";

cin >> fee;

}
// Function to display the data

// defined via constructor

void display()

cout << endl << rno << "\t" << name << "\t" << fee;

};

int main()

student s;

/*

constructor gets called automatically

as soon as the object of the class is declared

*/

s.display();

return 0;

Constructor outside Class

Output:

Enter the RollNo:11

Enter the Name:Aman

Enter the Fee:10111

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.

Syntax of Default Constructor

className() {

// body_of_constructor

The compiler automatically creates an implicit default constructor if the programmer does
not define one.

2. Parameterized Constructor

Parameterized constructors make it 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.

Syntax of Parameterized Constructor

className (parameters...) {

// body

If we want to initialize the data members, we can also use the initializer list as shown:

MyClass::MyClass(int val) : memberVar(val) {};


3. Copy Constructor

A copy constructor is a member function that initializes an object using another object of the
same class.

Syntax of Copy Constructor

Copy constructor takes a reference to an object of the same class as an argument.

ClassName (ClassName &obj)

// 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.

It can be seen as stealing the resources from other objects.

Syntax of Move Constructor

className (className&& obj) {

// body of the constructor

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

A constructor in C++ is a special method that is automatically called when an object of a


class is created.

To create a constructor, use the same name as the class, followed by parentheses ():
Example

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Note: The constructor has the same name as the class, it is always public, and it does not
have any return value.

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

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Just like functions, constructors can also be defined outside the class. First, declare the
constructor inside the class, and then define it outside of the class by specifying the name of
the class, followed by the scope resolution :: operator, followed by the name of the
constructor (which is the same as the class):

Example

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}

C++ Constructors

A constructor is a special member function that is called automatically when an object is


created.

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

 has the same name as the class,

 does not have a return type, and

 is public

C++ Default Constructor

A constructor with no parameters is known as a default constructor. For example,

// C++ program to demonstrate the use of default constructor

#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

public:

// default constructor to initialize variable

Wall()

: length{5.5} {

cout << "Creating a wall." << endl;


cout << "Length = " << length << endl;

};

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.

double length {5.5};

Let's see an example:

// C++ program to demonstrate the use of defaulted constructor

#include <iostream>

using namespace std;


// declare a class

class Wall {

private:

double length {5.5};

public:

// defaulted constructor to initialize variable

Wall() = default;

void print_length() {

cout << "length = " << length << endl;

};

int main() {

Wall wall1;

wall1.print_length();

return 0;

Run Code

Output:

length = 5.5

C++ Parameterized Constructor

In C++, a constructor with parameters is known as a parameterized constructor. This is the


preferred method to initialize member data. For example,

// C++ program to calculate the area of a wall


#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

double height;

public:

// parameterized constructor to initialize variables

Wall(double len, double hgt)

: length{len}

, height{hgt} {

double calculateArea() {

return length * height;

};

int main() {

// create object and initialize data members

Wall wall1(10.5, 8.6);

Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;

Run Code

Output

Area of Wall 1: 90.3

Area of Wall 2: 53.55

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}, height{hgt} is the member initializer list.

 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:

Wall wall1(10.5, 8.6);

Wall wall2(8.5, 6.3);

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.

C++ Member Initializer List

Consider the constructor:

Wall(double len, double hgt)

: length{len}

, height{hgt} {

}
Here,

: length{len}

, height{hgt}

is member initializer list.

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:

Wall(double hgt, double len)

: height{hgt}

, length{len} {

C++ Copy Constructor

The copy constructor in C++ is used to copy data from one object to another. For example,

#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

double height;

public:
// initialize variables with parameterized constructor

Wall(double len, double hgt)

: length{len}

, height{hgt} {

// copy constructor with a Wall object as parameter

// copies data of the obj parameter

Wall(const Wall& obj)

: length{obj.length}

, height{obj.height} {

double calculateArea() {

return length * height;

};

int main() {

// create an object of Wall class

Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2

Wall wall2 = wall1;

// print areas of wall1 and wall2

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;

Run Code

Output

Area of Wall 1: 90.3

Area of Wall 2: 90.3

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:

Wall(const Wall& obj)

: 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:

// copy contents of wall1 to wall2

Wall wall2 = wall1;

Here, the wall2 object calls its copy constructor by passing the reference of the wall1 object
as its argument.

C++ Default Copy Constructor

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:

// initialize variables with parameterized constructor

Wall(double len, double hgt)

: length{len}

, height{hgt} {

double calculateArea() {

return length * height;

};

int main() {

// create an object of Wall class

Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2 by default copy constructor

Wall wall2 = wall1;


// print areas of wall1 and wall2

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;

cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;

Run Code

Output

Area of Wall 1: 90.3

Area of Wall 2: 90.3

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++

Last Updated : 11 Oct, 2024

Destructor is an instance member function that is invoked automatically whenever an object


is going to be destroyed. Meaning, a destructor is the last function that is going to be called
before an object is destroyed.

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.

Syntax to Define Destructor

The syntax for defining the destructor within the class:

~ <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

 A destructor is also a special member function like 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 cannot be overloaded.

 It cannot be declared static or const.

 Destructor neither requires any argument nor returns any value.

 It is automatically called when an object goes out of scope.

 Destructor release memory space occupied by the objects created by the


constructor.

 In destructor, objects are destroyed in the reverse of an object creation.

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.

// C++ program to demonstrate the execution of constructor


2

// and destructor

#include <iostream>

using namespace std;

class Test {

public:

// User-Defined Constructor

10

Test() { cout << "\n Constructor executed"; }

11

12

// User-Defined Destructor

13

~Test() { cout << "\nDestructor executed"; }

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.

// C++ program to demonstrate the number of times

// constructor and destructors are called

#include <iostream>

using namespace std;

// It is static so that every class object has the same


7

// value

static int Count = 0;

class Test {

10

public:

11

// User-Defined Constructor

12

Test()

13

14

15

// Number of times constructor is called

16

Count++;

17

cout << "No. of Object created: " << Count << endl;

18

19

20

// User-Defined Destructor
21

~Test()

22

23

// It will print count in decending order

24

cout << "No. of Object destroyed: " << Count

25

<< endl;

26

Count--;

27

// Number of times destructor is called

28

29

};

30

31

// driver code

32

int main()

33

34

Test t, t1, t2, t3;


35

36

return 0;

37

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

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.

When is the destructor called?

A destructor function is called automatically when the object goes out of scope or is deleted.
Following are the cases where destructor is called:

1. Destructor is called when the function ends.

2. Destructor is called when the program ends.

3. Destructor is called when a block containing local variables ends.

4. Destructor is called when a delete operator is called.

How to call destructors explicitly?

Destructor can also be called explicitly for an object. We can call the destructors explicitly
using the following statement:

object_name.~class_name()

When do we need to write a user-defined destructor?

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.

Frequently Asked Questions (FAQs) on C++ Destructors

How are destructors different from normal member functions?

 Destructors have the same name as the class preceded by a tilde (~).

 Destructors don’t take any argument and don’t return anything.

Can there be more than one destructor in a class?

No, there can only be one destructor in a class with a class name preceded by ~, no
parameters, and no return type.

Can a destructor be virtual?

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.

Can destructor be private?

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.

You might also like