-1

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?

user63898
  • 29,839
  • 85
  • 272
  • 514
  • 2
    The problem is that `AA::getC1` returns a `ICC` ***instance***, which is not possible since it's abstract. Not to mention you will have [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing), and polymorphism not working without pointers (or references). Why does it have to return an instance instead of a pointer? – Some programmer dude Feb 03 '21 at 07:16
  • Polymorphism requires pointers in any language. It's the nature of the beast. The difference in C++ is that the pointers are explicit, whereas in other languages (e.g. Java) they are implicit. But in all cases a polymorphic interface requires a pointer. – john Feb 03 '21 at 07:55

2 Answers2

1

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.

1

If you have at least one pure virtual function in a class, it is considered as an abstract class. These classes cannot be instantiated. Only pointers are allowed (or references).

And in this function,

 virtual BB launch(std::map<std::string, std::string>& ops) = 0;

Your returning an object instance of an abstract class. This is not allowed as I stated before. You have to return an pointer or a reference, if not things wont work properly.

D-RAJ
  • 3,263
  • 2
  • 6
  • 24