0% found this document useful (0 votes)
11 views14 pages

A Constructor in C++

The document provides an overview of constructors in C++, detailing their purpose, types, and syntax. It explains default, parameterized, copy, and move constructors, along with examples demonstrating their usage. Key characteristics include the constructor's name matching the class name, the absence of a return type, and automatic invocation upon object creation.

Uploaded by

poonam Bhalla
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)
11 views14 pages

A Constructor in C++

The document provides an overview of constructors in C++, detailing their purpose, types, and syntax. It explains default, parameterized, copy, and move constructors, along with examples demonstrating their usage. Key characteristics include the constructor's name matching the class name, the absence of a return type, and automatic invocation upon object creation.

Uploaded by

poonam Bhalla
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/ 14

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,

#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

Constructors in C++
Last Updated : 11 Jan, 2025


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 ClassConstructor outside 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;
}

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++:
1. Default Constructor: No parameters. They are used to create
an object with default values.
2. Parameterized Constructor: Takes parameters. Used to
create an object with specific initial values.
3. Copy Constructor: Takes a reference to another object of the
same class. Used to create a copy of an object.
4. 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 rvalue reference of the object of
the same class and transfers the ownership of this object to the
newly created object.
Like a copy constructor, the compiler will create a move
constructor for each class that does not have any explicit move
constructor.

You might also like