Re: inheritance

From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 02/26/04


Date: Thu, 26 Feb 2004 00:45:37 GMT


"vsgdp" <nospam@nospam.com> wrote...
> Consider:
>
> #include <iostream>
> using namespace std;
> class A
> {
> public:
> A(){ p = this; }
> static A* p;
> };
> A* A::p = 0;
>
> class B : public A
> {
> public:
> B() : A() {}
> };
>
> int main()
> {
> B b;
> if( b.p == &b )
> cout << "Equal." << endl;
> }
> Output: Equal.
>
> Why does b.p point to b?

It doesn't.

> It seems it should point to the "A" part of b.

And it does.

> That is, Stroustrup says "In this respect, the base class acts exactly
like
> a member of the dervied class." (page 306 in special edition).
>
> However, the behavior of the program can be explained if we think of A()
as
> a "method" of B. But is that technically correct?

No.

> Accelerated C++ says
> constructors of a base class are not also members of the derived class.

The reason that the condition

    b.p == &b

evaluates to 'true' is simple: both sides need to be of the same type to
participate in comparison. The left side is of type A*. So, the right
side is _converted_ to A* using the standard "pointer to derived to pointer
to base" conversion.

Your mistake is to think of addresses as typeless. They aren't.

Victor



Relevant Pages

  • Re: why cant derived class pointer cant point to base class object
    ... a base class pointer can to point to derived class ... You can implicitly cast pointers to a base class, ...
    (comp.lang.cpp)
  • Base class method that returns a pointer to a derived class?
    ... I want to write a base class that includes a member function that creates an ... instance of a derrived class and returns a pointer to it. ... The derived class definition has to follow the base class ...
    (comp.lang.cpp)
  • Re: cannot set up function evaluation
    ... my pointer to my base class is different from the pointer to the ... of my function and simple passes the pointer of the derived class ... without casting it to the base class. ... This causes the function to 'crash', apparently the debugger runs these ...
    (microsoft.public.vc.debugger)
  • Re: Pointer to classes when deleted
    ... > virtual deleting an object of the derived class through a pointer ... > to a base class causes undefined behaviour. ...
    (comp.lang.cpp)
  • Re: ptr conversions and values
    ... >> each pointer pointed to a byte, ... Without that conversion, a pointer that points to an N-byte ... pointers to incomplete array types must indicate the start of the array ... >> It's all right, mostly equivalent with the previous one, representation ...
    (comp.std.c)