And I didn't understand any of it. I've watched all the videos he made about c++ before this one, but for some reason everything he was doing in this video just went over my head. I didn't understand why he was doing anything he did in the video. I don't know if he just didn't explain it well or what. I was hoping you guys here could explain to me what Member Initializers are, in hopes that I could maybe understand your guys' explanation of it better :)
// This would not work because you cannot initialize constant variables in a class without the member initializer list
class initVars {
private:
constint var1;
string var2;
public:
initVars(int v1, string v2)
{
var1 = v1;
var2 = v2;
}
void printVars ()
{
cout << var1 << endl;
cout << var2 << endl;
}
};
int main()
{
initVars iV(1, "Hi"); // Creating the object, and calling the constructor with the two variables discussed above.
iV.printVars();
}
The above code would produce the following error:
must be initialized in constructor base/member initializer list
// This would work because you use member initialization list to initialize the const data member
class initVars {
private:
constint var1;
string var2;
public:
initVars(int v1, string v2)
: var1(v1), // Here, C++ Says "Constructor, make var1 and var2 equal to the arguments given by the constructor.
var2(v2)
{
var1 = v1;
var2 = v2;
}
void printVars ()
{
cout << var1 << endl;
cout << var2 << endl;
}
};
int main()
{
initVars iV(1, "Hi"); // Creating the object, and calling the constructor with the two variables discussed above.
iV.printVars();
}