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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With