So I am refreshing on C++, and honestly it's been awhile. I made a console pong game as a sort of refresher task and got some input on using polymorphism for my classes to derive from a base "GameObject" (that has some base methods for drawing objects to the screen).
One of the pieces of input was (and I had subsequently asked about) was how memory worked when deriving from base classes. Since I hadn't really done much advanced C++.
For instance lets say we have a base class, for now it just has a "draw" method (Btw why do we need to say virtual
for it?), since all other derived objects really only share one common method, and that's being drawn:
class GameObject
{
public:
virtual void Draw( ) = 0;
};
we also have a ball class for instance:
class Ball : public GameObject
The input I received is that in a proper game these would probably be kept in some sort of vector of GameObject pointers. Something like this: std::vector<GameObject*> _gameObjects;
(So a vector of pointers to GameObjects) (BTW Why would we use pointers here? why not just pure GameObjects?). We would instantiate one of these gameObjects with something like:
_gameObjects.push_back( new Ball( -1, 1, boardWidth / 2, boardHeight / 2 ); );
(new
returns a pointer to the object correct? IIRC). From my understanding if I tried to do something like:
Ball b;
GameObject g = b;
That things would get messed up (as seen here: What is object slicing?)
However...am I not simply creating Derived objects on their own when I do the new Ball( -1, 1, boardWidth / 2, boardHeight / 2 );
or is that automatically assigning it as a GameObject too? I can't really figure out why one works and one doesn't. Does it have to do with creating an object via new
vs just Ball ball
for example?
Sorry if the question makes no sense, im just trying to understand how this object slicing would happen.