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
?
-
You can also declare references for abstract classes like `foo&`. – iammilind Apr 18 '11 at 06:37
-
Because I want to manipulate object of type shape generically (thus I need a pointer or reference to a shape). But I definitely do not want objects of type shape as this is an abstraction I need objects that are square's or circles. – Martin York Apr 18 '11 at 06:51
5 Answers
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)

- 24,532
- 6
- 47
- 87
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();

- 45,586
- 12
- 116
- 142
Also since abstract classes are usually use as parents (Base Classes - ABC's) which you use for polymorphisem
class Abstract {}
class DerivedNonAbstract: public Abstract {}
void CallMe(Abstract* ab) {}
CallMe(new DerivedNonAbstract("WOW!"));

- 8,725
- 14
- 49
- 86
Because a pointer to a foo is not a foo - they are completely different types. Making a class abstract says that you can't create objects of the class type, not that you can't create pointers (or references) to the class.
Because if we declare foo that meanz we are creating an instance of class foo which is an abstract, and it is impossible to create the instance of an abstract class. However, we can use the pointer of an abstract class to point to its drive classes to take the advantages of polymorphism. . .

- 41
- 1
- 8