CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2008
    Posts
    3

    Acessing memeber of a class from another class

    Hi ,

    I am a beginner in C++.

    I want to know how can we access data member of a class from another class. I am facing problem in visualizing the things in writing separate .h and .cpp file.

    Here I explain the things.We have three classes.

    In a.cpp (assuming the a.h files is wriiten )
    #include "a.h"
    A::A()
    {
    int ii=1;
    }
    void A:: fun_a()
    {
    cout<<"Value in A:"<<ii<<endl;
    }
    ============================
    In b.h
    #include "a.h"
    Class B
    {
    int jj;
    A b_aa;
    public:
    void fun_b();
    void change_ii();
    };

    In b.cpp
    #include "b.h"
    B::B()
    {
    jj=2;
    }

    void B::fun_b()
    {
    cout<<"value in A:" << ii <<"value in B:" <<jj;
    }
    void B::change_ii()
    {
    ii=5;
    }

    // suppose both the functions are called and the value of ii is 5 and jj is 2
    //Now I want to access the data ii from and jj from the C class.
    //I want to assign kk a member of C class or a simple variable the value of ii (i.e. 5).

    How to go about it ?

    If declare a member of type B in our C class..it will carete another instance of B but does not contains the data in the live B object.

    Is passing a reference to the B class in the contructor of C class is asolution? If so, whow to do that. I am getting confused in implementin this concept.

    And what other ways are there?

    Thanks and regards,
    Alex



    Back to Top

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Acessing memeber of a class from another class

    This has already been (partially) answered elsewhere.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Acessing memeber of a class from another class

    Several possible approaches:

    1) Make the two classes friends.
    2) Add get/set functions to the A class.
    3) Make B inherit from A, and change ii to protected rather than private.
    4) Figure out why your current design isn't as object-oriented as it should be, and fix it.

    Which of these solutions best suits your needs, I can't guess from the information given.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured