I have a vector of pointers to objects that are derived from the same base class. The problem is that the type of the original object is forgotten when calling functions (but not methods).
class Cat{
//base class
public:
virtual void growl() = 0;
};
class HouseCat : public Cat{
//derived class
public:
void growl(){};
};
class AlleyCat : public Cat{
//derived class
public:
void growl(){};
};
void function(HouseCat& a){};
void function(AlleyCat& a){};
int main(){
vector<Cat*> cats;
cats.push_back(new HouseCat);
cats.push_back(new AlleyCat);
function(*(cats[0])); //error: cannot convert parameter 1 from 'Cat' to 'HouseCat &'
(cats[0])->growl(); //this works though
}
Is there a workaround?
Add another virtual function to
Catas (add virtual destructor as well):And implement it as:
Then you can write this:
It will call the appropriate overload of
function()eventually.Or simply implement
functionas virtual member-function in the class hierarchy.