Suppose foo
is an abstract class
in a C++ program, why is it acceptable to declare variables of type foo*
, but not of type foo
?
Because if you declare a foo you must initialize/instantiate it. If you declare a *foo, you can use it to point to instances of classes that inherit from foo but are not abstract (and thus can be instantiated)
You can not instantiate an abstract class. And there are differences among following declarations.
// declares only a pointer, but do not instantiate.
// So this is valid
AbstractClass *foo;
// This actually instantiate the object, so not valid
AbstractClass foo;
// This is also not valid as you are trying to new
AbstractClass *foo = new AbstractClass();
// This is valid as derived concrete class is instantiated
AbstractClass *foo = new DerivedConcreteClass();
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