B\" means \"B inherits from A\":" />
开发者

Constructors with inheritance in c++

If you have 3 classes, with arrows going from parent to child classes (i.e. "A -> B" means "B inherits from A":

shape -> 2d shape -> circle
  +----> 3d shape -> sphere

When you write your constructor for the circle class, would you ever just initialize the grandparent Shape object and then your current object, skipping the middle class? It seems to me you could have x,y coordinates for Shape and initialize those in the constructor, and initialize a radius in the circle or sphere class, but in 2d or 3d shape classes, I wouldn't know what to put in the constructor since it seems like it would be identical to shape. So is something like this valid

Circle::Circle(int x, int y, int r) : Shape(x, y), r(r) {}

I get a compile error of:

 illegal member initialization: 'Shape' is not a base or member

So I wasn't sure if my code was legal or best practice even. Or if instead you'd have the middle class just do what the top level Shape class does

TwoDimensionalShape::TwoDimensionalShape(int x, int y) : Shape (x, y) {}

and then in the Circle c开发者_如何学运维lass

Circle::Circle(int x, int y, int r) : TwoDimensionalShape(x, y), r(r) {}


Yes, as you pointed out at the end of the post, you class constructor can only call its immediate parent's constructor, you can't "skip" classes and initialise your parent's parent.


For non-virtual inheritance, you can only call the constructor of your parent class.

The only time you construct a grandparent (or great-grandparent, etc) is with virtual inheritance.


The constructor for the Shape2d class should call the constructor for Shape. The constructor for Circle should call the constructor for Shape2d.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜