I was translating a Java program of mine to C++. I got to a problem trying to use polymorphism the same way as in Java.
My code looks something like this:
class Base
{
public:
virtual void print() = 0;
};
class Derived_1 : public Base
{
public:
void print()
{
std::cout << "1" << std::endl;
}
};
class Derived_2 : public Base
{
public:
void print()
{
std::cout << "2" << std::endl;
}
};
The next are two versions of my main method that I have tried, both give me compiler errors:
1:
int main(int argc, char const *argv[])
{
std::vector<Base> v;
v.push_back(Derived_1());
v.push_back(Derived_2());
for(Base i: v)
{
i.print();
}
return 0;
}
Error:
object of abstract class type "Base" is not allowed:C/C++(322)
main.cpp(35, 14): function "Base::print" is a pure virtual function
2:
int main(int argc, char const *argv[])
{
std::vector<Base*> v;
v.push_back(new Derived_1());
v.push_back(new Derived_2());
for(Base* i: v)
{
i.print();
}
return 0;
}
Error:
expression must have class type but it has type "Base *"C/C++(153)
How would you guys solve this?