#include <iostream>
#include <string>
usingnamespace std;
class MyClass{
public:
MyClass(int a, int b)
{
var = a;
var2= b;
}
}
private:
int var;
int var2;
};
int main()
{
MyClass obj(1,2);
return 0;
}
#include <iostream>
#include <string>
usingnamespace std;
class MyClass{
public:
MyClass(int a, int b)
: var(a), var2(b)
{
}
}
private:
int var;
int var2;
};
int main()
{
MyClass obj(1,2);
return 0;
}
For the ints in your example, it doesn't really matter much. But when you don't use the initializer list, objects are default constructed. If you have a member variable that has a costly default constructor, it could save some processes to just call the appropriate constructor.
Reference member variables must be initialized using the initializer list -- you can't have a reference that isn't referencing anything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Example program
#include <iostream>
#include <string>
class Foo {
public:
Foo(int& a)
//: a(a) // error when commented out
{}
int& a;
};
int main()
{
int b = 3;
Foo f(b);
}
If a class doesn't have a default constructor, you must call the appropriate constructor in the initializater list.
Because a base class is constructed before the child class, if you want non-default base-class construction, you must call the base class in the initializer list.