call overwritten child function within parent function

喜你入骨 提交于 2019-12-11 14:14:47

问题


is it possible in c++ to call a child function from a parent function.

Let's take an example: The parent class defines in a function (parse) the general workflow. The workflow then calls different methods which represent part of the flow (parseElementA). These functions can be overwritten by the child class, if not the standart function, which is part of the parent shall be used.

My issue is: I create a child object and execute the workflow function (parse). When the overwritten function (parseElementA) is called within the workflow function it calls the function from the parent and not from the child. What could i do so it calls the overwritten function in child.

    class Parent {
      public:
        void parse() { parseElementA(); }
        virtual void parseElementA() { printf("parent\n"); }
    };

    class Child : public Parent {
      public: 
        void parseElementA() { printf("child\n"); }
    };

    Child child;
    child.parse();

the output is parent. What can I do that it returns child.

Thank you very much for any advice.


回答1:


After fixing compiler errors from your code, it works fine.




回答2:


#include <cstdio>

class Parent {
        public:
                void parse() { parseElementA(); }
                virtual void parseElementA() { printf("parent\n"); }
};

class Child : public Parent {
        public:
                void parseElementA() { printf("child\n"); }
};

int main() {

   Child child;
   child.parse();

   return 0;
}


来源:https://stackoverflow.com/questions/6568778/call-overwritten-child-function-within-parent-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!