Re: pointer equality and inheritance

From: John Harrison (john_andronicus_at_hotmail.com)
Date: 04/01/04


Date: Thu, 1 Apr 2004 22:53:44 +0100


"sb" <spam_bait101@yahoo.com> wrote in message
news:221dd125.0404011328.4f48de15@posting.google.com...
> Given this relationship,
>
> class Base {
> //...
> };
>
>
> class Derived : public Base {
> //...
> bool myself(const void* p) { return p == this}
> };
>
>
>
> Is there a guarantee in the standard that
>
> Derived d;
> Base* p = &d;
> d.myself((void*)p); // - ?
>
> will be always true?

No.

class Base
{
};

class Derived : public Base
{
public:
virtual ~Derived() {}
bool myself(const void* p) { return p == this; }
};

int main()
{
Derived d;
Base* p = &d;
cout << (d.myself(p) ? "true\n" : "false\n");
}

prints false on my system. The virtual destructor in Derived but not in Base
is what spoils things.

john



Relevant Pages