C++ abstract classes

C++ abstract classes

What are Abstract Classes? Please explain with an example.

An abtract class has at least one pure virtual member function. A pure virtual member function is a non-implemented function that serves as a means of enforcing a common interface, or services, in derived classes.

For example, an abstract class File can define abstract operations such as Open and Read, which must be overridden in classed derived from it.

class File{public:void virtual Open() = 0; //pure virtualvoid virtual Read() = 0; //pure virtual//..};

This abstract class ensures that every class derived from it supports the Read and Open services:

class TextFile: public File{public:void Open() {/*..*/}void Read() {/*..*/}}

Note that you cannot create an instance of an abstract class but you can create pointers to abstract classes.

Unfortunately, many people, as well as primer books, confuse the terms “abstract class” and “abstract data type”. It’s important to realize that an abstract data type is anything but an abstract class: it has no base class, and no virtual member functions. For example, std::string and std::vector are abstract data types, while class File above is an abstract class.


Share the Post: