0

Everytime I call Draw method it always called for base class...

   #pragma once
    #include <pch.h>

    class A
    {
    public:
        A();

        virtual void Draw(CanvasDrawingSession^ drawingSession);
    };

Class B derived from A

#pragma once
#include <pch.h>
#include <A.h>

class B: public A
{
public:
    B();

    void Draw(CanvasDrawingSession^ drawingSession);
};

When I initialize base class object with derived class object A a = B() and call Draw method - a.Draw() it will always call Draw() from base class. What I'm doing wrong?

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
Max Naumov
  • 178
  • 12
  • 3
    `A a = B()` is doing *object slicing*, essentially converting your `B` instance into an `A` instance. Polymorphism in C++ works through *pointers* and *references* to base classes. – Matteo Italia Apr 26 '16 at 21:52

1 Answers1

2

The code A a = B() constructs an instance of type B, and then assigns it to a variable of type A. The compiler has generated for you a default copy constructor ...

A::A(const A&)

... that works fine for assignment from a variable of type B, because any instance of B is an instance of type A (because it's a subclass of A).

This effect is known as object slicing.

To make your code work, don't throw away the B-ness. You could for example do this:

B the_b = B();
A* a_ptr = &the_b;
a_ptr->Draw()

That will call B::Draw().

Community
  • 1
  • 1
James Youngman
  • 3,623
  • 2
  • 19
  • 21