devxlogo

C++ abstract classes

C++ abstract classes

Question:
What are Abstract Classes? Please explain with an example.

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

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist