initializing class members with member constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

class myClass
{
public:
	myClass(int inVal) : myInt(inVal){} //this is legal
	//myClass(int inVal) { myInt(inVal); } //this is not legal
private:
	int myInt;
};

int main()
{
	myClass mc(6);
	return 0;
}


I was wondering why the second method of initializing myInt is not legal.
The first one calls "int's constructor". By the time the control flow is inside the block, myInt has already been created, so it's too late to call its constructor.
It's illegal for the same reason this is illegal:
1
2
int a;
a(10);
Thanks Helios. Is it correct to say whatever comes after the ":" and before the body {...} must be something that invokes a constructor for a member or class known to "myClass"?
Yes. Remember that the initialization list is comma-separated.
I'm unsure what you mean about "class known to myClass". The initializer list can only be used to construct the actual members of the myClass or its base classes. That is what it is for. If myClass has a dependency on some other class, then it "knows about that class" but it can't construct it in the initializer list unless you have a class of that type as a member or base class.
Topic archived. No new replies allowed.