Abstract Classes, Polymorphism C++ – Calling pure virtual method in another function

  abstract-class, c++, oop, polymorphism, pure-virtual

I have an abstract class defined like so:

class NodeSubElementEnforceType {
    public:
        virtual void getType() = 0;
        void performChecks() {
            getType();
            // other things ......
        }
};

I will have a bunch of subclasses extending this class that will each have their own implementation of the getType() method, for example:

class BNode : public NodeSubElementEnforceType {
    public:
        void getType() {
            // ..... BNode implementation ....
        }
}

class CNode : public NodeSubElementEnforceType {
    public:
        void getType() {
            // ..... CNode implementation ....
        }
}

I will be storing NodeSubElementEnforceType objects in an container of some sort:

std::vector<NodeSubElementEnforceType*> allNodes;
NodeSubElementEnforceType* node1 = new BNode();
NodeSubElementEnforceType* node2 = new CNode();
allNodes.emplace_back(node1);
allNodes.emplace_back(node2);

Now, I simply want to iterate over all the objects in the vector and call the performChecks() method of each object.

for (unsigned i = 0; i < allNodes.size(); i++) {
    allNodes.at(i)->performChecks();
}

My question is, will this work the way I am hoping? I want performChecks() to call the getType() method of the correct class at runtime (either BNode or CNode). I implemented performChecks() in the parent class, because I don’t want to implement it in all the child classes, the only thing that changes is the getType() method depending on the child class.

Source: Windows Questions C++

LEAVE A COMMENT