D pointers #2

Luís Pedro Coelho luis at luispedro.org
Thu Oct 20 18:43:59 BST 2005

On Thursday 20 October 2005 06:27, Thiago Macieira wrote:
>   Maks Orlovich wrote:
> >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.
> Right. But the point is: people expect it to output C, C, C, because it's
> the virtual function "virt" that is called. I remember a certain job
> interview asking exactly that, recently :-)

BTW, Java does that. On the one hand, it can be said to be the expected 
behaviour, on the other hand if C::virt() uses a member object, it could be 
messy (undefined behaviour, ie crashes). C++ always chooses "do the correct 
thing even if its ugly and unexpected and not at all intuitive and the wrong 
behaviour only happens in very special circumstances".

Replace your struct C with this

struct C: public B
        C():type("C") {

        virtual void virt() {
                std::cout << this->type << "\n";
	std::string type;

to see why it was done like this in C++.

More information about the kde-core-devel mailing list