Wednesday, August 27, 2014

C++ Abstract and Interface fundamentals

Virtual Function A function preceded by virtual keyword. Intention is that this function would be overloaded in some derived classes. All virtual functions need not be overridden in some derived classes. They can remain in base class as it is.
            virtual void VirtualFunction();
            
Pure Virtual Function A virtual function with no implementation which is set equal to zero.
            virtual void PureVirtualFunction() = 0;
            
This can have an implementation in base class. You cannot instantiate a class having a pure virtual function. If you create a pointer of base class pointing to the derived class, it would call the function of the derived class. So, how do you use it?
            DerivedClass myDerivedClass;
            BaseClass* myBaseClass;
            myBaseClass = &myDerivedClass;      // In one line BaseClass* myBaseClass = &myDerivedClass;
            myBaseClass->PureVirtualFunction(); // This would call implementation of the pure virtual
                                                // function in derived class
            
You have to BOTH override AND implement a Pure Virtual Function in the class that derived from the class that had the pure virtual function. If no class derived from it, then it's not required.
Abstract Function Synonym for Pure Virtual Function. A function that is pure virtual.
            void AbstractFunction() = 0;
            
Abstract Class Class that has at least one Pure Virtual Function
Interface Class Class that has all functions Pure Virtual. And it has no member variables. This is not a rule per se. Intention is that the interface class will not have any implementation of its own. All required concrete class that derive from it must implement/override the functions in the interface. Note that there is a great temptation to add concrete member functions and data to iterface classes. This must be resisted, in general it is a sign that the interface is not well factored. Data and concrete member functions tend to imply a particular implementation and as such can inherit from the interface but should not be in that interface. A general test is the "is a" vs "has a", as in a Square is a Rectangle, but a Square has a set of sides. In other words, "is a" would use Abstract class and "has a" would use Interface.

Note: The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined. Note that a destructor must be defined even if it is declared pure-virtual. Ref: http://gcc.gnu.org/faq.html#vtables

Synonyms:
Base Class/Super Class/Parent Class
Derived Class/Inherited Class/Sub Class
Abstract Function/Pure Virtual Function
Instantiate/Create
Concrete/Independent
Abstraction
Indirection

No comments:

Post a Comment