Consider the following :
class Abstract
{
public:
virtual void func() = 0;
};
int main() {
Abstract abs1; // doesn't compile
Abstract * abs2 = new Abstract(); // doesn't compile
Abstract * abs3; // compiles
return 0;
}
Please notice that I didn't implement func()
, so why is it possible to do Abstract * abs3;
where we have a pure virtual method and an abstract class ?
I know that I'd get a run-time error if I'd try to do abs3->func(); , but still , it's not clear to me why C++ allows that code to compile ...?
thanks ,Ron
abs3
is a pointer to the class. It can be initialized to any concrete subclass of Abstract, or to NULL, safely. The compiler has to allow it because while you can't create abstract classes, you have to be able to create pointers to them. See below for an example
class Concrete: public Abstract
{
public:
virtual void func() { // do something };
};
int main ()
{
Abstract* abs3 = NULL;
abs3 = new Concrete;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With