0

This is a design problem.

I have a common baseclass that defines a bunch of virtual functions, and a default behavior for each function (if the derived classes don't define it).

For example:

class Transport {
public:
    Transport(){}
    Transport(const Definition & def);

    //Access functions that have to be redefined
    virtual void getFuelUsage(float& r) { r=0; }
    virtual void getMaxSpeed(float& r){ r=0; }
    virtual void getNumPeople(float& r){ r=0; }
    virtual void getWeight(float& r); { r=0; }
    //... Many more
};

Then I have some derived classes:

class Car {
public:
    Car(){}
    Car(const Definition & def);

    //Access functions that have to be redefined
    virtual void getFuelUsage(float& r) { .... } //Redefined
    virtual void getMaxSpeed(float& r){ .... } //Redefined
    virtual void getNumPeople(float& r){ .... } //Redefined
    //...
};

class Bike {
public:
    Bike(){}
    Bike(const Definition & def);

    //Access functions that have to be redefined
       //I want default to be kept
    virtual void getMaxSpeed(float& r){ .... } //Redefined
    virtual void getNumPeople(float& r){ .... } //Redefined
    //...
};

But when I use it this way:

Transport a = Bike(definition);
float speed;
a.getMaxSpeed(speed);

I am getting always the base class implementation. Which I don't want!

But, obviously I want the user, to simply care about "Transport", not if the transport is a bike or a car to have diferent methods and object types. Because the base class already defined all the methods, and the derived ones only redefine some of them.

Is there a simple way of achieving this? Maybe with a redesign?

Thanks!

DarkZeros
  • 8,235
  • 1
  • 26
  • 36
  • 1
    Use `Transport& a = Bike(definition);` instead. – πάντα ῥεῖ Jun 03 '15 at 10:30
  • So... as simple as don't copy or assign, use pointers/references. ok! Thanks!! – DarkZeros Jun 03 '15 at 10:33
  • _"as don't copy or assign"_ To prevent this, you can also make your constructors and the assignment operator of the `Transport` class `protected`, instead of letting it have the compiler generated versions. I suspect `Transport` shouldn't be used in another context than being inherited. – πάντα ῥεῖ Jun 03 '15 at 18:40

0 Answers0