user1139666
user1139666

Reputation: 1697

Derived class virtual function not executed

I am working on a Visual Solution including a C++ project and a C++/CLI project.
I have implemented a hierarchy of classes in the C++/CLI project :

Class D => Class C => Class B => Class A

=> means : is derived from

Class A to class D are not ref classes.

Class A contains the following method:

virtual int MyMethod() const;

MyMethod is also declared and implemented in class D:

int MyMethod() const;

I have written the following code in the C++ project:

A l_dObject = D();
l_dObject.MyMethod();

Class A's MyMethod is executed but I expect class D's MyMethod to be executed. Can someone please explain me why?

Upvotes: 0

Views: 61

Answers (2)

Wug
Wug

Reputation: 13196

This is what's known as slicing.

You're constructing an A from a D. A probably provides a copy constructor from an A and has no knowledge that D exists. You pass the D to the copy constructor (as const A&) and the constructor happily copies from it that way. When you're all done here, what you have is an A. The D is killed after the assignment.

Most of the solutions to this problem involve allocations on the heap, and pointers/references.

A *l_dObject = new D(); // allocate our D on the heap
...
delete l_dObject; // don't forget to delete afterwards

Upvotes: 2

Dark Falcon
Dark Falcon

Reputation: 44181

A l_dObject = D();

You are slicing the object: That means you are making a copy of the A portion of the object and discarding the D portion. When dealing with polymorphic objects, you need to use a pointer or a reference to the base class. For example:

A* l_dObject = new D();

Don't forget to delete it later.

Upvotes: 2

Related Questions