Search code examples
c++objectvirtual

Member duplication when using virtual method


When passing a pointer to an object whose parent has a virtual function to a method with a parent type, I get strange copying of parent members in the resulting object.

Child -> Parent -> Child

someMethod(Parent * obj);

Parent
virtual ~Parent() {}

Child : public Parent()

Child childobj = new Child();
someMethod(childobj);

When viewed in memory after being passed through soemMethod, this shows a resulting object that looks like this:

DATA[]
parentvar1
parentvar2
Child[]

->Child[]
->childvar1
->childvar2
->Parent[]

->->Parent[]
->->parentvar1
->->parentvar2

Why am I seeing parent data being duplicated both at index 0 and at index 2?


Solution

  • I'm just taking a guess, because your terminology is very difficult to understand.

    I'm guessing you're viewing your data a debugger, such as Visual Studio, and your program is currently within some method of the Parent class.

    In the debugger, you're seeing data in the this object as well as variables on the stack, what you refer to as "index 0". One of these variables is another Child object. Since Child is a subclass of Parent, you'll see both the properties of that Child as well as the Parent properties it inherits (what you refer to as "index 2").

    In this case, you're not seeing any copying, you're simply seeing the same data (or perhaps two different instances) from different perspectives in the debugger.