problems with constructors

C. van Reeuwijk C.vanReeuwijk@twi.tudelft.nl
Fri Nov 13 03:15: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

You are right, 'fullindex' is of a base class type.

Strictly speaking, you are right; it is not necessarily true that the
pointer to the base class is the same as the pointer to the subclass.
However:

(a) I should still be able to do 'delete fullindex;', but this statement
crashes. If I link in 'Electric fence', it tells me 'fullindex' is not a
malloc'ed pointer. The difference in pointers is a symptom of the problem;
the real problem is that 'delete fullindex;' crashes.

(b) If (implicit) casting a pointer to a base class changes it value,
doesn't this violate compatibility with C, where the casting rules for
struct pointers more-or-less fix their layout?

Does g++ in fact show this behavior? If so, how is 'delete' implemented?

(c) Note that the value of 'fullindex' is *larger* than the value of 'this'.
For some reason I would expect that for a superclass it would be smaller.

-- 
Kees van Reeuwijk, Delft University of Technology
http://www.pds.twi.tudelft.nl/~reeuwijk



More information about the Gcc-bugs mailing list