Constructors and Class Methods in C++

Topic Overview

Welcome back, C++ enthusiast! We're diving back into C++ classes, focusing on constructors and class methods. Picture building a robot: Constructors are the initial settings, and class methods are the commands that enable it to perform actions. Are you ready for a refresher? Let's get started!

Revisiting C++ Classes

A C++ class serves as a blueprint for creating objects. Here's a basic class, Robot:

class Robot {
    // Class body goes here
};

int main() {
    Robot robot_instance;  // Creating an instance of Robot
    return 0;
}

As of now, this Robot class is like an empty shell. It exists but doesn't know how to do anything. To make it functional, attributes and methods are needed.

Deep Dive into Constructors

A constructor is a special function that initializes an object when it is created. In C++, the constructor is a method with the same name as the class. It sets up — or constructs — our new objects with the necessary initial states.

Here, we upgrade the Robot class with a constructor:

#include<iostream>
#include<string>

class Robot {
public:
    // Constructor
    Robot(const std::string &name, const std::string &color) 
        : name(name), color(color) {
        std::cout << "Constructor is called" << std::endl;
    }

private:
    std::string name;
    std::string color;
};

int main() {
    Robot robot_instance("Robbie", "red");  // Output: Constructor is called
    return 0;
}

In this example, the constructor gets automatically called when we create a new Robot instance, set with name and color attributes. It’s always good practice to use constructors to ensure each instance starts with the correct initial values.

Notice the syntax : name(name), color(color) in the constructor. This is known as an initializer list. It is a more efficient way to initialize members because it directly initializes the member variables instead of first creating a default object and then assigning values to it. This can lead to better performance, especially with complex member variables or classes.

Multiple Constructors with Default Parameters

Having one constructor is great, but what if we want more flexibility in setting up our robots? In C++, you can use constructor overloading or default arguments to achieve similar behavior.

Consider the following code snippet:

#include<iostream>
#include<string>

class Robot {
public:
    // Constructor with default parameter for color
    Robot(const std::string &name, const std::string &color="grey")
        : name(name), color(color) {}

    // Overloaded constructor with only name, sets default color to grey
    Robot(const std::string &name)
        : name(name), color("grey") {}

private:
    std::string name;
    std::string color;
};

int main() {
    Robot robot_instance("Robbie", "red");  // Red Robbie
    Robot robot_instance2("Bobby");         // Grey Bobby, no color provided (default)
    return 0;
}

The first constructor defines a default color using default parameters. In other words, with default parameters color becomes optional: when we don't specify it, the robot is grey by default.

Let's now discuss constructor overloading. Overloading allows us to define multiple constructors with different parameters. In the example above, we have two constructors: one that takes name and color, and another that takes only name and sets color to a default value. This provides flexibility in initializing our Robot instances, and now there are multiple ways to create a robot.

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