Abstract Classes

We have already seen the definition of abstract classes, the classes who serve the purpose of blueprint for subclasses and are never instantiated are called abstract classes.

Some points

  1. To protect abstract classes from getting instantiated, there constructors can be made protected. Though it is not a compulsion. (They are made protected and not private so they can be inherited)
  2. Abstract classes contain at least one pure virtual function

Pure Virtual Functions

A pure virtual function is a virtual function that has no definition within the base class. Following syntax is used for defining a pure virtual function:
virtual return-type function-name (parameter-list) = 0;

When a pure virtual function is given by a base class, it must be overridden by all of its derived classes i.e. the derived classes must provide their own definition for this pure virtual function.
This is used because sometimes there is no sense of providing a definition for abstract class version because they are never instantiated.
And also sometimes subclasses so no override virtual functions, it makes this a compulsion! This is the real example of polymorphism.

Sample Program illustration

class A                 //an abstract class
{
    int a;
    protected:
    A()
    {}
    ~A()
    {}
    public:
    virtual void foo() = 0;     //pure virtual function
};

class B
{
    int b;
    public:
    virtual void foo()
    {
        cout << foo << endl;
    }
};

A *a;
B b;
a = &b;
a -> foo();

In the example above, we see that B has defined its own version of foo().
If B would have not defined foo(), it would have given a compile time error.

Early Binding

Early binding refers to the event that occur at compile time.
When all the information to call a function is available at compile time it is called early binding.
Calls to normal functions, overloaded functions, etc.
comes under this category as all the things needed to call these functions are available at compile time. But important advantage of early binding is speed. As it is all available ay compile time, it is less overhead on runtime hence faster execution of programs.

Late Binding

Late binding refers to the event that occurs at runtime.
Sometimes which version of function is called is not determined until runtime, like virtual functions: which version of that function is to be called is not confirmed until runtime (where the pointer of base class points). So calling of virtual functions come under late binding. Main advantage of late binding is that we can write flexible code and like we learnt. But also, there is a disadvantage of slow execution of programs.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?