Topic: dynamic_cast<T> question


Author: olaf@cwi.nl (Olaf Weber)
Date: Mon, 8 Aug 1994 07:19:30 GMT
Raw View
In article <776021916snz@storcomp.demon.co.uk>, Philip@storcomp.demon.co.uk (Philip Hugh Hunt) writes:

> Would this work:

> class A {...};
> class B {...};
> /* Both A and B include virtual functions */

> class C: public A, public B {...};

> void f()
> {
>    A* a;
>    C* c = new C;
>    B* b;

>    a = c;
>    b = dynamic_cast<B*>(a);
>    ...
> }

Yes.  Details are given in the chapter on ANSI/ISO resolutions found
in newer printings of Stroustrup2e and the ARM (subsection 5.2.6).
The latest version of that text for Stroustrup2e is available on the
net as:
 ftp://ftp.std.com/AW/stroustrup2e/iso.ps
it is dated May 3 1994.

-- Olaf Weber




Author: etse@scdt.intel.com (Eric Tse)
Date: 2 Aug 1994 16:45:31 GMT
Raw View
Hi,

 I wonder if I could do a safe down cast of the
following using dynamic_cast<T> keyword:

class B {..};
class D : public B {..};
class G : public D {..};

void f(){
 B* b = 0;
 D* d = 0;
 G* g = new G();

 b = g;

 d = dynamic_cast<D*>(b);
 ...
}

 Thanks.

Eric

--
---------------------------------------------------
Eric Tse   etse@scdt.intel.com
Intel Corporation       (408) 765-8453
---------------------------------------------------




Author: jason@cygnus.com (Jason Merrill)
Date: Tue, 2 Aug 1994 20:05:35 GMT
Raw View
>>>>> Eric Tse <etse@scdt.intel.com> writes:

>  I wonder if I could do a safe down cast of the
> following using dynamic_cast<T> keyword:

> class B {..};
> class D : public B {..};
> class G : public D {..};

> void f(){
>  B* b = 0;
>  D* d = 0;
>  G* g = new G();

>  b = g;

>  d = dynamic_cast<D*>(b);
>  ...
> }

If B has virtual functions, yes.  Otherwise, no.

Jason




Author: Philip@storcomp.demon.co.uk (Philip Hugh Hunt)
Date: Thu, 4 Aug 1994 17:38:36 +0000
Raw View
Would this work:


class A {...};
class B {...};
/* Both A and B include virtual functions */

class C: public A, public B {...};

void f()
{
   A* a;
   C* c = new C;
   B* b;

   a = c;
   b = dynamic_cast<B*>(a);
   ...
}








--
Phil Hunt




Author: b91926@fsgi01.fnal.gov (David Sachs)
Date: 5 Aug 1994 14:13:15 -0500
Raw View
Philip@storcomp.demon.co.uk (Philip Hugh Hunt) writes:


>Would this work:


>class A {...};
>class B {...};
>/* Both A and B include virtual functions */

>class C: public A, public B {...};

>void f()
>{
>   A* a;
>   C* c = new C;
>   B* b;
>
>   a = c;
>   b = dynamic_cast<B*>(a);
>   ...
>}

Yes, this construct in known as a "sideways" dynamic cast, and
works with BCC 4.

Though not stated in the documentation, the target base class
(B in your example) apparently must be a public base class of
the type of the actual object (C in your example). Mere
accessability is not enough.

Apparently, the C++ standards committee is working on this and
related issues.