C++ pack 2: Inheritance + initialization lists

02.12.2009 23:21 in c++

I've got quite confused today.

class Foo
{
public:
  int *bar;
  int index;
};

class FooEx : protected Foo
{
public:
  FooEx(int *bar, int index) :
    bar(bar), index(index) {};
};

What's wrong with this code? (of course real example was more complicated with templates & other fun stuff involved) I was convinced that everything is OK, and error message broke my heart:

foo.cpp: In constructor 'FooEx::FooEx(int*, int)':
foo.cpp:13: error: class 'FooEx' does not have any field named 'bar'
foo.cpp:13: error: class 'FooEx' does not have any field named 'index'

And answer is: you can't have superclass' members in initialization list. Instead you must call superclass' constructor with appropriate parameters. Considering that such code as above is not often seen it's not a shame to be defeated by another C++ fancy feature.

Comments:

  1. Reg

    Reg:

    Yeah, repeating all these parameters passed to the constructor of every class in the hierarchy is sometimes lots of typing when coding in C+ .

    You actually can initialize parent members in the child constructor initialization list when using virtual inheritance - but it's not the correct solution for problem here I think :)

    06.12.2009 12:01:39

  2. EDM

    EDM:

    I just tripped over this today. To fix it, I needed to write a constructor for an abstract base class. Before today, if you had asked me if abstract classes needed constructors, I would have said no.

    11.03.2010 20:58:30

Leave comment: