Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class with pure virtual method - why is it possible to do "Abstract * abs3;"?

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

like image 670
Ron_s Avatar asked Dec 05 '22 20:12

Ron_s


1 Answers

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;
}
like image 123
Dave S Avatar answered Jan 22 '23 22:01

Dave S