Question About Polymorphism And Function Calls | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Question About Polymorphism And Function Calls

Can a polymorphed class only call functions that exist/are derived from the base class if the object is a pointer to the base class? And if so, is there a possible work-around to call the derived functions? class A{ public: virtual void go() = 0; }; class B : public A{ public: void go() { //stuff } void stop() { //other stuff } }; int main() { A *a = new B; a->go(); a->stop(); //Doesn't know about 'stop' }

5th Sep 2017, 12:44 AM
Alex
3 Answers
+ 11
not that I am aware. Having a stop() in A is how I would go about this.
5th Sep 2017, 1:30 AM
jay
jay - avatar
+ 4
You can always recast it to call derived functions. This will work: https://code.sololearn.com/c3auwm2ywMkO/#cpp
5th Sep 2017, 2:12 AM
aklex
aklex - avatar
+ 2
I would use a dynamic_cast <> in this case though, just in case. Then check that it's not a nullptr before using it.
5th Sep 2017, 5:35 AM
Zeke Williams
Zeke Williams - avatar