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

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...