You can write a default constructor, which is a constructor that accepts parameters.

When all members of a class [or struct] are public, we can use aggregate initialization to initialize the class [or struct] directly using list-initialization:

class Foo
{
public:
    int m_x {};
    int m_y {};
};

int main[]
{
    Foo foo { 6, 7 }; // list-initialization

    return 0;
}

However, as soon as we make any member variables private, we’re no longer able to initialize classes in this way. It does make sense: if you can’t directly access a variable [because it’s private], you shouldn’t be able to directly initialize it.

So then how do we initialize a class with private member variables? The answer is through constructors.

Constructors

A constructor is a special kind of class member function that is automatically called when an object of that class is created. Constructors are typically used to initialize member variables of the class to appropriate user-provided values, or to do any setup steps necessary for the class to be used [e.g. open a file or database].

After a constructor executes, the object should be in a well-defined, usable state.

Unlike normal member functions, constructors have specific rules for how they must be named:

  1. Constructors must have the same name as the class [with the same capitalization]
  2. Constructors have no return type [not even void]

Default constructors and default initialization

A constructor that takes no parameters [or has parameters that all have default values] is called a default constructor. The default constructor is called if no user-provided initialization values are provided.

Here is an example of a class that has a default constructor:

#include 

class Fraction
{
private:
    int m_numerator {};
    int m_denominator {};

public:
    Fraction[] // default constructor
    {
        m_numerator = 0;
        m_denominator = 1;
    }

    int getNumerator[] { return m_numerator; }
    int getDenominator[] { return m_denominator; }
    double getValue[] { return static_cast[m_numerator] / m_denominator; }
};

int main[]
{
    Fraction frac{}; // calls Fraction[] default constructor
    std::cout 

Chủ Đề