use reference as class member

Dear friends:
I am confused about the problem of "using reference as class member". For example, i have two classes.

class A
{
public:
A(Mesh& FM):FVmesh(FM){}
private:
Mesh& FVmesh;
}

class B
{
B(A& FAA):AA(FAA){}

private:
A& AA;
}
The class B use the reference of A as a class member, it will not compiled sucessfully. Since class A must have a "Mesh& FM" to initilize it class member.
one solution is to use pointer as the class member of class B. But how to resolve this problem with referenes.
Regards
Last edited on
What compilation error are you getting?

The main problem of using references as members that I can think of is that it will prohibit copy assigment because references can't be reassigned.
the errors I see are missing semicolons and B's constructor is private. Fixing that, it compiles and objects of type B can be created: https://wandbox.org/permlink/TEjReCpzs8H229Vd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
typedef int Mesh;

class A
{
  public:
    A(Mesh & FM):FVmesh(FM) { }
  private:
      Mesh & FVmesh;
};

class B
{
  public:
    B(A & FAA):AA(FAA) { }

  private:
      A & AA;
};

int
main()
{
    Mesh m;
    A a(m);
    B b(a);
}

Last edited on
Topic archived. No new replies allowed.