D pointers #2

Thiago Macieira thiago at kde.org
Thu Oct 20 19:10:53 BST 2005

Luís Pedro Coelho wrote:
>On Thursday 20 October 2005 06:27, Thiago Macieira wrote:
>> 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".

After being asked what would happen in that interview, I was asked why C++ 
chose to do it that way.

My answer was: because of multiple inheritance.

If you think a bit, you'll see that C++ could do the RightThing™ and still 
call virtuals through the virtual table from inside constructors if it 
were not for MI. The constructor flow is like this:

1) call parents' constructors
2) initialise variables
3) run code

If you exchanged 1 and 2, you'd arrive at the base class with all 
variables initialised by the time the first line of code were executed. 
But only for single inheritance. For it to work in MI, you'd need to call 
all parents' variable initialisation and only then start code exection.

class C: public A, public B
You'd need to initialise all of A's member variables, then B's and only 
then run A's code.

Also note that, even with the RightThing™ C++ you can still manage to do 
WrongThings. Running the following program will produce junk in the 

#include <iostream>

using namespace std;

class MyClass
  class Private;
  Private * const d;
  int m_variable;


class MyClass::Private
  MyClass * const q;
  Private(MyClass* parent)
    : q(parent)
    cout << q->m_variable << endl;

  : d(new Private(this)), m_variable(0)
{ }

  MyClass c;

  Thiago Macieira  -  thiago (AT) macieira.info - thiago (AT) kde.org
    PGP/GPG: 0x6EF45358; fingerprint:
    E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358

5. Swa he géanhwearf tó timbran, and hwonne he cóm, lá! Unix cwæð "Hello, 
World". Ǽfre ǽghwilc wæs glæd and seo woruld wæs fréo.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20051020/face75d8/attachment.sig>

More information about the kde-core-devel mailing list