-1

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;
}
JHobern
  • 866
  • 1
  • 13
  • 20

1 Answers1

6

When you do

A a = B();

you are slicing the object. What you have is only an instance of an A object.

To make polymorphism work you need to either use references:

B b;
A& a = b;

or use pointers

A* a = new B;
Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621