A class constructor is a function that places data into a class object and performs any other set up for a class object that needs to be performed when a class object is first instantiated. In this article, I’ll demonstrate how to create and use several different types of class constructors.

I’m going to demonstrate how to create and use constructors using a class definition I developed in my previous article, which was an introduction to C++ classes. Here is the class definition I’ll be starting from:

class Date {
private:
  int month, day, year;
  string adjustDate(int d) {
    string date;
    if (d < 10) {
      date = "0" + to_string(d);
    }
    else {
      date = to_string(d);
    }
    return date;
  }
public:
  void display() {
    string date = adjustDate(month) + "/" + adjustDate(day)
                + "/" + adjustDate(year);
    cout << date;
  }
  void setMonth(int m) {
    month = m;
  }
  void setDay(int d) {
    day = d;
  }
  void setYear(int y) {
    year = y;
  }
};

An Overview of Constructors

A constructor function is used to initialize the member variables of a class and to perform any other set-up operations that need to be performed when a class object is instantiated. A class can have multiple constructors based on the needs of the class. Constructors must have the same name as the class.

There are two types of constructors most classes need to have. The first type is a default constructor. The default constructor initializes all class member variables to their default values, so that integer variables get 0s, string variables get the empty string, and so on.

The second constructor type most classes will have is the fully-parameterized constructor. This constructor has this name because there is a function parameter for every member variable of the class.

In between these two constructors, can be other constructors depending on the needs of the class. For example, the Date class might provide a constructor that just sets the month and the year and sets the day to its default value.

#learn-to-program #cpp #object-oriented #learn-to-code #programming-education

Learning C++: Class Constructors
1.10 GEEK