Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

8.7 Polymorphism & virtual function

1 min read

Polymorphism
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Example: function overloading, virtual functions. Another example can be a plus + sign, used for adding two integers or for using it to concatenate two strings.

Virtual Function:
A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding.

class Shape {
protected:
int width, height;

public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}

// pure virtual function
virtual int area() = 0;
};

Important Points to Remember
1. Only the Base class Method's declaration needs the Virtual Keyword, not the definition.
2. If a function is declared as virtual in the base class, it will be virtual in all its derived classes.
3. The address of the virtual Function is placed in the VTABLE and the copiler uses VPTR(vpointer) to point to the Virtual Function.

                      8.8 Data Abstraction          NEXT >>

You may like these posts

  • A function is a group of statements that together perform a task. All C programs made up of one or more functions. There must be one and only one main function. You can divide up…
  •   Calling a function generally causes a certain overhead (stacking arguments, jumps, etc...), and thus for very short functions, it may be more efficient to simply inser…
  •   Constructor A constructor is a special kind of class member function that is executed when an object of that class is instantiated. Constructors are typically used to init…
  •   Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C++, this takes the form of a function that calls its…
  •   Function Declaration A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately…
  • Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. An object is an instanti…

Post a Comment