Page 218 - DCAP404 _Object Oriented Programming
P. 218

Unit 10: Virtual Functions and Polymorphism




          virtual  return_type  function_name3(  arguments);                                    Notes
          ———————
          ———————
          };
          To make a member function virtual, the keyword virtual is used in the methods while it  is
          declared in the class definition but not in the member function definition. The keyword virtual
          precedes the return type of the function name. The compiler gets information from the keyword
          virtual that it is a virtual function and not a conventional function declaration.

                 Example: The following declaration of the virtual function is valid.

          class  point  {
          intx;
          inty;
          public:
          virtual  int  length  (  );
          virtual  void  display  (  );

          };
          Remember that the keyword virtual should not be repeated in the definition if the definition
          occurs outside the class declaration. The use of a function specifier virtual in the function definition
          is invalid.

                 Example:

          class  point  {
          intx;
          inty;
          public:
          virtual  void  display  ();
          };

          virtual  void  point:  :  display  ()  //error
          {
          Function  Body
          }
          A virtual function cannot be a static member since a virtual member is always a member of a
          particular object in a class rather than a member of the class as a whole.

          class  point  {
          int  x;
          int  y;
          public:
          virtual  static  int  length  ();  //error




                                           LOVELY PROFESSIONAL UNIVERSITY                                   211
   213   214   215   216   217   218   219   220   221   222   223