Search code examples
c++pointersabstract-class

cpp 17 , cannot instantiate abstract class , way Interface must be pointer?


i try to create an interface in c++ that enables me to use it as i want different types to implement it. getting :

cannot instantiate abstract class

for example :

BB.h
class BB {
    public:
        BB() {}
};


ICC.h
class BB;
class ICC {
public:
    virtual BB launch(std::map<std::string, std::string>& ops) = 0;

};

C1.h
class C1: public ICC {
    public:
        C1() {}
        BB launch(std::map<std::string, std::string>& ops){};
};


AA.h

class C1;
class AA {
    public:
        AA() {}
    private:
        ICC getC1() {
            C1 c
            return c;
        }
        ICC cc;
        
};
 

if I convert the ICC to pointer like this: ICC *cc all work fine but why do i need to use a pointer here?


Solution

  • The problem is in AA.h. You can not instantiate cc.Also getC1() is maybe not implemented as intended, it is causing slicing problems. You can create instantiate only a pointer of ICC as it is pure virtual.

    If you further work with Base-pointer objects you may also consider to make the destructor virtual. (Delete on Base-Pointer objects will not call dtor of derived classes, if not declared virtual.) Another tip is to use override/final if you derive another method.