Quantcast
Channel: User Karthik T - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by Karthik T for assigning derived class pointer to base class pointer in C++

$
0
0

If you are adamant that this function should NOT be a part of base, you have but 2 options to do it.

Either use a pointer to derived class

derived* pDerived = new derived();pDerived->myFunc();

Or (uglier& vehemently discouraged) static_cast the pointer up to derived class type and then call the function
NOTE: To be used with caution. Only use when you are SURE of the type of the pointer you are casting, i.e. you are sure that pbase is a derived or a type derived from derived. In this particular case its ok, but im guessing this is only an example of the actual code.

base* pbase = new derived();static_cast<derived*>(pbase)->myFunc();

Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>