Pages

Friday, May 16, 2025

Friend functions & class in OOPs

 #include <iostream>

using namespace std;

class A {
    string secret = "secret data";
    friend class B;
    friend void revealSecret(A &obj);
};

class B {  // becomes a friend class of A
public:
    void showSecret(A &obj) {
        cout << obj.secret << endl;
    }
};

void revealSecret(A &obj) {
    cout << obj.secret << endl;

}

int main() {
    A a1;
    B b1;

    // b1.showSecret(a1);
    revealSecret(a1);

    return 0;
}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...