C++ Constructors

What are Constructors?

Constructors are special member functions in C++ used to initialize objects of a class. They are called automatically when an object is created. A constructor has the same name as the class and does not have a return type, not even void.

The syntax for defining a constructor within a class is as follows:


class MyClass {
public:
    MyClass() {
        // code here
    }
};

In this example, the constructor for the class MyClass is defined within the class itself. The code inside the constructor is executed each time an object of MyClass is created.

To define a constructor outside the class, the syntax is slightly different. The constructor is declared within the class, and its definition is provided outside the class using the scope resolution operator ::. Here is an example:


class MyClass {
public:
    MyClass();
};

MyClass::MyClass() {
    // code here
}

Constructors can have parameters, allowing us to initialize objects with specific values. Here is an example:


class Rectangle {
private:
    int width, height;

public:
    Rectangle(int w, int h) {
        width = w;
        height = h;
    }
};

int main() {
    Rectangle myRect(10, 20);
    return 0;
}

In this example, the constructor of the Rectangle class takes two parameters, w and h, which are used to initialize the width and height members of the object myRect respectively.

Constructors are essential in C++ as they allow for the proper initialization of objects, ensuring their correct and expected behavior.

Definition of Constructors

Constructors in C++ are the special member functions responsible for initializing objects of a class. They are called automatically when an object is created and set the initial values of the object's data members.

A constructor has the same name as the class and no return type, not even void. They can have parameters, allowing for customization during initialization. Constructors can be defined within the class declaration or separately outside the class.

The purpose of constructors is to ensure that objects are in a valid and usable state once they are created. They are called automatically when a new object is created, eliminating the need for explicit initialization.

Purpose of Constructors in C++

Constructors play a vital role in C++ programming, as they are responsible for initializing objects of a class. A constructor is a special member function within a class that is automatically called whenever a new object of that class is created. Its primary purpose is to ensure the proper initialization of the object's data members and prepare it for use.

When an object is instantiated, the constructor is called to allocate memory for the object and set its initial values. By defining a constructor, programmers can control the initial state of the object, ensuring that it is properly set up and ready to perform its intended tasks.

In C++, constructors have the same name as the class and do not return any value, not even void. They can be overloaded, which means that multiple constructors can be defined with different parameters. This allows for flexibility in object initialization, as different constructors can be used depending on the needs of the program.

Additionally, constructors can also be used to perform other tasks, such as allocating dynamic memory or establishing connections with external resources. This further highlights their significance in the overall functionality of the program.

Types of Constructors in C++

Default Constructor

Definition of Default Constructor

A default constructor in C++ is a special type of constructor that is automatically called when an object of a class is created without any arguments. It is a constructor that does not take any parameters, also known as a zero-argument constructor.

The purpose of a default constructor is to initialize the object's data members to their default values. When an object is created using the default constructor, all the data members of the object are assigned default values based on their type. For example, if an object has an integer data member, it will be initialized to 0, or if it has a string data member, it will be initialized to an empty string.

The default constructor plays a crucial role in object creation as it ensures that the object is in a valid state from the moment it is created. Without a default constructor, the object would contain unpredictable or garbage values, which could lead to incorrect behavior or errors when trying to access or manipulate the object's data members.

In C++, if a class does not have any explicit constructors defined, the compiler automatically generates a default constructor. However, if there is at least one constructor defined in the class (other than the default constructor), the compiler does not generate a default constructor. In such cases, if an object is created without any arguments, it will result in a compilation error. Therefore, it is essential to define a default constructor explicitly if needed.

Syntax for Default Constructor

The syntax for a default constructor in C++ is as follows:


class Person {
public:
    std::string name;
    int age;

    // Default constructor
    Person() {
        name = "Unknown";
        age = 0;
    }
};

int main() {
    // Creating an object of Person class using the default constructor
    Person p1;
    std::cout << "Name: " << p1.name << ", Age: " << p1.age << std::endl;
    return 0;
}

In the above example, the default constructor of the Person class initializes the name member to “Unknown” and the age member to 0. After creating an object p1 using the default constructor, we can access and modify its data members.

Parameterized Constructor

Definition of Parameterized Constructor

A parameterized constructor is a special type of constructor in object-oriented programming that allows for the assignment of initial values to an object at the time of its creation by accepting parameters.

The purpose of a parameterized constructor is to provide a convenient way to initialize an object with specific values without the need for separate setter methods. By accepting parameters, the constructor can receive values from outside and assign them to the object's instance variables.

Compared to a default constructor, which is automatically provided by the compiler if no explicit constructor is defined, a parameterized constructor differs in that it accepts arguments. These arguments, also known as parameters, are used to pass values to the constructor when creating an object.

The ability to assign initial values through a parameterized constructor adds flexibility and customization to the object creation process. It allows for different objects of the same class to have different initial values, tailored to specific requirements. This can be particularly useful when working with complex objects that may have multiple properties or dependencies that need to be set when the object is instantiated.

Syntax for Parameterized Constructor

The syntax for defining a parameterized constructor in C++ is similar to that of a regular function. It begins with the constructor name, followed by a set of parentheses that contain the parameter list. These parameters can be of any valid C++ data type, such as int, float, or string.

Here's an example of a parameterized constructor:


class MyClass {
private:
    int myVariable;

public:
    // Parameterized constructor
    MyClass(int value) {
        myVariable = value;
    }
};

int main() {
    // Creating an object and passing a value to the constructor
    MyClass obj(10);
    return 0;
}

In the above code, the parameterized constructor of the MyClass class initializes the myVariable member with the value passed as an argument. The object obj is created with a value of 10, which is then assigned to the private variable using the constructor.

Using a parameterized constructor allows for customization and initialization of objects during their creation, providing flexibility and improving code readability and maintainability.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate

Master coding skills by choosing your ideal learning course

View all courses