GandalfDGrey
GandalfDGrey

Reputation: 321

Accessibility of a friend function

class C2;   //Forward Declaration

class C1
{
    int status;

    public:
    void set_status(int state);
    void get_status(C2 y);
};

class C2
{
    int status;

    public:
    void set_status(int state);
    friend void C1::get_status(C2 y);
};

//Function Definitions

void C1::set_status(int state)
{
    status = state;
}

void C2::set_status(int state)
{
    status = state;
}

void C1::get_status(C2 y)   //Member function of C1
{
    if (y.status | status)
    cout<<" PRINT " <<endl;
}

y.status in the second last line displays an error:

C2::status is inaccessible

The code executes properly, but there is a red line (error) under y.status.

Why is this?

Upvotes: 4

Views: 102

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490663

It sounds to me like the compiler (or part of a compiler) used by your IDE has a problem. I added enough to your code to get a complete program:

#include <iostream>
using namespace std;


class C2;   //Forward Declaration

class C1
{
    int status;

public:
    void set_status(int state);
    void get_status(C2 y);
};

class C2
{
    int status;

public:
    void set_status(int state);
    friend void C1::get_status(C2);
};

//Function Definitions

void C1::set_status(int state) {
    status = state;
}

void C2::set_status(int state) {
    status = state;
}

void C1::get_status(C2 y)   //Member function of C1
{
    if (y.status | status)
        cout << " PRINT " << endl;
}

int main() {

    C1 c;
    C2 d;
    d.set_status(1);

    c.get_status(d);
}

This compiled (without errors or warnings, at with default flags) with g++ 4.9 and VC++ 12 (aka VC++ 2013). Both produced: PRINT as output.

It's pretty common for an IDE to parse the source code separately from the actual compiler, and some of them are fairly limited compared to real compilers, so I guess it's not terribly surprising that they get confused about some things.

Upvotes: 6

Related Questions