Sie sind auf Seite 1von 8

VIRTUAL FUNCTIONS 1.

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.

Can be invoked via either a dereference pointer or a reference


object. Actual function to be invoked is determined from the

type of object that is stored at the memory location being accessed


5. Definition of the derived function overrides the definition of the base class version 6. Determination of which virtual function to use cannot always be made at compile time.

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(); }

When i is 0, a TriangleShapes Draw() is used

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();

cout<<\n bptr points to base\n;


bptr=&d; 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; };

Das könnte Ihnen auch gefallen