Pergunta

Maybe this is a bit of a beginner's question but I need some help regarding this issue.

Assume there is a class A that inherits from class B that itself inherits from class C.

Now when class A constructor looks like this everything is fine:

A::A(params)
  :B(params)
{
}

Next I tried this but it fails:

A::A(params)
  :C(params)
{
}

Why can't I ignore inheritance from B here - or is there a way to make this possible? Defining A as follows does not work, here compiler complains C is already a base class of A:

class A : B, C
Foi útil?

Solução

Why can't I ignore inheritacne from B here - or is there a way to make this possible?

Because classes can only decide how to construct their direct subobject. The direct subobject for A is B and for B is C. The B object needs to be constructed too, you can't bypass it.

The error you got, basically complains about this.

Defining A as follows does not work, here compiler complains C is already a base class of A: class A : B,C

With:

class A : B, C

you are actually declaring a private multiple inheritance. And since you said B has already a subobject (inherits from) C, the compiler is complaining that inheriting from C in A is useless.

But please remember to always specify the private/protected/public kind of inheritance so that you avoid confusion. By default the inheritance for classes is private and for structs is public. So the above code corresponds to:

class A : private B, private C

Outras dicas

You should write:

class C
{
public: C(ParamType param) { ... }
};

class B : public C
{
public: B(ParamType param) : C(param) { ... }
};

class A : public B
{
public: A(ParamType param) : B(param) { ... }
};

There is really no other way....

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top