Home > Mobile >  Storing derived class to the vector C
Storing derived class to the vector C

Time:10-01

I have problem with storing child class object to the vector. I have parent class

class IngameObject
{
protected:
    bool clickable = false;
};

I have second class

class Character : public IngameObject
{
protected:
    bool clickable = true;
};

Now, I am trying to create new instance of Character and stroe it to the vector. I have vector defined as

std::vector<IngameObject*> objVector;

Code for creating Characters and stroring them is

for(int i = 0; i < 1; i  )
{
     int a = i*32;
     Character *c = new Character(this->holderTextures["texture"], sf::IntRect(a, a, 32, 32), sf::Vector2f(2*a, 10.f));
     std::cout << instanceof<Character>(c) << " TEST" <<std::endl;
     this->objVector.emplace_back( c );
     std::cout << instanceof<Character>(this->objVector.back()) << " TEST" <<std::endl;
}

In the first case, instance is Character. After emplace_back to the objVector is type of instance IngameObject and bool clickable is set to false. What I am doing wrong?

EDIT Instanceof is defined as

template<typename Base, typename T>
inline bool instanceof(const T*) {
   return std::is_base_of<Base, T>::value;
}

CodePudding user response:

Storing a derived class in a std::vector as you do is correct: the problem is not related with polymorphism or "storing derived class in a vector":

#include <iostream>
#include <vector>

class IngameObject
{
protected:
    bool clickable = false;
};

class Character : public IngameObject
{
protected:
    bool clickable = true;
};

int main()
{
    std::vector<IngameObject*> objVector;
    
    Character *c = new Character();
    objVector.emplace_back( c );
    
    delete c;

    return 0;
}

The problem is related with you you implement instanceof


To solve the instanceof function, your class need to be polymorphic. Then, the pointer to the base class can be converted to the derived class, thus confirming that it is instanceof the base class:

#include <iostream>
#include <vector>

class IngameObject
{
protected:
    bool clickable = false;
    virtual ~IngameObject() = default;
};

class Character : public IngameObject
{
protected:
    bool clickable = true;
};

template<class Base, class T>
inline bool instanceof(T* t) {
   return nullptr != dynamic_cast<Base*>(t);
}


int main()
{
    std::vector<IngameObject*> objVector;
    
    Character *c = new Character();
    std::cout << instanceof<Character>(c) << " TEST" <<std::endl;
    objVector.emplace_back( c );
    std::cout << instanceof<Character>(objVector.back()) << " TEST" <<std::endl;
    
    delete c;

    return 0;
}

Note: to make Base polymorphic, it needs to have at least one virtual method.

  • Related