D pointers #2

Maks Orlovich mo85 at cornell.edu
Wed Oct 19 23:25:48 BST 2005


On Wednesday 19 October 2005 18:03, Guillaume Laurent wrote:
> On Wednesday 19 October 2005 23:53, Michael Pyne wrote:
> > Now I could be thinking things wrong here, but if I know my obscure C++
> > correctly, nothing is virtual in nature within the constructor of a
> > class.
>
> You're correct.

Not quite. Try out the following:

#include <iostream>

struct A
{
        A() {
		doStuff();
        }

	void doStuff(){
		virt();
	}

	virtual void virt() {
		std::cout << "A\n";
	}
};

struct B: public A
{
        B() {
		doStuff();
        }

	virtual void virt() {
		std::cout << "B\n";
	}
};

struct C: public B
{
        C() {
		doStuff();
        }

	virtual void virt() {
		std::cout << "C\n";
	}
};

int main() {
	C test;
}

---
It outputs A, B, C. If virtuals didn't work, it would output A, A, A. 
In fact, virtuals very much work inside the constructor --- except that when 
you're in a constructor of a superclass, your class -is- the superclass.

-Maks





More information about the kde-core-devel mailing list