C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ virtual function
Late binding or Dynamic linkageIn late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call. Rules of Virtual Function
#include <iostream> using namespace std; class A { int x=5; public: void display() { std::cout << "Value of x is : " << x<<std::endl; } }; class B: public A { int y = 10; public: void display() { std::cout << "Value of y is : " <<y<< std::endl; } }; int main() { A *a; B b; a = &b; a->display(); return 0; } Output: Value of x is : 5 In the above example, * a is the base class pointer. The pointer can only access the base class members but not the members of the derived class. Although C++ permits the base pointer to point to any object derived from the base class, it cannot directly access the members of the derived class. Therefore, there is a need for virtual function which allows the base pointer to access the members of the derived class. C++ virtual function ExampleLet's see the simple example of C++ virtual function used to invoked the derived class in a program. #include <iostream> { public: virtual void display() { cout << "Base class is invoked"<<endl; } }; class B:public A { public: void display() { cout << "Derived Class is invoked"<<endl; } }; int main() { A* a; //pointer of base class B b; //object of derived class a = &b; a->display(); //Late Binding occurs } Output: Derived Class is invoked Pure Virtual Function
Pure virtual function can be defined as: virtual void display() = 0; Let's see a simple example: #include <iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived : public Base { public: void show() { std::cout << "Derived class is derived from the base class." << std::endl; } }; int main() { Base *bptr; //Base b; Derived d; bptr = &d; bptr->show(); return 0; } Output: Derived class is derived from the base class. In the above example, the base class contains the pure virtual function. Therefore, the base class is an abstract base class. We cannot create the object of the base class.
Next TopicC++ Interfaces
|