Jump to content
  • Advertisement
Sign in to follow this  
stu2000

Inheritance and virtual functions

This topic is 2805 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!