OA. free
Free
IBM Quantitative Aptitude Core Computer Science Medium

By using which of the following functions can we access the private members of two distinct...

IBM aptitude question, verified with a worked answer. Free to practise - no sign-up.

By using which of the following functions can we access the private members of two distinct instances of the same class in C++?

Choose one option.
Show answer & explanation
Answer: C. Both A and B

In C++, private members of a class can be accessed by both member functions and friend functions, even when operating on different instances of the same class. Member functions have implicit access to all private members of their own class instances, and friend functions are explicitly granted access to all private members of the class they befriend. Both mechanisms allow cross-instance access to private data.

Step-by-step Derivation:

  1. Member Function Access: A member function of class X can access private members of any instance of class X, including other instances passed as parameters or created within the function.

  2. Friend Function Access: A friend function declared within class X gains permission to access all private and protected members of class X for any instance of X.

  3. Example demonstrating both:

class MyClass {
private:
    int value;
    
public:
    MyClass(int v) : value(v) {}
    
    // Member function accessing private members of two instances
    bool compare(MyClass& other) {
        return this->value > other.value; // Accesses private 'value' of both instances
    }
    
    friend void printBoth(MyClass& a, MyClass& b); // Friend function
};

// Friend function accessing private members of two instances
void printBoth(MyClass& a, MyClass& b) {
    cout << a.value << " " << b.value; // Accesses private 'value' of both instances
}
  1. Both mechanisms allow access to private members across multiple distinct instances of the same class, so the answer is C (Both A and B).