Page 93 - DCAP404 _Object Oriented Programming
P. 93

Object-oriented Programming




                    Notes                      {
                                                   num1 = 2;
                                                   num2 = 3;
                                                   int sum = num1 + num2;
                                                   return sum;
                                               }
                                       };

                                   int  main()
                                       {
                                                   ChildCalculator  myChildObj;
                                                   int  result  =  myChildObj.add();
                                           cout << result;
                                           return 0;
                                       }
                                   The base class has just two properties and no method; these properties are protected. The derived
                                   class has one method and no property. Inside the derived class, the protected properties of the
                                   base class are used as identifiers. Generally, when a derived class is using a member of a base
                                   class, it is a method of the derived class that is using the member, as in this example. The above
                                   code is OK.

                                   The following code will  not compile,  because line  2 in the main() function tries  to access  a
                                   protected member of the base class:

                                   #include  <iostream>
                                   using  namespace  std;
                                   class  Calculator
                                       {
                                           protected:
                                           int num1;
                                           int num2;
                                       };
                                   class  ChildCalculator:  public  Calculator

                                       {
                                           public:
                                           int add()
                                               {
                                                   num1;
                                                   num2 = 3;
                                                   int sum = num1 + num2;







          86                                LOVELY PROFESSIONAL UNIVERSITY
   88   89   90   91   92   93   94   95   96   97   98