Polymorphism and Template-Based Designs

Abstraction

Currently, the most-used method of implementing polymorphism in C++ is by using inheritance and virtual functions. The same thing also can be designed using templates.

Some of the design decisions based on virtual functions and inheritance (dynamic polymorphism) are:

  1. Increases the complexity
  2. Becomes fat and time consuming
  3. Less flexible

By carefully designing the applications using the templates, you can solve these design problems.

Polymorphic-Based Design Through Inheritance and Virtual Functions (Dynamic Polymorphism)

  1. Identify the abstraction.
  2. Declare the common methods in the abstract base class as virtual.
  3. Provide the context-dependent implementations in the derived classes.

For example:


class File {
public:
virtual void Open() = 0;
virtual void Save() = 0;
virtual void SaveAS(String&) = 0;
virtual void Close() = 0;
};
class TextFile:public File{
public:
void Open();
void Save();
void SaveAS(String&);
void Close();
};
class ImageFile:public File{
public:
void Open();
void Save();
void SaveAS(String&);
void Close();
};

// user menu selection to open the file
void menu_open_file(File* f_ptr){
f_ptr->Open();
….

}

By using the above code, you would have the following:


File *file_ptr = new TextFile();
menu_open_file(file_ptr);//open the text file
.
.
file_ptr = new ImageFile();
menu_open_file(file_ptr);//open the image file

  1. In above example, the file is the abstraction. It has been declared as an abstract base class.
  2. Open, Save, SaveAs, and Close are common methods that are declared as virtual in the File class.
  3. Concrete implementations of the file abstractions are the image file and text file that are provided the context-dependent implementations.
  4. This will work along with the Open, Close, Save, and SaveAS menu operations.
  5. If user selects File Open, based on the file type, the menu selection function calls the context-dependent function.

Template-Based Polymorphic Design

Templates will not force you to declare the common methods in the base class. But, they will force the application to declare the common methods implicitly.

Designing the above example using the template based design:


class TextFile{
public:
void Open();
};

class ImageFile{
public:
void Open();
};

//user menu selection to open the file

template<typename T> void menu_open_file(T file){
file.Open();
}

Using the code:


TextFile txt_file;
ImageFile img_file;
menu_open_file(txt_file); //open the text file
menu_open_file(img_file); //open the image file

  1. Define the concrete classes text file and image file.
  2. Define the client code as template: menu_open_file.
  3. In templates, there is no need to use pointers or references.

More by Author

Must Read