"Anonyomous" Objects
I am having great troubles with "anonymous" objects.
That might not be the correct term, but I just mean an
object created on the stack but never given a name.
These objects apparently do not follow the rules of
virtual inheritance.
The code below outputs the following:
B::func()
B::func()
A::func()
A::func()
The behavior is the same on both g++ and in MS Visual
Studio 2005.
The most obvious workaround would be to avoid using
anonymous objects. Unfortunately, I really NEED to use
them. I can explain the details of why I need to do
this, if it matters.
I've spent a day experimenting and I've found that the
behavior is very fickle. For example, removing the
constructor and destructor from class A changes the
output to:
B::func()
B::func()
B::func()
B::func()
Can anyone explain what's going on? Thanks in advance.
----- begin code: -----
#include "stdio.h"
class A
{
public:
A() {}
virtual ~A() {}
virtual void func() { printf("A::func()\n"); }
};
class B: public A
{
public:
void func() { printf("B::func()\n"); }
};
class C: public B
{
};
C x()
{
C new_C;
return new_C;
}
int main(int argc, char **argv)
{
// Call a method in an anonyomus object.
// This works.
x().func();
// Call a method in an anonymous object through a
pointer.
// This looks a little strange, but works.
(&(x()))->func();
// Should be exactly the same as above, but split
into two lines.
// This calls A::func() even though func() is
virtual!
A *A_ptr = &(x());
A_ptr->func();
// This also calls A::func(), even though the
pointer
// is of type "pointer-to-C"!!
C *C_ptr = &(x());
C_ptr->func();
return 0;
}
----- end code -----