abhimanyuaryan
abhimanyuaryan

Reputation: 4044

can't access member even after making a member function a friend

In the code below if, I make the College class friend of University class then I am able to access the private attributes of University class. But in College class I only want the print function to access those private attributes. So, I only made print function of College class as friend but that doesn't seem to work. What's is it that I am missing or doing wrong?

Error: Can't access name private attribute of University class.

#include <iostream>

//class college; 

class University{
    //friend class college;   // Works fine
    friend void College::print(University &ob);    // doesn't work

public:
    University() = default;

    University(int i, char *n) : buildings{ i }, name{ n } {}

private:
    int buildings; 
    char *name; 
};

class College{
public:
    void print(University &ob){
        std::cout << "I am a part of " << ob.name;   // <-----------
    }
};

int main()
{
    University first{ 2000, "Mit" };

    College c; 
    c.print(first); 

    return 0; 
}

Upvotes: 2

Views: 88

Answers (1)

R Sahu
R Sahu

Reputation: 206747

In order to use

friend void College::print(University &ob);

The definition of the class College must be visible.

class University;

class College{
public:
    void print(University &ob);
};

class University{
    //friend class college;   // Works fine
    friend void College::print(University &ob);

public:
    University() = default;

    University(int i, char *n) : buildings{ i }, name{ n } {}

private:
    int buildings; 
    char *name; 
};

void Collelge::print(University &ob){
        std::cout << "I am a part of " << ob.name;   // <-----------
}

Upvotes: 5

Related Questions