Nick
Nick

Reputation: 10499

Call derived class method

I have a base class:

class motorcycle
{
public:

   virtual int speed()
   { return 0; }
}

And some classes that inherits the base class (only 2 in the example, but i can have a lot of classes):

class honda: public motorcycle 
{
public:

   int speed()
   { return 2; }
}

class yamaha: public motorcycle 
{
public:

   int speed()
   { return 1; }
}

I have a pointer to the base class that points to one of the derived class:

honda* h = new honda();
...
int speed = get_speed(h);

Where get_speed is:

int get_speed(motorcycle* m)
{
    // How to return speed according to m class?
}

Now, what is the best method to return speed?

Upvotes: 0

Views: 101

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

int get_speed(motorcycle* m)
{
    return m->speed();
}

Upvotes: 6

Related Questions