Sign in to follow this  
stu2000

Inheritance and virtual functions

Recommended Posts

stu2000    101
Alright I understand thus far: If you have a base class 'mover' and a virtual function in it 'Move()' and then create a child class 'car' which inherits from 'mover', if you create a 'Move' function in car, that will get called when you create an object of type 'Car' and call 'move'. You can also call 'move' if you dont override the function in car because it is defined in the 'mover' class.

Now what happens if you create an array of 'mover' but only fill it with 'car' objects. When you call 'move' will it run the car move function or the mover move function? Example code below

Mover movers[10];
Car aCar;
aCar.Move();
movers*[0] = &aCar;

Mover* myMover;
myMover = movers[0];
myMover->Move();

Thx in advance.
Stu

Share this post


Link to post
Share on other sites
Aardvajk    13207
Yes, the whole point of virtual functions is that if you call one via a base pointer, the compiler will, at runtime, call the appropriate function based on the actual type being pointed to.

Probably a typo but this code is syntactically incorrect:


Mover movers[10];
Car aCar;
aCar.Move();
movers*[0] = &aCar;


You would need to do:


Mover *movers[10]; // array of ten pointers to Mover
Car aCar;
aCar.Move();
movers[0]=&aCar;


HTH

Share this post


Link to post
Share on other sites
Rycross    584
If you're using a pointer to your Car objects, then it will call Car's move method. If you're storing by value, then you will get what is called "object slicing." Basically, the array only allocated space for a Mover object and expects one of those, so it will cut out anything extra in Car. It will call Mover's move method.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this