views:

159

answers:

5
+2  Q: 

c++ inheritance

Hi, i am trouble with this.. Is there some solution or i have to keep exactly class types?

//header file

Class Car {
public:
    Car();
    virtual ~Car();
};

class Bmw:Car {
public:
    Bmw();
    virtual ~Bmw();
};

void Start(Car& mycar) {};

//cpp file

Car::Car(){}
Car::~Car() {}

Bmw::Bmw()
    :Car::Car(){}
Bmw::~Bmw() {}

int main() {
    Car myCar;
    Bmw myBmw;

    Start(myCar); //works
    Start(myBmw); //!! doesnt work

    return 0;
}
+8  A: 

You should write class Bmw : public Car.

What you want to have here is public inheritance, but not a private one (which is default for classes in C++).

Kotti
+5  A: 

You have Bmw inheriting privately from Car, which prevents converting a Bmw reference to a Car reference. Change the definition to:

class Bmw : public Car
Mike Seymour
+14  A: 

C++ defaults to private inheritance, so, you need to declare Bmw as:

class Bmw:public Car

Also, to be completely accurate, you should really have Start as a virtual method of Car and override it as needed in descendant classes. :)

Donnie
+4  A: 

You need public inheritance - it represents IS A relationship between derived and base types. As in bmw IS A car, while private inheritance (the default when not explicitly specified and what you have here) represents implemented in terms of relationship.

Try:

class Bmw: public Car
{
    // ...
];
Nikolai N Fetissov
+3  A: 

I'm no mechanic, but class Bmw: public Car should fix you up and have you on the road to understanding inheritance in no time!

Inheritance is private by default for classes (public for structs).

Johnsyweb