Home > Enterprise >  How to make a class public only to another class
How to make a class public only to another class

Time:12-31

I have two separate distinct classes in C , Node and Graph. I want to make the contents of Node accessible via the methods in graph but not public, how do I do this?

CodePudding user response:

You can use a friend declaration to specify classes or functions that you'd like to give full access to the private and protected members.

Example:

class Node {
    // ...
private:
    friend class Graph;
    int x;
};

class Graph {
public:
    void foo(Node& n) {
        n.x = 1; // wouldn't work without `friend` above
    }
};

int main() {
    Graph g;
    Node n;
    g.foo(n);
}
  • Related