Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ friend class data access

Tags:

c++

C++ newbie here.

I am a science guy writing a cfd (ish) code. I have created a class for all solving functions, and one that handles operations on a grid. The grid class wants to be able to see a few of the variables stored in the solving class, as passing them all to the grid class seems like a bit of effort.

So in my research I came across friend classes, but can't seem to get it to work. Please see the fully cut back example below. Class A is the solver, and it creates a grid class B. Even though I have written friend class B, I still get the following compile error (g++):

In member function 'void B::testB()':

error: 'a1' was not declared in this scope

Here is the code:

#include <iostream>
using namespace std;
class B {
private:
    int b1;

public:
    void testB(){
        cout<<a1<<endl;
    };  


};

class A {
friend class B;

private:
    int a1;

public:
    void testA(){
        a1=2;
        B b;
        b.testB();
        };
};


int main(){
    A a;
    a.testA();
}
like image 448
CptLightning Avatar asked Dec 22 '22 16:12

CptLightning


1 Answers

a1 only exists as a part of instances of class A. In other words, you need an A object in order to access a1.

EDIT: but it turns out that wasn't the only problem in the source you gave.

This works:

#include <iostream>
using namespace std;

class B;

class A {
  friend class B;
  private:
    int a1;
  public:
    void testA();
};

class B {
private:
    int b1;

public:
    void testB(A *a){
        cout << (a->a1) << endl;
    }
};

void A::testA() {
    this->a1 = 2;
    B b;
    b.testB(this);
}


int main(){
    A a;
    a.testA();
}
like image 139
CromTheDestroyer Avatar answered Jan 02 '23 01:01

CromTheDestroyer