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 ...)