Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Design Patterns
Expertise: Beginner
Sep 7, 1999

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

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap