Virtual Function in C++

Virtual Function in C++

Virtual Function in C++

 

Virtual Function is one of the advances features of OOPs .Β A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class.

Polymorphism refers to the property by which objects belonging to different classes are able to
respond to the same message, but different forms. An essential requirement of polymorphism is therefore the ability to refer to objects without any regard to their classes.
When we use the same function name in both the base and derived classes, the function in the bas
class is declared as virtual using the keyword virtual preceding its normal declaration.


CODE :

#include <iostream>
using namespace std;

class Base {
   public:
    virtual void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() override {
        cout << "Derived Function" << endl;
    }
};

int main() {
    Derived derived1;

    // pointer of Base type that points to derived1
    Base* base1 = &derived1;

    // calls member function of Derived class
    base1->print();

    return 0;
}

 

OUTPUT :

Derived Function

 

Topics Covered :

  • virtual function in c++
  • virtual functions
  • virtual functions tutorial
  • function
  • object-oriented programming
  • programming

 

 


 

 


 

Thanks for reading this blog. Hope you get satisfied with the blog and definitely this blog must have valued your time and effort of reading.

Take a time to connect our other digital creations such as Instagram , Facebook and Youtube.

 

πŸ§‘β€πŸ’»πŸ§‘β€πŸ’»Β Social MediaΒ LinksΒ ofΒ Tech DCodeΒ :

πŸ‘‰πŸ»Β YouTube :Β https://www.youtube.com/channel/UCjJnEdeugftBwQ3yMuD4B_A
πŸ‘‰πŸ»Β Instagram :Β https://www.instagram.com/thetechdcode/
πŸ‘‰πŸ»Β Facebook Page :Β https://www.facebook.com/thetechdcode
πŸ‘‰πŸ»Β Twitter :Β https://twitter.com/thetechdcode
πŸ‘‰πŸ»Β Telegram Channel :Β https://t.me/thetechdcode
πŸ‘‰πŸ»Β Tech DCode Linktree :Β https://linktr.ee/thetechdcode
πŸ‘‰πŸ»Β My Personal Handles :Β https://linktr.ee/virtualshivamin

πŸ§‘β€πŸ’»πŸ§‘β€πŸ’»Β Social Media LinksΒ ofΒ SHIVAM SINGHΒ (OWNER) :

πŸ‘‰πŸ»Β Instagram :Β https://www.instagram.com/virtualshivamin/
πŸ‘‰πŸ»Β Facebook Page :Β https://www.facebook.com/virtualshivamin/
πŸ‘‰πŸ»Β Twitter :Β https://twitter.com/virtualshivamin/
πŸ‘‰πŸ»Β Personal Linktree :Β https://linktr.ee/virtualshivaminΒ 

 

Leave a Reply

Your email address will not be published. Required fields are marked *