| | |
virutual function
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
Virtual functions are the backbone of runtime polymorphism. You can use a member function declared as virtual to redefine the behavior of a base class. Then, when accessing a derived class through a pointer or reference to the base class, the redefined member function will be called:
This works because in do_foo, b has two types. The static type is the type of object the code says the reference refers to (base in all cases). The dynamic type is the type of object the reference actually refers to (base in call 1, derived in call 2).
The virtual mechanism is a way to access the dynamic type safely and easily.
C++ Syntax (Toggle Plain Text)
#include <iostream> class base { public: virtual void foo() const { std::cout<<"base\n"; } }; class derived: public base { public: virtual void foo() const { std::cout<<"derived\n"; } }; void do_foo ( const base& b ) { b.foo(); } int main() { do_foo ( base() ); // Call 1 do_foo ( derived() ); // Call 2 }
The virtual mechanism is a way to access the dynamic type safely and easily.
I'm here to prove you wrong.
![]() |
Other Threads in the C++ Forum
- Previous Thread: determinant 'pow'
- Next Thread: Arrays (Reading in 10 numbers)
| Thread Tools | Search this Thread |
api array arrays beginner binary bitmap c++ c/c++ calculator char char* class classes coding compile compiler console conversion convert count data database delete desktop developer directshow dll dynamiccharacterarray email encryption error file forms fstream function functions game generator getline google graph homeworkhelper iamthwee ifstream input int integer java lib linkedlist linux list loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg sorting string strings struct template templates test text tree unix url vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






