| | |
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 based binary c++ c/c++ calculator char char* class classes code coding compile console conversion count database delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory multiple news number numbertoword output pointer problem program programming project python random read recursion recursive reference return rpg sorting string strings temperature template templates test text text-file tree unix url variable vector video visual visualstudio win32 windows winsock wordfrequency wxwidgets






