views:

55

answers:

2

Hi.

Here's what I thought of doing :

A - Structure {
 Position
 Name
}

B1 - Vehicle {
 Fuel
}

B2 - Building {
 -nothing-
}

foo - Car
foo2 - Truck
bar - Hospital
bar2 - Market

It's impossible to declare constructors like the following since A is not the direct base class :

foo(x,y,z):A(x,y,z)
bar(a,b,c):A(a,b,c)

So I tried doing it like that :

B1():A(){}
B2():A(){}
...
foo(x,y,z):A(x,y,z),B1()
bar(a,b,c):A(a,b,c),B2()

It works, but I'm not sure if this is the right way to do it since A is constructed twice (or so I think). I don't want to make the same constructors (taking the same arguments) that'll wrap around the constructor of class A, like :

B1(x,y,z):A(x,y,z){}
...
foo(x,y,z):B1(x,y,z)

Edit :

Clarified it a bit more.

Initially, there was a "structure" class from which all the foo's and bar's derived and it was all fine, but the moment I needed to add Fuel to vehicles, I had to differentiate vehicles from buildings.

It makes perfect sense that Vehicles and Buildings should be supported with the same quantity of arguments, but what I want to know is if it's legal to separate the constructor calls (what seems to work -the second last snippet- seems to do that, however, as I said above, I don't know if that's the correct way to do it.) .

I know I could just do multiple inheritance for vehicles and buildings or a simply use an instance thereof as a property of foo&bar, but I wonder if there's a correct way to do it this way.

+1  A: 

The easiest way to resolve your problem is to make constructors' parameters consistent across all inheritance hierarchy. If default constructors are ok, you should have and use them in all three levels of inheritance. If there should be parameterized constructors, they're also should be at all three levels of inheritance. After you'll do so, you'll be able to construct instances of foo like

foo(x, y, z): B1(x, y, z);
B1(x, y, z): A(x, y, z);

or

foo(): B1();
B1(): A();

I believe that there's no other reasonable solution for this.

Haspemulator
A: 

Your solution does not compile for me. What you need to do is to make the B constructors take the arguments that A needs into its constructor. If you also want a default constructed A make another B constructor. Foo and Bar inherits the B's not A so they should never call A's constructor either.

daramarak