OOP

Constructor

In object-oriented programming, a constructor is a special type of method that is automatically called whenever you create an object of a class. It acts like a blueprint to set up a new object’s initial state.

Here’s why constructors are important:

Overall, constructors are essential for creating well-defined and flexible objects in object-oriented programming.

class Distance
{
    private: 
      int feet;
      float inches;
    public:
      Distance() = default;  // new syntax
      // Distance(): feet(0), inches(0.0){}   //older way
    /* Distance()            // older more similar to java in syntax
     {
        feet = 0; 
        inches = 0.0;
     } */  
     // Distance(int f, float in): feet(f), inches(in){}  //2 argument constructor
      int getFeet()
      {
        return feet;
      }
      void setFeet(int newValue)
      {
         feet = newValue;
      }
};

How many constructors in a class?

A class can have as many constructors as you want, within reason. There’s typically no practical limit imposed by most programming languages themselves.

This ability to have multiple constructors is called constructor overloading. It means creating constructors with different parameter lists (number and types of arguments). This allows you to:

However, it’s important to consider these points:

While there’s no set limit, strive to create a manageable number of constructors that provide the necessary initialization options for your class.

Practice