Saturday, October 13, 2012

Virtual Functions

All the signal processing blocks are derived from the base class gr_block

There is a method in this class called general_work() which does all the signal processing task. The functions in general_work() are implemented as pure virtual and one has to override them when they want to write their own signal processing blocks.

Lets know what are virtual functions : 

A virtual function is a member function that is declared within a base class and redefined by a derived class.

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.

The derived class can either fully replace ("override") the base class member function, or the derived class can partially replace ("augment") the base class member function.

Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support runtime polymorphism.

 Here is a good example :

#include
using namespace std;


class A
{
        int a;
        public:
        A()
        {
                 a = 15;
        }
        virtual void show()
        {
                    cout << a;
        }
};

class B: public A
{
         int b;
         public:
         B()
         {
                 b = 2;
         }
         virtual void show()
         {
                  cout << b;
         }
};

int main()
{
           A  *pA; // pointer to the base class A
           A    oA; // object of class A
           B    oB; // object of derived class B
           pA  = &oB; // pointer took the address of the object of derived class B
           pA->show(); use show from the derived class
           pA = &oA; // pointer took the address of the object of base class A
           pA->show(); // use show of base class
           return 0;
}


 So the output is 213 as expected

No comments:

Post a Comment