Page 229 - DCAP404 _Object Oriented Programming
P. 229

Object-oriented Programming




                    Notes          An additional feature of C++ abstract class is that it allows pure virtual methods in an abstract
                                   class to contain an implementation in their declaring class. This mechanism providing fallback
                                   or default behavior that a derived class can fall upon if needed.
                                   The following code snippet defines an abstract class:


                                   class  Abst

                                   {
                                   public:
                                                 virtual  void  AbstFunc()  =  0;
                                   };
                                   Function Abst::AbstFunc is a pure virtual function. Note that a function declaration cannot have
                                   both a pure specifier and a definition. Due to this reason the following code is incorrect. The
                                   compiler will issue an error message for this.
                                   Class  Abst
                                   {

                                          virtual  void  AbstFunc()  {  }  =  0;  //Incorrect!  {}  and  =0  cannot  be
                                   used  together
                                   };
                                   There are other restrictions also. You cannot use an abstract class as a parameter type, a function
                                   return type, or the type of an explicit conversion, nor can you declare an object of an abstract
                                   class. You can, however, declare pointers and references to an abstract class.
                                   Care should be taken when cyclic inheritance is employed as shown in Figure 10.1.

                                                           Figure  10.1:  Ambiguous  Inheritance























                                   In this case a compiler error takes place. The member function Func() of class D attempts to
                                   access member data x of class A. The error results because the derived classes B and C derived
                                   from base class A create copies of A called. Each of the copies have A member data and member
                                   functions and each has one copy of member data x. When the member function of the class D
                                   tries to access member data x, confusion arises as to which of the two copies it must access since
                                   it has been derived from both derived classes.





          222                               LOVELY PROFESSIONAL UNIVERSITY
   224   225   226   227   228   229   230   231   232   233   234