How do you handle a “cannot instantiate abstract class” error in C++?

后端 未结 8 2098
暗喜
暗喜 2020-12-15 17:02

How do you handle a \"cannot instantiate abstract class\" error in C++? I have looked at some of the similar errors here and none of them seem to be exactly the same or prob

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 17:48

    The error means there are some methods of the class that aren't implemented. You cannot instantiate such a class, so there isn't anything you can do, other than implement all of the methods of the class.

    On the other hand, a common pattern is to instantiate a concrete class and assign it to a pointer of an abstrate base class:

    class Abstract { /* stuff */ 4};
    class Derived : virtual public Abstract { /* implement Abstract's methods */ };
    
    Abstract* pAbs = new Derived; // OK
    

    Just an aside, to avoid memory management issues with the above line, you could consider using a smart pointer, such as an `std::unique_ptr:

    std::unique_ptr pAbs(new Derived);
    

提交回复
热议问题