GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — Virtual Function in C++
Selected Reading
Virtual Function in C++A virtual function in C++ is a member function in a base class, which is further overridden in derived classes. This helps in enabling runtime polymorphism, which means the function to be executed is determined at runtime, not compile-time as the function that gets called depends on the actual object type, not the pointer or reference type. Virtual Function DeclarationA virtual function is declared in the base class using the virtual keyword. SyntaxBelow is the syntax of virtual function declaration: class BaseClassName {
public:
virtual void func_name() {
// implementation
}
};
Where,
How Virtual Functions WorkIn C++, Virtual Functions allow runtime polymorphism, which means the function, that gets called depends on the actual object type, not the pointer or reference type, and this is done by using a mechanism called the vtable (virtual table) and vptr (virtual table pointer). Virtual Table (VTable) and Virtual Pointer (VPTR)Virtual Table is a table of function pointers, which is created for each class that has virtual functions, it stores addresses of virtual functions of the class. Step-by-Step Working
Example#include<iostream>
using namespace std;
class shape {
public: virtual void draw() { // Virtual function
cout << "Creating a shape!" << endl;
}
};
class circle: public shape {
public: void draw() { // Overriding virtual function
cout << "Creating a Circle!" << endl;
}
};
class square: public shape {
public: void draw() { // Overriding virtual function
cout << "Creating a Square!" << endl;
}
};
int main() {
shape * shapePtr; // Base class pointer
circle c;
square s;
shapePtr = & c; // Pointing to circle object
shapePtr -> draw(); // Calls circle's draw() method
shapePtr = & s; // Pointing to square object
shapePtr -> draw(); // Calls square's draw() method
return 0;
}
OutputCreating a Circle! Explanation
Rules for Virtual Functions
Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |