Major Rules for defining virtual functions in C++?
Here we understand about Rules for defining Virtual functions in C++ in detail.
Major Rules for defining Virtual functions in C++?
Before we know about the rules for defining Virtual functions, we understand about what is a pure virtual function in C++.
Pure Virtual function:
A pure virtual function is a virtual function with no body.
Syntax: virtual void show()=0.
Major Rules for defining virtual functions:
- The virtual functions must be members of some class.
- They can not be static members.
- They are accessed by using object pointer.
- A virtual function can be a friend of another class.
- A virtual function in base class must be defined even though it may not be used.
- The prototypes of the base class version of a virtual function and all the derived class versions must be identical. If the two function with the same name have different prototypes, C++ considers them as overloaded functions and virtual function mechanism is ignored.
- We can not have virtual constructors but we can have virtual destructors.
- While a base pointer can point to any type of derived object, the reverse is not true. That is to say, we can not use pointer to a derived class to access an object of base type.
- When a base pointer points to a derived class, incrementing or decrementing it will not make it to point the next object of the derived class. It is incremented or decremented only relative to its base type. Therefore, we should not use this method to move the pointer to the next object.
- If a virtual function is defined in the base class, it need not be necessarily redefined in the derived class. In such cases, calls will invoke the base function.
Major rules for defining virtual functions
Access by using object pointer
A pure virtual function is a virtual function with no body
Major rules for defining virtual functions in C++ language.
Tech writer at NewsandStory
Total 605 views