Abstract Base Class create instance of derived class with Base class as type

  abstract, c++, class

I got a simple problem: I have a base class which is abstract, and I want to use it as type for a derived class. What I mean is this:

class Rule {
public:
    //Return value is equal to the count of consumned chars or -1 if the given chars are invalid for this rule
    virtual int parse(const std::string& text, unsigned int startIndex) = 0;
};

class OptionalRule : public Rule {
private:
    Rule m_rule;

public:
    OptionalRule(Rule rule) {
        m_rule = rule;
    }
};

This gives me the following error code: object of abstract class type is not allowed. Now I know that I can’t have an instance of Rule, but what I want is any subclass of Rule to be allowed. How do I do this? I’m aware that it has something to do with pointers, but I don’t quite understand why or how it works.

Thanks for any help!

PS: I know that I have to implement the virtual function in the class OptionalRule so that I can instantiate it

Source: Windows Questions C++

LEAVE A COMMENT