call overwritten child function within parent func

2019-08-02 02:52发布

问题:

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;
}