Search code examples
c++listinitializer

C++: newbie initializer list question


Newbie here. I am looking at company code.

It appears that there are NO member variables in class A yet in A's constructor it initializes an object B even though class A does not contain any member variable of type B (or any member variable at all!).

I guess I don't understand it enough to even ask a question...so what's going on here!? My intuition is that you need a variable before you even try to initialize it. How is it possible (or what good does it do) to initialize an object without having the object?

.h:

class A: public B
{
public:
     A(bool r = true);
     virtual ~A;

private:
}

.cpp:

A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
}

A::~A()
{
}

Please help.

Thanks, jbu


Solution

  • Class A (publicly) inherits from class B:

    class A: public B
    

    The only way to initialize a base class with parameters is through the initializer list.