Why is virtual function not being called?

后端 未结 6 1867
挽巷
挽巷 2021-01-26 07:00
//GUITEXT
class guitext : public entity {
public:
    guitext(graphics *gfx, std::string _text, float _x, float _y, 
        float _size, float timeToLive);
    bool upd         


        
相关标签:
6条回答
  • 2021-01-26 07:13

    You should define entitys to contain pointers to entity. Slightly edited example derived from your code.

    #include "stdafx.h"
    #include <vector>
    #include <string>
    
    class entity 
    {
    public:
        virtual void draw() { }
    };
    
    class guitext : public entity 
    {
    public:
        void draw()
        {
            printf("draw");
        }
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        std::vector<entity *> entitys;
    
        guitext g;
    
        entitys.push_back(&g); 
    
        for(int i = 0; i < (int)entitys.size(); i++) 
        { 
            entitys[i]->draw(); 
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-26 07:15

    Was the vector declared as vector<entity>? Then only the base class part can be stored there, i.e. you lose polymorphism (which only works through pointer or reference in C++).

    0 讨论(0)
  • 2021-01-26 07:23

    You made a vector of entity. Those objects always have type entity. If you want to invoke polymorphism, they need to be pointers or references. How can a vector of entity store a guitext? There's not enough space, it doesn't know how to destroy it, etc etc.

    0 讨论(0)
  • 2021-01-26 07:30

    You're storing Entitys, not pointers to objects of varying derived types of Entity.

    0 讨论(0)
  • 2021-01-26 07:31

    What you've done is a bit concealed variant of slicing.

    0 讨论(0)
  • 2021-01-26 07:39

    In addition, in your case it's not good idea to pass arguments by value, i suppose there will be very big quantity of objects that need to be redrawed. Better, by const reference, since functon doesn't change state of passed object inside.

    0 讨论(0)
提交回复
热议问题