Calling derived functions of a class from within a vector (C ++)

I have two classes:

class Object { public: Object(); virtual void update(); virtual void draw(); private: protected: int x, y, tick; } 

and

 class Unit : public Object { public: Unit(); void update(); private: protected: } 

Then I define the constructors and functions in the sepparate.cpp files.

Here are the definitions for Object:

 Object::Object() { x = y = 0; }; Object::update() { tick ++; }; Object::draw() { // All my draw code is in here. }; 

And Unit:

 Unit::Unit() : Object() { }; Unit::update() { Object::update(); // Then there a bunch of movement related code here. }; 

Everything works fine individually, but I encounter a problem when trying to call functions from within the vector.

 vector<Object> objects; 

Then I do this in my void main ():

 for (int i = 0; i < objects.size(); i ++) { objects[i].update(); objects[i].draw(); }; 

This draws fine, but only calls the verson update () object, not the version defined by the derived class. Should I create a vector for each type that I get from the Object class for it to work, or is there another way to call derived functions?

Thanks in advance - Seymore

+4
source share
2 answers

Yes, it calls class Object methods because you have a vector of class Object objects:

 vector<Object> objects; // stores instances of class Object 

A possible solution is to use a pointer vector:

 vector<Object*> objects; objects.push_back( new Unit() ); 

and then call the pointers:

 for (int i = 0; i < objects.size(); i ++) { objects[i]->update(); objects[i]->draw(); } 
+6
source

If you want to use object-oriented polymorphism in C ++ (with the meaning: you have a base class and derived classes, and at runtime you may encounter any of them), you should use pointers.

 vector<Object *> objects; 

This means manual memory management (but you can use shared_pointers or http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/ptr_container.html ) and, possibly, a very small performance loss (due to one extra dereferencing and v-table, however you should not worry about it). And do not forget to make your methods virtual;)

I think that’s why I rarely use my daily working object-oriented programming, since I studied it at school;) I use the legacy, but I don’t mix mom and daugther classes in the same containers (and I use templates for many interfaces) .

+1
source

Source: https://habr.com/ru/post/1343292/


All Articles