I have a list of objects of type A, that may contain instances of any number of classes derived from A. I am calling a function on each member of the list, and wish to have the function from the most derived class be called. However, the function of the base class is called. How can I get it to be the case that the most derived class is used?
The following code illustrates my problem. The code outputs "In a" but I want it to output "In b".
#include <iostream>
class A {
public:
virtual void func()
{
std::cout << "In A" << std::endl;
}
};
class B : public A {
public:
virtual void func()
{
std::cout << "In B" << std::endl;
}
};
int main()
{
A a = B();
a.func();
return 0;
}