In C++, the constructor serves as a unique function that is automatically triggered during the object's instantiation process. Its primary purpose is to set initial values for the object's data attributes. In C++, the constructor typically shares the identical name with 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's consider a scenario to demonstrate the Constructor inside a 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 instance, we've defined a class called Car. The constructor assigns default values to the class's attributes such as brand, model, and year. Upon creating an object named my_car within the main function, the constructor executes automatically, initializing these default values. Subsequently, the cout statements showcase 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 examine each of these constructors individually.
C++ Default Constructor
A constructor that doesn't require any arguments is referred to as a default constructor. This constructor is called during the object creation process and enables us to set the class member variables to their default values. It is also commonly 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's consider a straightforward example to demonstrate 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 instance, we are showcasing a class named Employee. The constructor is invoked automatically whenever an instance of the class is generated. Within the main function, two instances (e1 and e2) are instantiated, leading to the constructor being called twice. Subsequently, the statement "Default Constructor Invoked" is displayed on two occasions.
C++ Parameterized Constructor
In C++, a constructor with arguments is referred to as a parameterized constructor. This type of constructor is employed to assign distinct values to various objects. It proves beneficial in setting initial values for member data. Utilizing the parameters, we can effectively initialize the objects when specifying the constructor's implementation.
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's consider an example to demonstrate the Parameterized Constructor functionality 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 instance, we've defined a class named Employee which encapsulates various data members such as ID, name, and salary. Within the main function, we initialize the attributes of the objects. Subsequently, we instantiate emp1 and emp2 objects of the Employee class to display the results.
Copy Constructor
A class method referred to as a copy constructor is responsible for initializing an object using another object of the identical class. This constructor necessitates a reference to an object within 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's consider an example to demonstrate 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 instance, the 'Box' class contains a constructor that takes in arguments for the box's 'length'. Subsequently, the copy constructor generates a fresh 'Box' instance based on an original one by duplicating the 'length' value. Within the main function, the copy constructor is applied to replicate a 'Box' instance, and both objects showcase their respective 'length' values.
Move Constructor
In C++, the move constructor serves as a unique constructor designed to facilitate the transfer of resources from one object to another by relocating them in memory instead of duplicating them. This functionality is specifically designed to work with r-value references and is rooted in the concept of move semantics. By utilizing the move constructor, it becomes possible to shift the ownership of resources between objects without the need for an extensive duplication process, ultimately leading to enhanced program performance.
Syntax
It has the following syntax:
Class Class_name{
public:
Class_name(Class_name&& obj); //declaration of move constructor
};
C++ Move Constructor Example
Let's consider an example to demonstrate 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 instance, we are examining a class called CppTutorial that manages a dynamically allocated C-style string. This class consists of a constructor for string initialization, a copy constructor for creating deep copies, a move constructor for efficient string ownership transfer, and a destructor for deallocating the memory that was allocated.
In the main function, an instance T1 is instantiated with a string, and T2 is set up using the std::move(T1) method which invokes 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 can include default parameter values, indicating that if no value is provided, the default value will be utilized.
C++ Constructor With Default Parameters Example
Let's consider a basic illustration 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 instance, we are demonstrating a constructor that includes preset values of 5 and 3 for the length and width attributes. When an object is instantiated without any parameters, the predefined default values of 5 and 3 are applied. However, when specific parameters are provided during object creation, these default values are replaced with the new ones.
Constructor Overloading
Constructor overloading permits the definition of multiple constructors with varying parameters, providing flexibility in creating objects to suit different scenarios.
To Read More: Constructor Overloading
C++ Constructor Overloading Example
Let's consider a straightforward illustration of 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 instance, we are demonstrating a class named Person which offers two constructors: one that doesn't require any parameters and another that requests a name and an age. Subsequently, each instance can employ a specific constructor based on the given scenario.
Constructor with Initializer List
This method of initializing class attributes provides a performance boost. It is commonly employed for constant variables or references that need to be initialized during object instantiation.
C++ Constructor Example with Initializer List
Let's consider a basic illustration of a Constructor with an Initialization List in the C++ programming language.
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 play a vital role in initializing objects and handling resources effectively. They ensure that all objects have valid values and take care of resource management tasks. Familiarizing ourselves with different types of constructors (default, parameterized, copy) enables us to write more sophisticated and streamlined 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
To commence objects while they are being constructed
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.
Option c) It executes a shallow duplication of all attributes.
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
Choose: d) The function should take its parameter by reference