problems with constructors

Ross Smith ross.s@ihug.co.nz
Wed Nov 11 18:07:00 GMT 1998


From: C. van Reeuwijk <C.vanReeuwijk@twi.tudelft.nl>
>
>I'm having problems with some class constructors in one of my programs.
>It appears that in some circumstances the code that implements the
>constructor of a class does not return 'this', but an unspecified
>value. It does not seem to be an optimizer bug, since it occurs even
>without any optimizations on.
>
>WordListIndex::WordListIndex()
>{
>    ...
>    fprintf( stderr, "WordListIndex: this = %p\n", this );
>}
>
>    fullindex = new WordListIndex();
>    fprintf( stderr, "fullindex = %p\n", fullindex );
>
>this = 0x40934fd8
>fullindex = 0x40934ff8
>
>Which shows that something is wrong. Unfortunately, I have not been able
>to take it any further than that. Constructors work for most classes,
>but for this class, and a number of sibling classes, something is wrong.

You don't say what type fullindex is, but your reference to sibling
classes suggests that WordListIndex is part of an inheritance
hierarchy. If fullindex is declared as a pointer to some base type
rather than to WordListIndex itself, the above behaviour is perfectly
normal. A pointer to a derived class object can be freely converted to
a base class pointer, of course -- but the two pointers are not
obliged to point to the exact same memory location, and often don't
(especially if multiple inheritance is involved).

Example:

    class Base {};
    class Derived: public Base {}
    Derived d;
    Derived* dp = &d;
    Base* bp = &d;
    void* vdp = dp;
    void* vbp = bp;
    std::cout << (dp == bp) << std::endl;   // Required to be true
    std::cout << (vdp == vbp) << std::endl; // Not required to be true

--
Ross Smith ................................... mailto:ross.s@ihug.co.nz
.............. The Internet Group, Auckland, New Zealand ..............
                               * * * * *
      "Screw up your courage. You've screwed up everything else."





More information about the Gcc-bugs mailing list