abstract class declarations in c++

2020-03-19 03:04发布

问题:

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?

回答1:

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)



回答2:

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();


回答3:

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!"));


回答4:

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.



回答5:

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. . .