Andrew's answer is very good but need some notes.
I would like to emphasize that the concept of abstract class is irrelevant to availability of constructor(s). That could cause some misunderstanding. See below.
As Andrew correctly explained us, "abstractness" of a class is recognized by one or more "pure virtual functions", his example:
GraphFunc()
. The compiler will not compile initialization if such class -- for a good reason (what should happen with the instance if someone calls a pure virtual function?). For more modern OOP languages a special keyword
abstract
is used to denote a class (or a method, a syntax used for the same purpose as C++ as pure virtual) as abstract. The sole purpose of the abstract class is to server as a base class for derived non-abstract classes.
Using declarations from Andrew's sample, we can add:
class RectangularGraph : public Graph {
public:
RectangularGraph(int nMyInt, int extraData) :
Graph(nMyInt) { m_extraData = extraData; }
virtual void GraphFunc() { }
private:
int m_extraData;
};
RectangularGraph(2);
So, my point here is, if an abstract class cannot be "constructed" (a class instance can not be initialized), why it needs a constructor?
This is because a constructor, strictly speaking, has nothing to do with instance initialization -- it is designed to initialize
part of the instance: see constructor
RectangularGraph
: it is composed of two parts: it's base is constructed first (came from
Graph
class), then the rest of the class
RectangularGraph
. Finally, it should be noted that a parameterless constructor of a base class (no matter abstract or not) is called automatically.
This way, not only constructors of abstract class is allowed -- it's very important. Look at the sample: how else
m_nMyInt
(see Andrew's sample) could be initialized, if it is not accessible for derived classes?