Function and Method - Object oriented programming (MCQ) questions for Q. 3

Q.  Give output of the following:

#include <iostream>
            using namespace std;

class exam
            {     private:
                  int x, y, z;
               public:
               int testcase( )

             {
                x=50; y=20; z=30;
                 }
               friend int add( exam e);
             };

            int add( exam e)
             {

                   return int( e.x+ e.y+ e.z);
                    }
              int main( )
           {
  exam a;
  a.testcase( );
              cout << add(a);
              return 0;

               }

- Published on 19 Oct 15

a. 0
b. compile time error
c. 100
d. none

ANSWER: compile time error
 
This code shows usage of a friend function and how a friend function has access to private members of a class. Generally a function defined outside the class cannot access the private and protected members of the class but by declaring a function as friend function the class gives it permission to access its private and protected data.
 

    Discussion

  • Shruti Gupta   -Posted on 24 Sep 16
    Answer should be 100 not compile time error.
  • Abuturab Bohra   -Posted on 28 Aug 16
    The output of the Q.4 of Function and Method in Object oriented programming (MCQ) should be 100 but it is showing answer as compile time error

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)