Parent fields not accessible from initializer list

Oct 12, 2010 at 6:46pm
I'm trying to use a constructor's initializer list to initialize a public field in the superclass, like this:

1
2
3
4
5
6
7
8
9
class Parent {
public:
    int foo;
};

class Child : public Parent {
public:
    Child() : foo(42) {}
};


But this gives a compiler error: "class ‘Child’ does not have any field named ‘foo’".

Can anyone explain why this type of initialization is illegal in C++? Thanks.
Oct 12, 2010 at 6:58pm
You can't initialise field of the parent class directly like that.
You can call a Parent class constructor.

So you will have to make a constructor for Parent.
Oct 12, 2010 at 7:04pm
Yes, I understand that I cannot. But my question was, why? I don't see why the C++ standard would disallow this kind of initialization.
Oct 12, 2010 at 7:47pm
In the initialisation list - a class is responsible only for it's own fields - (this includes a parent constructors).


Anyway - As the parent class will be constructed before the child class - and foo will havehad it's initial value - you cannot have foo(42) in the way you have - because you can't construct something twice.

You can only change it by assignment from now on.
1
2
3
4
class Child : public Parent {
public:
    Child()  {foo = 42;}
};
Last edited on Oct 12, 2010 at 8:34pm
Oct 12, 2010 at 11:06pm
The reason is that this way has the advantage of protecting the parent class against external stuff dinking around with its fields in unorthodox ways. (Yes, you read that right: a derived class is not a "friend" of a parent class -- it is an external thing). Hence guestgulkan's first response: use a parent class constructor.
1
2
3
4
5
6
7
8
9
10
class Parent {
public:
    int foo;
    Parent( int foo = 0 ): foo( foo ) { }
};

class Child : public Parent {
public:
    Child() : Parent(42) { }
};

Hope this helps.
Oct 12, 2010 at 11:25pm
You say the reason is to protect unauthorized dinking, but a subclass can still dink around with public/protected members after initialization. So there's no point in barring access to public/protected members only in the initializer list.

I think guestgulkan's explanation makes more sense. The fields are already initialized when the superclass's constructor is called, so initializing them in the subclass's initializer list would be improperly redundant.
Topic archived. No new replies allowed.