Constructor Functions  «Prev  Next»
Lesson 6 An initialization constructor
Objective Use constructor to initialize values of class data members

C++ Constructor Initialization for Data Members

Question: How do I use a constructor to initialize values of class data members in C++?
A constructor in C++ is a special type of function that's used to initialize the data members of a class. The constructor is called automatically when an object of the class is created. It can be used to assign default or initial values to the data members of that object.
Here is how you might go about using a constructor in this way:
  1. Step 1: Define the Constructor within the Class
    The first thing to do is to define the constructor within your class. The constructor should have the same name as the class itself and it doesn't return any value, not even void.
    In our case, we will make a class called MyClass:
    class MyClass {
    public:
        int myInt;
        float myFloat;
        string myString;
    
        MyClass();  // The constructor declaration
    };
    
  2. Step 2: Implement the Constructor
    Next, you will need to implement the constructor. This is where you specify what should happen when an object of your class is created. For this case, we'll assign some initial values to our data members. The constructor implementation is typically done outside the class definition using
    scope resolution operator :: .
    

    MyClass::MyClass() {  // The constructor implementation
        myInt = 0;
        myFloat = 0.0f;
        myString = "";
    }
    
  3. Step 3: Create an Object of Your Class:
    When you create an object of your class, the constructor will be called automatically, and your data members will be initialized with the values you specified in the constructor:
    int main() {
        MyClass obj;  // Creating object of MyClass
    
        // Accessing and printing data members
        cout << "myInt: " << obj.myInt << endl;
        cout << "myFloat: " << obj.myFloat << endl;
        cout << "myString: " << obj.myString << endl;
    
        return 0;
    }
    

    In this example, myInt will be initialized to 0, myFloat to 0.0, and myString to an empty string.
    You can also create constructors that take parameters. These are known as parameterized constructors. They can be used to initialize data members with specific values at the time of creating an object.

For example:
class MyClass {
public:
    int myInt;
    float myFloat;
    string myString;

    MyClass(int, float, string);  // Parameterized constructor declaration
};

// Parameterized constructor implementation
MyClass::MyClass(int a, float b, string c) {
    myInt = a;
    myFloat = b;
    myString = c;
}

int main() {
    MyClass obj(10, 20.5f, "OpenAI");  // Creating object of MyClass with initial values

    // Accessing and printing data members
    cout << "myInt: " << obj.myInt << endl;
    cout << "myFloat: " << obj.myFloat << endl;
    cout << "myString: " << obj.myString << endl;

    return 0;
}

In this case, myInt will be initialized to 10, myFloat to 20.5, and myString to "OpenAI". This allows you to have more control over the initial state of your objects.


Automatic Initialization in C++

When an object of type Counter is first created, we want its count to be initialized to 0. After all, most counts start at 0. We could provide a set_count() function to do this and call it with an argument of 0, or we could provide a zero_count() function, which would always set count to 0. However, such functions would need to be executed every time we created a Counter object.
Counter c1; //every time we do this,
c1.zero_count(); //we must do this too

This is mistake prone, because the programmer may forget to initialize the object after creating it. It is more reliable and convenient, especially when there are a great many objects of a given class, to cause each object to initialize itself when it is created. In the Counter class (from the previous lesson), the constructor Counter() does this. This function is called automatically whenever a new object of type Counter is created. Thus in main() the statement Counter c1, c2; creates two objects of type Counter. As each is created, its constructor, Counter(), is executed. This function sets the count variable to 0. So the effect of this single statement is to not only create two objects, but also to initialize their count variables to 0.

C++ Initialization Constructor

Use constructor to initialize values of class data members. We will now examine the implementation of a data type mod_int to store numbers that are computed with a modulus.
//Modulo numbers and constructor initialization
class mod_int {
public:
   mod_int(int i) { v = i % modulus; }
   void assign(int i) { v = i % modulus; }
   void  print() const { cout << v << '\t'; }
   const static int modulus;
private:
   int  v;
};
const int  mod_int::modulus = 60;

The integer v is restricted in value to 0, 1, 2, ... , modulus - 1. It is the programmer's responsibility to enforce this restriction by having all member functions guarantee this behavior. The member function mod_int::mod_int(int) is a constructor. It does not have a return type. It is invoked when objects of type mod_int are used in a definition and has one argument. When invoked, it requires an expression that is assignment-compatible with its int parameter. It then creates and initializes the declared object.

Same Name as the Class

There are some unusual aspects of constructor functions. First, it is no accident that they have exactly the same name (Counter in this example) as the class of which they are members. This is one way the compiler knows they are constructors. Second, no return type is used for constructors. Why not? Since the constructor is called automatically by the system, there is no program for it to return anything to; a return value would not make sense. This is the second way the compiler knows they are constructors.

SEMrush Software