How to Implement Class Constructors in C++

Jinku Hu Feb 02, 2024
  1. What Constructors Are and How They Work in C++
  2. Implement Multiple Class Constructors Using Overloading in C++
How to Implement Class Constructors in C++

This article will introduce how to implement class constructors in C++.

What Constructors Are and How They Work in C++

Constructors are special member functions that define how the class object should be initialized. Constructors generally initialize data members of the class, and they are executed when a class object is created. Some specific features of the constructor functions are that they have the same name as the class itself and can not have a return type. Usually, a class has multiple constructors which overload each other, but they must have a different number or types of parameters.

Note that constructors are often explicitly specified by the user in any slightly complex class. Still, the default constructor is generated automatically by the compiler when the user does not define any constructors. The default constructor is generally the one that takes no arguments, and it’s called for default initialization of the class. Note, though, a compiler-generated default constructor is formally called a synthesized default constructor. The latter is specifically inferred for each class according to its data members, and it initializes the members using the in-class initializer or using the default value. Thus, automatically generated constructors are not the universal solution, but they work correctly for simple class structures.

In the following example, we defined a MyClass1 class with two constructors. Notice that the first one does not take any arguments, which imply that it’s a default constructor, but we still specified a default keyword. The latter indicates to the compiler that this specific constructor should be the default one. Generally, a compiler does not generate a default constructor if the user defines any constructor. In this case, a user should explicitly request the default designation for the given constructor function.

The second constructor of MyClass1 takes a single string value as the argument and initializes name data member with it. It prints the special string literal to cout stream only to make the function execution moment visible for observation. m2 object creation triggers the constructor one. m1 object is initialized with the default constructor, and since the compiler itself generates the latter one, we don’t see any printed string on cout stream.

#include <iostream>
#include <utility>

using std::cout;
using std::endl;
using std::string;

class MyClass1 {
 private:
  string name;
  string nickname;

 public:
  MyClass1() = default;
  explicit MyClass1(string n) : name(std::move(n)) {
    cout << "Constructor 1 is called" << endl;
  };

  string getName() { return name; }

  string getNickname() { return nickname; }

  ~MyClass1() { cout << "Destructor is called" << endl; }
};

int main() {
  MyClass1 m1{};
  cout << m1.getName() << endl;
  cout << m1.getNickname() << endl;
  cout << "------------------" << endl;

  string n1("Maude");
  MyClass1 m2(n1);
  cout << m2.getName() << endl;
  cout << m2.getNickname() << endl;
  cout << "------------------" << endl;

  return EXIT_SUCCESS;
}

Output:

------------------
Constructor 1 is called
Maude

------------------
Destructor is called
Destructor is called

Implement Multiple Class Constructors Using Overloading in C++

MyClass1 has the second string data member called nickname. Suppose we create another constructor that takes a single string value and defines it to initialize the nickname. In that case, the compiler will raise the error that we can’t overload the functions with the same parameters. So, we need to define another constructor, e.g., we chose the constructor that takes two string references and initializes both data members. When the following code snippet is run, we can see that the second constructor was executed.

Constructors have far more detailed characteristics, and we only introduced the main features in this article. Other special functions contain the word - constructor in their names, like move-constructor and copy-constructor. These two are part of special operations collectively called copy control. Note that destructors conduct the opposite of what the constructors do. Namely, they deallocate the class members, and they are usually called automatically when the object goes out of scope. One can easily observe constructor-destructor call behavior with the given code snippets.

#include <iostream>
#include <utility>
#include <vector>

using std::cout;
using std::endl;
using std::string;

class MyClass1 {
 private:
  string name;
  string nickname;

 public:
  MyClass1() = default;
  explicit MyClass1(string n) : name(std::move(n)) {
    cout << "Constructor 1 is called" << endl;
  };

  // ERROR: Does not Compile
  //    MyClass1(string nk) : nickname(nk) {
  //        cout << "Constructor 3 is called" << endl;
  //    };
  MyClass1(string &n, string &nk) : name(n), nickname(nk) {
    cout << "Constructor 2 is called" << endl;
  };

  string getName() { return name; }

  string getNickname() { return nickname; }

  ~MyClass1() { cout << "Destructor is called" << endl; }
};

int main() {
  string n1("Maude");
  string n2("Bibi");

  MyClass1 m4(n1, n2);
  cout << m4.getName() << endl;
  cout << m4.getNickname() << endl;
  cout << "------------------" << endl;

  return EXIT_SUCCESS;
}

Output:

Constructor 2 is called
Maude
Bibi
------------------
Destructor is called
Destructor is called
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ Class