Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstract class declarations in c++

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?

like image 417
Glove Avatar asked Apr 18 '11 06:04

Glove


2 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)

like image 53
SJuan76 Avatar answered Sep 23 '22 19:09

SJuan76


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();
like image 23
taskinoor Avatar answered Sep 24 '22 19:09

taskinoor