Virtual: Dereference Pointer or A Reference Object
Virtual: Dereference Pointer or A Reference Object
We use the same function name in both the base and derived classes, the function in the base class is declared as Virtual using the keyword Virtual preceding its normal declaration. 2. When a function is made Virtual, C++ determines which function to use at the run time based on the type of object pointed to by the base pointer, rather than the type of the pointer. 3. Thus by making the base pointer to different objects, we can execute different versions of the Virtual function.
4.
VIRTUAL FUNCTIONS
For virtual functions It is the type of object to which the pointer refers that determines which function is invoked
TriangleShape T(W, P, Red, 1); RectangleShape R(W,P, Yellow, 3, 2); CircleShape C(W, P, Yellow, 4); Shape *A[3] = {&T, &R, &C}; for (int i = 0; i < 3; ++i) { A[i]->Draw(); }
class Shape : public WindowObject { public: Shape(SimpleWindow &w, const Position &p, const color c = Red); color GetColor() const; void SetColor(const color c); virtual void Draw(); // virtual function! private: color Color; };
#include <iostream.h> class base { public: void diplay() { cout<<\n Display base; } virtual void show() { cout<<\n show base; };
class derived : public base { public: void diplay() { cout<<\n Display base; } virtual void show() { cout<<\n show base; } }; Void main() { base b; derived d; base *bptr; cout<<\n bptr points to base\n; bptr=&b; bptr->display(); bptr->show();
PURE VIRTUAL FUNCTION Has no implementation A pure virtual function is specified in C++ by assigning the function the null address within its class definition A class with a pure virtual function is an abstract base class Convenient for defining interfaces Base class cannot be directly instantiated
class Shape : public WindowObject { public: Shape(SimpleWindow &w, const Position &p, const color &c = Red); color GetColor() const; void SetColor(const color &c); virtual void Draw() = 0; // pure virtual // function! private: color Color; };