Search code examples
c++virtualreturn-value

Can virtual functions be used in return values?


I was a little surprised that the following code did not work as expected:

#include "stdio.h"

class RetA
{
public:
    virtual void PrintMe () { printf ("Return class A\n"); }
};

class A
{
public:
    virtual RetA GetValue () { return RetA (); }
};

class RetB : public RetA
{
public:
    virtual void PrintMe () { printf ("Return class B\n"); }
};

class B : public A
{
public:
    virtual RetA GetValue () { return RetB (); }
};

int main (int argc, char *argv[])
{
    A instance_A;
    B instance_B;
    RetA ret;

    printf ("Test instance A: ");
    ret = instance_A.GetValue ();
    ret.PrintMe (); // Expected result: "Return class A"

    printf ("Test instance B: ");
    ret = instance_B.GetValue ();
    ret.PrintMe (); // Expected result: "Return class B"

    return 0;
}

So, does virtual methods not work when returning a value? Should I revert to allocating the return class on the heap, or is there a better way?

(In reality I want to do this to let some different classes that inherits from a container class to return different iterator class instances depending on class ...)


Solution

  • Polymorphic behavior does not work by value, you need to return pointers or references for this to work.

    If you return by value you get what is known as "slicing" which means that only the parent part of the object gets returned, so you've successfully striped a child object into a parent object, this is not safe at all.

    Take a look at: What is object slicing?