Because this is the purpose of the notion, to prevent instantiation of abstract classes.
In this case, the class can be called
abstract, because it contains at least one
pure virtual function (the one with "= 0" following the declaration,
display
in the code sample), which also can be called "abstract". Imagine what
would have happened if you could instantiate such class:
Base b;
b.display();
Note that it is impossible for the compiler to deny compilation of
b.display()
, because this line could be valid if the
runtime type of
b
wasn't
Base
, but was a class derived from
Base
, with properly overridden
display()
. And this is the whole idea of the purpose of abstract classes: to serve as a base class for derived classes and provide a common interface for them. In such cases, the
compile-time type of instantiated object could be the base class, but all actual
runtime types should be all non-abstract. This is enforced by having the compiler preventing instantiation of abstract types (
class
or
struct
).
[EDIT]
Thanks to the important comments by Stefan Lang (please see below), I improved the answer. I removed the mention that the pure virtual function has no implementation, because it can have one:
http://en.cppreference.com/book/intro/abstract_classes[
^].
Adding the implementation does not make a type non-abstract; the implementation can be used for whatever purpose in the derived classes. When the using code calls this function, such outside call will always be dispatched to one of the implementations of this function in one of derived classes, because overriding of the pure virtual function is required to make a non-abstract type; and only a non-abstract type can be instantiated.
Also, in my comment to the question, I explained in what cases the compiler cannot deny the compilation of
b.display()
. Of course, in principle, the compiler could analyze and find out that this line makes no sense, based on the declaration of
b
. But let's consider the cases when this is not so.
For example,
class Base {} class Derived : public Base {}
Let's say we have function
void SomeExample(Base* b) { b->display(); }
or
void SomeExample(Base& b) { b.display(); }
Should it compile? Yes, always. This is because the function does not "know" the runtime type of
b
. It can be called with any of the derived types, and
Base
serves as a common interface for them.
Note that, in the last code sample, the line which should compile is exactly the same as in the very first "impossible" code sample:
b.display();
but in this context it should compile and will work, exactly by the reason I started with: the runtime type of
b
cannot be
Base
, the compiler will prevent instantiation of an abstract class.
—SA Codeproject Bot