Page 92 - DCAP404 _Object Oriented Programming
P. 92

Unit 4: Classes and Objects




                          num1;                                                                 Notes
                          num2 = 3;
                          int sum = num1 + num2;
                          return sum;
                      }
              };
          int  main()

              {
                  Calculator obj;
                  obj.num1 = 2;
                      int  result =  obj.add();
                  cout << result;
                  return 0;
              }
          The second line in the main function is wrong because at that line, main tries to access (use as
          identifier) the private member, num1.

          4.5.3 The Protected Access Specifier

          If a member of a class is public, it can be accessed by an external function including a derived
          class. If a member of a class is private, it cannot be accessed by an external function; even a
          derived class cannot access it.
          The question is, should a derived class not really be able to access a private member of its base
          class (since the derived class and base class are related)? Well, to solve this problem you have
          another access specifier called, protected. If a member of a class is protected, it can be accessed by
          a derived class, but it cannot be accessed by an external function. It can also be accessed by
          members within the class. The following code illustrates how a derived class can access a protected
          member of a base class:
          #include  <iostream>
          using  namespace  std;
          class  Calculator
              {

                  protected:
                  int num1;
                  int num2;
              };
          class  ChildCalculator:  public  Calculator
              {
                  public:

                  int add()




                                           LOVELY PROFESSIONAL UNIVERSITY                                   85
   87   88   89   90   91   92   93   94   95   96   97