0

Say I have class B that derives from class A. If B overrides a virtual method f of class A, what exactly happens with this virtual method when I assign an instance of class B into an instance of class A?

Most basic example:

#include <stdio.h>

class A
{
  public:
    virtual void f()
    {
      printf("I am A\n");
    }
};

class B : public A
{
  public:
    virtual void f()
    {
      printf("I am B\n");
    }
};

int main()
{
  // Instance of B:
  B b;
  b.f();

  // Reference to A:
  A& a_ref = b;
  a_ref.f();

  // Assignment:
  A a = b;
  a.f();

  return 0;
}

Output:

[windel@hoefnix]$ g++ wtf.cpp
[windel@hoefnix]$ ./a.out 
I am B
I am B
I am A

When using a reference, all is going as expected, but with a cast, I was put on the wrong foot here.

Windel
  • 499
  • 4
  • 11
  • Your final example is not _casting_ - doing `A a = b;` slices the `B` to an `A`, so both the static and dynamic type of `a` is an A. – BeeOnRope Jan 11 '17 at 20:20
  • Just a quick helpful note: you only get polymorphism in C++ when you use a *reference* or a *pointer* to an object. – Mark Ransom Jan 11 '17 at 20:37
  • It's also not assignment happening at that point, even though you wrote = – Flexo Jan 11 '17 at 20:44

0 Answers0