Casting with MI classes

P

Paul Richards

Hi,
I remember reading something regarding this in one of my C++
textbooks, but unfortunately I do not have those available to me right
now..

Say I have some classes which do a little bit of funky MI...

class BaseA {
.....
};

class BaseB {
.....
};

class Derrived : public BaseA, public BaseB {
.....
};

Say I have a pointer to Derrived as such:
Derrived *d = new Derrived();

I can cast it to either BaseA* or BaseB* of course very easily:
BaseA *a = d;
BaseB *b = d;

What I can't remember is whether it'll work to cast BaseA* to/from
BaseB* assuming I know that I really do have an instance of Derrived..
[style A]: a = (BaseA*)b; // is this ok?

I have a feeling that this isn't safe. Do I need to use dynamic_cast
down to Derrived* then back up?
[style B]: a = dynamic_cast<Derived*>( b );

Or am I getting mixed up, is style A safe so long as my inheritances
aren't virtual?
 
P

Phlip

Paul said:
What I can't remember is whether it'll work to cast BaseA* to/from
BaseB* assuming I know that I really do have an instance of Derrived..
[style A]: a = (BaseA*)b; // is this ok?

I have a feeling that this isn't safe. Do I need to use dynamic_cast
down to Derrived* then back up?
[style B]: a = dynamic_cast<Derived*>( b );

Or am I getting mixed up, is style A safe so long as my inheritances
aren't virtual?

Style A is not safe because it has a C-style typecast. Never use one again.
Always use an elaborate_cast<>().

dynamic_cast<> exploits RTTI to safely find the BaseA inside the *b object.
But test 'a' for NULL before using it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top