I looked around, and most questions deal with why you would use virtual, what polymorphism is and so on. I am having a problem in my program and I want to know WHY the child function is not being called and how to actually CALL the child function in this situation.
I can emulate my problem:
#include <string>
#include <iostream>
#include <vector>
class BaseA {
public:
BaseA(const std::string &n)
: name(n)
{
}
virtual void print() const
{
std::string str("");
str += name;
std::cout << str << std::endl;
}
protected:
std::string name;
};
class BaseB : public BaseA {
public:
BaseB(const std::string &n, const std::string &v)
: BaseA(n), value(v)
{
}
void print() const
{
std::string str("");
str += name;
str += ' ';
str += value;
std::cout << str << std::endl;
}
private:
std::string value;
};
int main() {
std::vector<BaseA> vec;
vec.push_back(BaseA("cat"));
vec.push_back(BaseB("cat", "kitten"));
for(BaseA &obj : vec)
obj.print();
return 0;
}
Why is the output: cat cat?
How do I change the output to "cat cat kitten " using BaseB::print()?