abstract class declarations in c++

99封情书 提交于 2019-12-01 04:11:46

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!