Search code examples
c++ooppolymorphismabstract-classpure-virtual

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


I have an abstract base class defined like this:

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

I will have a bunch of derived classes 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 derived class objects in an container of some sort, like this:

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 derived class at runtime (either BNode or CNode). I implemented performChecks() in the base class, because I don't want to implement it in all the derived classes, the only thing that changes is the getType() method depending on the derived class.

Is this a good design? Should I ever be calling a virtual method from inside of another concrete method?


Solution

  • Yes, it would work. But storing raw pointers inside a vector is not a good idea, use smart pointers or boost pointer container if that’s not an overkill.