Why did I get the error “error C2259: … cannot instantiate abstract class”?

前端 未结 3 1052
太阳男子
太阳男子 2021-01-29 02:46

Any help is appriciated. I\'m working on a C++ factory pattern and i get this error.

1>c:\\users\\brian\\documents\\visual studio 2010\\projects\\cst276lab_3\\guitar.hpp

相关标签:
3条回答
  • 2021-01-29 03:08

    To fix the specific problem, you need to declare a destructor for ElectricGuitarComponentFactory because you have declared the destructor of the base class as a pure virtual function. Why you have declared the base class destructor as pure virtual, I don't know; it really doesn't make any sense to do that. The destructor should be declared virtual, but not as pure virtual.

    Also, the syntax you have used,

    public: virtual ~GuitarComponentFactory() = 0 {}
    

    is ill-formed. You cannot declare a pure virtual function and provide a definition for it in the class definition. If you want to provide a definition for a pure virtual function, you must do so outside of the class definition. The compiler you are using, Visual C++, is a bit lenient with respect to this rule.

    0 讨论(0)
  • 2021-01-29 03:24
    class GuitarComponentFactory 
      {
         public: virtual ~GuitarComponentFactory() = 0 {}
      };
    

    In your derived ElectricGuitarComponentFactory you don't provide a destructor, hence it's still an abstract class.

    0 讨论(0)
  • 2021-01-29 03:32

    ElectricGuitarComponentFactory inherits GuitarComponentFactory ....

    When you inherit an abstract class (abstract = has pure virtual methods), then you need to override all those methods.

    in GuitarComponentFactory you got 7 methods, and in ElectricGuitarComponentFactory you only declared 6.

    You forgot to override the destructor.

    0 讨论(0)
提交回复
热议问题