[comp.lang.c++] Calling virtual functions INDIRECTLY from constructors

jordan@aerospace.aero.org (Larry M. Jordan) (12/19/90)

Should there also be a loss of "virtualness" when virtual
member functions are called INDIRECTLY from a constructor?  


Consider the following:

#include <stdio.h>

static void say(char *s) { printf("%s\n", s); }


struct C0 {
	virtual void f() { say("C0 init"); }
	virtual void g() { f(); }
	C0() { g(); }
};

struct C1 : C0 {
	virtual void f() { say("C1 init"); }
	virtual void g() { f(); }
	C1() { g(); }
};


main()
{
	C0 aC0;
	C1 aC1;
}




I was expecting:

	C0 init
	C1 init
	C1 init

But got (from Zortech v2.1):

	C0 init
	C0 init
	C1 init


This seems like an amazing sleight of hand.  How do you suppose it's done?


-- Larry Jordan

jordan@aerospace.aero.org (Larry M. Jordan) (12/19/90)

I see how it might be done!  While in C0's constructor the "pre-object" is
momentarily pointing at C0's vft.  When it finishes with the last
constructor (C1) it will ultimately point to its class's vft.  

How does anyone (except a C++ compiler implementor) ever clearly understand
how C++ should behave?

haydens@natasha.juliet.ll.mit.edu (Hayden Schultz) (12/20/90)

The same result happens with Sun's CC (ATT cfront) compiler. My guess
is that when a new C1 instance is created, first the parent class
constructor is called, then the class constructor is called.

	Hayden (haydens@juliet.ll.mit.edu)

rfg@NCD.COM (Ron Guilmette) (12/22/90)

In article <94898@aerospace.AERO.ORG> jordan@antares.UUCP (Larry M. Jordan) writes:
+
+How does anyone (except a C++ compiler implementor) ever clearly understand
+how C++ should behave?

Even some of them don't! :-) :-)

-- 

// Ron Guilmette  -  C++ Entomologist
// Internet: rfg@ncd.com      uucp: ...uunet!lupine!rfg
// Motto:  If it sticks, force it.  If it breaks, it needed replacing anyway.