c++ - Inheritance: use inherited methods from parent pointer -


i'm working production code, of cannot safely modify (without breaking things). issue use specific method, 1 of parameters of pointer class. class parameter not want to.

so wrote sub-class of class , attempting call above function, still uses parent class' methods.

i have mwe below:

#include <iostream>  class parent  { public:     parent() {};     void method() {std::cout<<"in parent\n";} };  class child : public parent { public:     child() {};     void method() {std::cout<<"in child\n";} };  void secondmethod(parent* pptr) {     pptr->method(); }  int main() {     child c = child();     parent* parentptr = &c;      c.method();     parentptr->method();      secondmethod(parentptr);     secondmethod(&c);      return 0; } 

in above example running output of course:

in child in parent in parent in parent 

i believe issue slicing? i'm casting pointer of parent class, considered parent.

i have seen ways around making methods virtual in parent class don't have option.

is there way make secondmethod actual use child's method? without changing parent class or secondmethod.

no not if aren't able change parent class or 'secondmethod'. constructor of 'secondmethod' defines parameter parent*. passing child* 'secondmethod' cause child* upcast parent* , in turn cause parent's implementation of 'method' called.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -