ruben
ruben

Reputation: 1750

using derived class in runtime c++

this is checking in runtime if mybase class is a derived class. I need to call a member variable from say myDerived.member1 using myBase like myBase.member1 in runtime. Here myBase is a pointer. How to do that.

if(dynamic_cast<myDerived*>(myBase))

Upvotes: 0

Views: 58

Answers (1)

Carlton
Carlton

Reputation: 4297

I'd do it like this:

myDerived* p_derived = nullptr;
p_derived = dynamic_cast<myDerived*>(myBase);
if (p_derived != nullptr)
   //do something with p_derived->member1;

This way you're only making a (possibly expensive) call to dynamic_cast once.

Upvotes: 1

Related Questions