In C++, the constructor is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of the new object generally. In C++ , the constructor has the same name as the class or structure.
Syntax for Constructor within the Class
It has the following syntax:
class ClassName {
public:
ClassName(); // Constructor declaration
};
Syntax for constructor outside the class:
ClassName::ClassName() {
// Constructor definition outside the class
// ClassName:: indicates the scope of the constructor
}
Simple C++ Constructor Example
Let us take an example to illustrate the Constructor within the class in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Car { // Class
public: //Access Specifier
string brand; //Attribute
string model;
int year;
Car() { // Constructor defined
brand = "Toyota";
model = "Fortuner";
year = 2020;
}
};
int main() //Main Function
{
Car my_car;
cout << "Brand: " << my_car.brand << endl;
cout << "Model: " << my_car.model << endl;
cout << "Year: " << my_car.year << endl;
return 0;
}
Output:
Brand: Toyota
Model: Fortuner
Year: 2020
Explanation
In this example, we have taken a class named Car. The constructor initialized the member variables brand, model, and year with default values. When the my_car object is created in the main function, the constructor is automatically called, setting these default values. After that, the cout statements display the initialized values.
Types of Constructors in C++
In C++, constructors can be categorized into four categories:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Move Constructor
Here, we will discuss these constructors one by one.
C++ Default Constructor
A constructor which does not argument is known as a default constructor. It is invoked at the time of creating an object. It allows us to initialize the class member variables to their default values. It is also known as a zero-argument constructor.
Syntax
It has the following syntax:
class Class_name{
public:
Class_name(); //declaration of default constructor
};
C++ Default Constructor Example
Let us take a simple example to illustrate the default constructor in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Employee //class
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void) //Main Function
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:
Default Constructor Invoked
Default Constructor Invoked
Explanation
In this example, we have taken a class Employee. The constructor is automatically called each time an object of the class is created. In the main function, two objects (e1 and e2) are created, which results in the constructor being invoked twice. Finally, the message "Default Constructor Invoked" is printed two times.
C++ Parameterized Constructor
In C++, a constructor that has parameters is called a parameterized constructor. It is used to provide different values to different objects. It is useful to initialize the member data. When we want to define the body of the constructor, we can use the parameters to initialize the objects.
Syntax
It has the following syntax:
class Class_name{
public:
Class_name(type1 param1, type2 param2, ...); //declaration of parameterized constructor
};
C++ Parameterized Constructor Example
Let us take an example to illustrate the Parameterized Constructor in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Employee { //class
public:
int id; //data member (also instance variable)
string name;
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void show()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) //Main Function
{
Employee emp1 =Employee(201, "John", 650000); //creating an object of Employee
Employee emp2=Employee(202, "Alice", 750000);
emp1.show();
emp2.show();
return 0;
}
Output:
201 John 650000
202 Alice 750000
Explanation
In this example, we have taken a class Employee that contains several member variables, including ID, name, and salary. In the main function, we assign the values of the objects. After that, we create emp1 and emp2 objects of the Employee class that show the output.
Copy Constructor
A member function known as a copy constructor that helps to initializes an item using another object from the same class. The copy constructor requires a reference to an object belonging to the same class.
To Read More: Copy Constructor
Syntax
It has the following syntax:
class Class_name{
public:
Class_name(const Class_name& obj); //declaration of copy constructor
}
C++ Copy Constructor Example
Let us take an example to illustrate the copy Constructor in C++.
Example
#include <iostream>
using namespace std; //Using Standard Namespace
class Box {
private:
int length;
public:
// Parameterized constructor
Box(int l) : length(l) {}
// Copy constructor
Box(const Box &b) {
length = b.length;
}
// Function to display the length
void display() {
cout << "Length: " << length << endl;
}
};
int main() { //Main Function
// Creating an object using the parameterized constructor
Box box1(10);
// Creating a copy of box1 using the copy constructor
Box box2 = box1;
// Displaying the length of both boxes
box1.display();
box2.display();
return 0;
}
Output:
Length: 10
Length: 10
Explanation:
In this example, the 'Box' class has a constructor that accepts parameters for the 'length' of the box. After that, the copy constructor creates a new 'Box' object from an existing one by copying the value of 'length'. In the main function, we use the copy constructor to copy a 'Box' object, and both objects display their 'length'.
Move Constructor
In C++, the move constructor is a special type of constructor that allows the resources of one object to be moved into another instead of copying the object in the memory. It works with r-value references and is based on the move semantics. It enables us to transfer the ownership of resources from one object to another without performing a deep copy, which helps to improve the performance of the program.
Syntax
It has the following syntax:
Class Class_name{
public:
Class_name(Class_name&& obj); //declaration of move constructor
};
C++ Move Constructor Example
Let us take an example to illustrate the move constructor in C++.
Example
#include <iostream>
#include <cstring>
using namespace std; //using standard namespace
class CppTutorial { //class
char* str;
public: //Access Specifier
CppTutorial(const char* s) { // Constructor
str = new char[strlen(s) + 1];
strcpy(str, s);
cout << "Constructor called\n";
}
// Copy Constructor
CppTutorial(const CppTutorial& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
cout << "Copy Constructor called\n";
}
// Move Constructor
CppTutorial(CppTutorial&& other) {
str = other.str;
other.str = nullptr;
cout << "Move Constructor called\n";
}
// Destructor
~CppTutorial() {
delete[] str;
}
void show() {
if (str)
cout << str << endl;
else
cout << "Null string" << endl;
}
};
int main() { //Main Function
CppTutorial T1("Hello Cpp Tutorial");
CppTutorial T2 = move(T1); // Move constructor called
T2.show();
T1.show(); // T1 has been moved from
return 0;
}
Output:
Constructor called
Move Constructor called
Hello Cpp Tutorial
Null string
Explanation
In this example, we have taken a class named CppTutorial that handles a dynamically allocated C-style string. The class includes a constructor to initialize the string, a copy constructor for deep copying, a move constructor to transfer ownership of the string efficiently, and a destructor to release the allocated memory.
In the main function, an object T1 is created with a string, and T2 is initialized using the std::move(T1) function that calls the move constructor.
Characteristics of Constructors in C++
Several characteristics of constructors in C++ are as follows:
- The constructor has the same name as the class it belongs to.
- Constructors are typically declared in the class's public member section.
- When we create a class object, the constructor is immediately invoked.
- Constructor do not return values in C++, so they don't have any return type.
- Declaring a constructor virtual is not permitted.
- Multiple constructors can not be declared within a single class.
- When allocating memory, the constructor makes implicit calls to the new and delete operators.
Constructors with Default Parameters
A constructor may have some default parameter values, which basically means that if no value is passed in, the default value will be used.
C++ Constructor With Default Parameters Example
Let us take a simple example of a Constructor with Default Parameters In C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Rectangle {
int length;
int width;
public:
// Constructor with default parameters
Rectangle(int l = 5, int w = 3) {
length = l;
width = w;
}
void area() {
cout << "Area of Rectangle: " << length * width << endl;
}
};
int main() { //Main function
// Object with default parameters
Rectangle rect1;
rect1.area(); // Uses default values: 5 and 3
// Object with custom parameters
Rectangle rect2(10, 7);
rect2.area(); // Uses custom values: 10 and 7
return 0;
}
Output:
Area of Rectangle: 15
Area of Rectangle: 70
Explanation
In this example, we have taken a constructor containing the default values of 5 and 3 for both the length and width. If the object is created without parameters, the given default values are used. If the parameters are passed, the default values are overridden.
Constructor Overloading
Constructor overloading allows multiple constructors to be defined with different parameters. It enables us to create objects in various ways based on the situation.
To Read More: Constructor Overloading
C++ Constructor Overloading Example
Let us take a simple example of the Constructor Overloading in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Person { //class
string name;
int age;
public:
// Default constructor
Person() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
Person(string n, int a) {
name = n;
age = a;
}
void show() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() { //Main Function
// Using the default constructor
Person person1;
person1.show();
// Using the parameterized constructor
Person person2("John Doe", 30);
person2.show();
return 0;
}
Output:
Name: Unknown, Age: 0
Name: John Doe, Age: 30
Explanation
In this example, we have taken a class Person that provides two constructors one with no parameter, and another asks for a name and an age. After that, depending on the situation, one instantiation can use one constructor, and the other instantiation can use another.
Constructor with Initializer List
This way of initializing member variables is faster. It is mainly used for const variables or references that require initialization upon object creation.
C++ Constructor Example with Initializer List
Let us take a simple example of a Constructor with an Initializer List in C++.
Example
#include <iostream>
using namespace std;
class Book {
const string title;
int year;
public:
// Constructor with initializer list
Book(string t, int y) : title(t), year(y) {}
void show() {
cout << "Book Title: " << title << ", Year: " << year << endl;
}
};
int main() {
Book book("The C++ Programming Language", 2025);
book.show();
return 0;
}
Output:
Book Title: The C++ Programming Language, Year: 2025
Conclusion
In C++, constructors are an essential part of object initialization and resource management. They can guarantee valid values for all the objects and will manage resources as well. By understanding all forms of constructors (default, parameter, copy), we can write even more capable and cleaner C++ code.
C++ Constructors MCQs:
1) What is the primary objective of a constructor in C ++?
- To allocate memory for objects
- To initialize objects during their construction
- to define class behaviour
- to return the object address
2) Which of the following statements is correct about default constructors?
- A default constructor should have a parameter.
- A default constructor only initializes the static variable.
- A default constructor does not take any parameter.
- A default constructor can only be called explicitly.
3) Which of the following best describes the default behaviour of the compiler-generated copy constructor?
- It performs a deep copy of all members.
- It performs a bitwise copy of an object.
- It performs a shallow copy of all members.
- It initializes only primitive-type members.
4) Which of the following is correct about constructor overloading in C ++?
- Constructors cannot be overloaded
- Only copy constructors can be overloaded
- Overloaded constructors must differ in the return type
- Constructors can be overloaded by changing the parameter list
5) Which of the following is correct about copy constructors?
- It should be declared with static keywords
- It cannot take parameters
- It can only be defined inside the class
- It should accept its argument by reference