Thread: use reference as class member

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    8

    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.
    Code:
     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

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Works for me:
    Code:
    class 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);
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 51
    Last Post: 02-09-2009, 05:35 PM
  2. Replies: 6
    Last Post: 07-29-2008, 04:37 AM
  3. Class member variables only readable by member functions?
    By _Elixia_ in forum C++ Programming
    Replies: 4
    Last Post: 10-10-2003, 03:52 PM
  4. Reference another class's data member...
    By RoD in forum C++ Programming
    Replies: 4
    Last Post: 02-15-2003, 11:20 AM
  5. passing a class member function by reference?
    By m712 in forum C++ Programming
    Replies: 4
    Last Post: 12-08-2002, 05:01 AM

Tags for this Thread