Recast a member variable in derived class?

D

David

Hello,

Is there a way to automatically have a member variable in a derived class
recast within that class. In other words, something like this:

class ABase
{
protected:
BBase *m_something;
public:
ABase(BBase *something);

..etc..
};

class ABaseDerived : public ABase
{
public:
ABaseDerived(BBaseDerived *something)

..etc..
};

I'd like m_something in ABaseDerived to be automatically cast to
BBaseDerived everyplace used in ABaseDerived.

Something like this:

class ABaseDerived : public ABase
{
protected:
reinterpret_cast<BBaseDerived *>(m_something); // this would be cool

public:
ABaseDerived(BBaseDerived *something)

..etc..
};


Is there a way to do that?

Thanks!
 
M

mlimber

David said:
Hello,

Is there a way to automatically have a member variable in a derived class
recast within that class. In other words, something like this:

class ABase
{
protected:
BBase *m_something;
public:
ABase(BBase *something);

..etc..
};

class ABaseDerived : public ABase
{
public:
ABaseDerived(BBaseDerived *something)

..etc..
};

I'd like m_something in ABaseDerived to be automatically cast to
BBaseDerived everyplace used in ABaseDerived.

Something like this:

class ABaseDerived : public ABase
{
protected:
reinterpret_cast<BBaseDerived *>(m_something); // this would be cool

public:
ABaseDerived(BBaseDerived *something)

..etc..
};


Is there a way to do that?

No. Assuming BBase and BBaseDerived are related by inheritance as the
names imply, you could use dynamic_cast (not reinterpret_cast!), though
it would probably be poor design to do so in such a situation. The best
way to accomplish what you want is likely just to store a pointer to
BBaseDerived in ABaseDerived. Casting from BBase to BBaseDerived is
automatic, but casting the other direction should be avoided if
possible.

Cheers! --M
 

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,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top