Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for solving error: "cannot instantiate abstract class"

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 abstract and the compiler doesn't list which functions are abstract. There's got to be a more intelligent way to solve these than reading the headers 10 times until I finally notice a missing "const" somewhere. How do you solve these?

like image 206
max Avatar asked Nov 09 '09 05:11

max


People also ask

Why can you not instantiate an abstract class?

We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.

Why can't we instantiate an abstract class in C?

We can't instantiate an abstract class because the motive of abstract class is to provide a common definition of base class that multiple derived classes can share.

Can we instantiate an abstract class in C++?

An abstract class is, conceptually, a class that cannot be instantiated and is usually implemented as a class that has one or more pure virtual (abstract) functions. A pure virtual function is one which must be overridden by any concrete (i.e., non-abstract) derived class.

Can I instantiate abstract class PHP?

Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract.


2 Answers

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.

like image 63
James McNellis Avatar answered Sep 17 '22 22:09

James McNellis


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.


like image 31
bdonlan Avatar answered Sep 16 '22 22:09

bdonlan