Constructors in C++ Classes

Lesson Introduction

Welcome to the lesson on Constructors in C++ classes!

Have you ever wondered how objects in your code are created and initialized? This is where constructors come into play. Constructors are special functions that are automatically called when an object of a class is created. They help set up the object with initial values and are essential for managing resources efficiently. In this lesson, our goal is to understand different types of constructors in C++: default, parameterized, and copy constructors, and learn how to implement them in a class.

Understanding Constructors

So, what exactly is a constructor? A constructor is a special member function of a class that initializes objects. It has the same name as the class and does not have a return type, not even void.

Think of a constructor like setting up a new house. When you move in, you need to set up the furniture before you can comfortably live in it. Similarly, when an object is created, a constructor sets up the initial state of the object.

Example of a Default Constructor

A default constructor is a constructor that either has no parameters or has parameters with default values. Its primary purpose is to initialize objects with default settings.

Let's see how to write a default constructor using an example:

#include <iostream>

class MyClass {
public:
    // Default constructor
    MyClass() {
        std::cout << "Default constructor called!" << std::endl;
    }
};

int main() {
    MyClass obj; // Default constructor is called here
    return 0;
}

In this example, when we create an object obj of MyClass, the default constructor is called, displaying the message "Default constructor called!".

Parameterized Constructor

Parameterized constructors help when you need to initialize objects with specific values. These constructors accept arguments to initialize an object with provided values.

Let's extend our previous example:

#include <iostream>

class MyClass {
public:
    int value;

    // Default constructor
    MyClass() {
        value = 0;
        std::cout << "Default constructor called!" << std::endl;
    }

    // Parameterized constructor
    MyClass(int param) {
        value = param;
        std::cout << "Parameterized constructor called! Value: " << value << std::endl;
    }
};

int main() {
    MyClass obj1; // Default constructor is called
    MyClass obj2(100); // Parameterized constructor is called
    return 0;
}

Here, obj1 uses the default constructor, and obj2 uses the parameterized constructor to initialize the value to 100.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal