0

I have the following code:

#include <string>
#include <iostream>

class A{
public:
    virtual void print() {std::cout << "A" << std::endl;};
};

class B : public A{
public:
    void print() {std::cout << "B" << std::endl;};
};

int main(){
    A* a1;
    a1 = new B;

    B b;
    A a2 = b;
    a1->print();
    a2.print();

    std::string s2;
    std::getline (std::cin,s2);

}

And the output that it produce is

B
A

Now, why it the derived method called when the object is a pointer and the base method when the object is not?

Robert
  • 725
  • 1
  • 7
  • 15
  • 1
    Because `a2` is not actually a `B` object. You should read about [object slicing](http://stackoverflow.com/questions/274626/what-is-object-slicing). – Some programmer dude Nov 21 '15 at 12:59
  • Thanks for the explanation @JoachimPileborg. I understand this. However, my concern is not quite treated by the referred post. It is clear that an A can not know of additional members added by the B class. However, the print method here is virtual, and B's version kind of replaces A's. I understand that a B have to store both print methods, but why, when the pointer is an A-pointer, is the derived method called? – Robert Nov 21 '15 at 18:46
  • But `a2` doesn't have any information that it's initialized from a `B` object. When you do the initialization, you *slice* the `B` object into an `A` object, and all the compiler (and your program) have is the `A` object `a2`. – Some programmer dude Nov 21 '15 at 20:02

0 Answers0