0

Consider the fallowing code:

class BaseParameter
{
protected:
    int value;

public:
    BaseParameter(int v) : value(v) { }

    virtual void print() = 0;
};

class MyParam : public BaseParameter
{
public:
    MyParam(int v): BaseParameter(v) { }

    void print() override
    {
        std::cout << "Param value: " << value << std::endl;
    }
};

int main()
{
    std::vector<BaseParameter> paramsVector;

    paramsVector.push_back(MyParam(1));
    paramsVector.push_back(MyParam(2));
    paramsVector.push_back(MyParam(3));
    paramsVector.push_back(MyParam(4));

    for (BaseParameter& p : paramsVector)
    {
        p.print();
    }
}

The code above is a basic representation of a more complex code I have in a project. However, this distills the problem to the basic form.

Why do I get the "cannot instantiate abstract class" error? How to over come this issue so I can use a base class and many different parameter classes and iterate and print all according to the interface?

NirG
  • 71
  • 1
  • 7

1 Answers1

2

Because BaseParameter has abstract method print(). You need to declare a vector of raw or smart pointers for it, not class itself. For example, following code works:

int main()
{
    std::vector<std::unique_ptr<BaseParameter>> paramsVector;

    paramsVector.push_back(std::make_unique<MyParam>(1));
    paramsVector.push_back(std::make_unique<MyParam>(2));
    paramsVector.push_back(std::make_unique<MyParam>(3));
    paramsVector.push_back(std::make_unique<MyParam>(4));

    for (const auto& p : paramsVector)
    {
        p->print();
    }
}

In addition, don't forget you need a virtual destructor for base class if you are using polymorphism:

virtual ~BaseParameter() = default;
Afshin
  • 8,839
  • 1
  • 18
  • 53
  • Thanks! but why is that different? – NirG Aug 29 '22 at 07:59
  • @NirG You cannot create instance of a class with abstract methods. These abstract method have no definitions in their class. But when you inheriting from these classes and implement them, they find a definition in inherited class. if you want to use polymorphism to access members of a inherited class from parent class, you need to keep a pointer or reference of them in a parent class type. This mistake is somehow common for someone who comes to c++ from a language like Java because it is done internally in those languages. – Afshin Aug 29 '22 at 08:04
  • I thought of sharing few more information. If you are going to use static object alone/ClassName(parameter) you can use: vector paramsVector; and paramsVector.push_back(MyParam(1)); – murugesan openssl Aug 29 '22 at 08:26