views:

187

answers:

5

Hi,

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

+8  A: 

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.

luke
so then it sounds like since Class A inherits from Class B, every object of type A contains a hidden reference to an object of type B?
jbu
@jbu: It's more than a reference it's a base class sub-object. Every A instance contains a complete B instance as a sub-object. Inheritance is used to express "is a" relationships, so every A is also a B.
Charles Bailey
Inheritance is consider an "is-a" relationship. `A` "is-a" `B`. You can think of class `A` as a `B` with extra stuff. You can treat an `A` as if it were a `B`.
luke
Rather, *public* inheritance is considered an "is-a" relationship.
luke
A: 

This is actually the only way to call the ctor of a base class in C++ as there is noch such thing as super().

pmr
And indeed there can't be, because C++ supports multiple inheritance.
Novelocrat
A: 
class A : public B
{
};

class B
{
  public:
  int x;
};

A is a derived type from B. Or A inherits B.

So this is valid...

A a;
a.x = 3;

The rest of your code is just calling B's constructor when A is constructed.

Brian R. Bondy
A: 

Since construtor cannot be inherited so base class data members are to be initialized by passying argument in derived class constructor and with the help of initialization list.

You should also know that in case of polymorphic class initialization of vptr to respective virtual table is done only in constructor.

Ashish
A: 
class A: public B
{
public:
     A(bool r = true); // defaults parameter 1 as "true" if no arguments provided ex A *pA = new A();
     virtual ~A;

private:
}

.cpp

A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
  // calls parent class, and initialize argument 1 with some enumeration based on whether r is true or false
}

A::~A()
{
}
Daniel