views:

102

answers:

3

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 class

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

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

Dima
+3  A: 

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.

Igor Zevaka
+1  A: 

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.

R Samuel Klatchko