Can we access updated public variable of one class in another class without inheritance. Just like below.
This class A which have public int variable x. In updateValue function i have updated x value.

class A
{
    public:

        int x;

        A()
        {
            x=0;
        }

        void updateValue()
        {
            for(int i=1; i<=5; i++)
            {
                x++;
            }
        }
};

Now I want to access this updated x value in another class without using inheritance.



class B
{

    public:

        void getVal()
        {
            cout<<"Valuse of x is : "<<x <<endl;
        }

};

Anyone please help ! I need this functionality to use in my project but I can't use inheritace becuase class A and class B are already two separate child classes.

class B
{
    public:
    void getVal(A someObjectOfTypeA)
    {
        cout<<"Value of x in the type A object you just passed to me is : "<< someObjectOfTypeA.x <<endl;
    }
};

Alternatively, make the B object permanently aware of an A object.

class B
    {
        A* aPointerToAnObjectOfTypeA;

        // constructor
        B(A* pointerToSomeObjectOfTypeA)
        {
          aPointerToAnObjectOfTypeA = pointerToSomeObjectOfTypeA;
        }

        public:
        void getVal()
        {
            cout<<"Value of x in the type A object I know about is : "<< aPointerToAnObjectOfTypeA->x <<endl;
        }
    };

I feel that someone should point out that having public member variables is generally very poor practice. The coding standards at my work require all member variables to be private.

Thanks for help. I works fine in the above situation but when i use this approach my project I get following error. Any idea !

e:\software\code blocks\codeblocks\mingw\bin..\lib\gcc\mingw32\4.4.1\include\c++\bits\ios_base.h|790|error: 'std::ios_base::ios_base(const std::ios_base&)' is private|

The compiler error message either before of after that should give the line of you code that has produced this error. When posting compiler output post the complete output with the relevent lines of your source code.

And perhaps making the constructor from Moschops 2nd example public, or adding a static method which returns an object of type B. It's not that important for the situation at hand, but we should be careful with those things.

Also, as Banfa pointed out, see the line number from your error message. It will lead you to your problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.