class A{
public:
A(){
this->draw();
}
virtual void draw()=0;
};
Does it cause compile error. If yes, why. If no, why?
class A{
public:
A(){
this->draw();
}
virtual void draw()=0;
};
Does it cause compile error. If yes, why. If no, why?
First, the call of the pure virtual from the constructor is Undefined Behavior.
C++11 §10.4/6:
“the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.”
Then your question is if UB in general, as this is, requires a diagnostic.
It does not.
Although notes are not normative, the following note from C++11 §1.3.24 clarifies:
“Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message)”
Your compiler, with the specific options that you choose, may or may not emit a diagnostic, and then may or may not produce an executable. If it does, execution of the constructor may or may not result in some run time error. In short, it's Undefined Behavior.
Why is the call Undefined Behavior? Why could it not, for example, call an implementation in a derived class?
Well, if it could, then code in the derived class could be executed before the derived class instance was initialized, which means that it could be executed with faulty assumptions about instance variable values, which means it could easily lead to bugs.
And that's the situation in e.g. Java and C#.
In C++, however, execution of code in a constructor or destructor of a class T
is performed with the *this
object of dynamic type T
. Calls to virtual functions here have the same effect as if the object was originally instantiated as T
(even if T
has pure virtual functions). This ensures that the effect of the code is independent of what may be done in derived classes, that you as the T
programmer really know what you have at hand.
And with these more type safe rules there can't be any derived class implementation of the pure virtual function, because in this context there is no derived class part of the object: it's purely a T
object.
Yes, it will cause an error.
Pure virtual functions are used to make your class abstract meaning that any class that inherits from that class must implement your virtual function.
For example say you have a class B which inherits from your class A, you must implement the draw() method there, and you may call it there. But you never call a pure virtual function in the class that it is defined in.