Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Classes & Constructors: Using Initialization Lists to Initialize Fields

Full code. Line specified later.

#include <iostream>
#include <string>

using namespace std;

class X
{
    private:

    int i;
    float f;
    char c;

    public:

    X(int first=1, float second=2.0, char third='a') : i(first) , f(second) , c(third) { } 
    void print() { cout << i << " " << f << " " << c << endl;}

};


int main()
{
    X var1;
    var1.print();

    return 0;
}

What exactly is going on on this line:

X(int first=1, float second=2.0, char third='a') : i(first) , f(second) , c(third) { }

As far as I can understand (could be wrong), we are declaring objects first, second, and third of type (class) X. We are initializing them during declaration. What's going on after the colon? What's going on altogether?

like image 308
user1478983 Avatar asked Apr 27 '26 20:04

user1478983


1 Answers

What exactly is going on on this line:

X(int first=1, float second=2.0, char third='a') 
: i(first) , f(second) , c(third) { 
}

It's a constructor which takes 3 parameters with default values.

This part : i(first) , f(second) , c(third) is called a member initializer list.The member initializer list consists of a comma-separated list of initializers preceded by a colon. It’s placed after the closing parenthesis of the argument list and before the opening bracket of the function body.

Only constructors can use this initializer-list syntax. const class members must be initialized in member initializers.

like image 86
billz Avatar answered Apr 30 '26 11:04

billz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!