Abstract class declarations in C ++

Suppose it foois abstract classin a C ++ program, why is it permissible to declare type variables foo*, but not type variables foo?

+5
source share
5 answers

Because if you declare foo, you have to initialize / create it. If you declare * foo, you can use it to specify instances of classes that inherit from foo but are not abstract (and therefore can be created)

+12
source

You cannot instantiate an abstract class. There are differences in the 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();
+2

, ( - ABC), polymorphisem

class Abstract {}

class DerivedNonAbstract: public Abstract {}


void CallMe(Abstract* ab) {}


CallMe(new DerivedNonAbstract("WOW!"));
+1

foo foo - . , , , ( ) .

0

Because if we declare foo that meanz, we create an instance of the class foo that is abstract, and it is not possible to instantiate an abstract class. However, we can use an abstract class pointer to point to its disk classes to take advantage of polymorphism.,.

0
source

All Articles