Reskareth
Reskareth

Reputation: 47

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

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

Upvotes: 0

Views: 389

Answers (1)

Stephen Newell
Stephen Newell

Reputation: 7828

You cannot pass or store a Rule by value since it has pure virutal member functions. Instead, you'll need to store the Rule as either a pointer or a reference. A good starting point is to use a std::unique_ptr:

class OptionalRule : public Rule {
private:
    std::unique_ptr<Rule> m_rule;

public:
    OptionalRule(std::unique_ptr<Rule> rule)
    : m_rule{std::move(rule)} { }
};

You can use another smart pointer (e.g., std::shared_ptr<Rule>) if that fits your needs better.

Upvotes: 1

Related Questions