Method for solving error: “cannot instantiate abstract class”

前端 未结 3 1787
情话喂你
情话喂你 2020-12-17 16:45

I find one of the most time-consuming compiler errors for me is \"cannot instantiate abstract class,\" since the problem is always that I didn\'t intend for the class to be

相关标签:
3条回答
  • 2020-12-17 17:21

    cannot instantiate abstract class

    Based on this error, my guess is that you are using Visual Studio (since that's what Visual C++ says when you try to instantiate an abstract class).

    Look at the Visual Studio Output window (View => Output); the output should include a statement after the error stating:

    stubby.cpp(10) : error C2259: 'bar' : cannot instantiate abstract class
    due to following members:
    'void foo::x(void) const' : is abstract
    stubby.cpp(2) : see declaration of 'foo::x'
    

    (That is the error given for bdonlan's example code)

    In Visual Studio, the "Error List" window only displays the first line of an error message.

    0 讨论(0)
  • 2020-12-17 17:24

    C++ tells you exactly which functions are abstract, and where they are declared:

    class foo {
            virtual void x() const = 0;
    };
    
    class bar : public foo {
            virtual void x() { }
    };
    
    void test() {
            new bar;
    }
    
    test.cpp: In function ‘void test()’:
    test.cpp:10: error: cannot allocate an object of abstract type ‘bar’
    test.cpp:5: note:   because the following virtual functions are pure within ‘bar’:
    test.cpp:2: note:       virtual void foo::x() const
    

    So perhaps try compiling your code with C++, or specify your compiler so others can give useful suggestions for your specific compiler.


    0 讨论(0)
  • 2020-12-17 17:26

    C++Builder tells you which method is abstract:

    class foo {
        virtual void x() const = 0;
    };
    
    class bar : public foo {
        virtual void x() { }
    };
    
    new bar;
    

    [BCC32 Error] File55.cpp(20): E2352 Cannot create instance of abstract class 'bar'
    [BCC32 Error] File55.cpp(20): E2353 Class 'bar' is abstract because of 'foo::x() const = 0'
    
    0 讨论(0)
提交回复
热议问题