I'm having a problem accessing information between classes. The following simple program illustrates the problem. I have two classes. Int Cell and second. IntCell has a single data member: storedValue. I initialize the value of storedValue to 0, and then assign a value of 16 to it in main() on line 41.

My problem is that I don't know how to access the correct data from a member function of class second. I attempt to access it through an instance of an IntCell object k (line 34) in the member function show() which belongs to class second, but I don't get the value of 16 when I call show() on line 44. Where am I going wrong here? Thanks.

#include <iostream>
    using namespace std;

    class IntCell
    {
          public:
            IntCell() : storedValue( 0 ) {}
            int read() const;
            void write( int x );


          private:
            int storedValue;
    };

    class second
    {
          public:
            void show();
    };

    int IntCell::read() const
    {
        return storedValue;
    }

    void IntCell::write( int x )
    {
         storedValue = x;
    }

    void second::show()
    {
         IntCell k;
         cout << "Here is the incorrect value of stored value: " << k.read() << endl;
    }

    int main()
    {
        IntCell t;
        t.write( 16 );
        cout << "Here is the value for t.read(): " << t.read() << endl;
        second s;
        s.show();
        return 0;
    }

Edited 2 Years Ago by smitsky

storedValue on line 13 is an object of each instance of the class. Each instance of intCell has it's own copy of storedValue. The objects on lines 34 and 40 are two different instances of the class, so they will not have the same copy of storedValue. If that is what you want (all instances have the same copy of storedValue) then you need to make storedValue a static member of the class.

class IntCell
    {
          public:
            IntCell() {} // <<<<<<<<<<<<<<<<<<<<<
            int read() const;
            void write( int x );
          private:
           static int storedValue; // <<<<<<<<<
    };

That will make storedValue just like any other global variable, so you will need to declare it as a global. Notice that you have to remove the initialization from the constructor so that the constructor doesn't destroy the current value when a new instance of the class is instatiated.

Somewhere near the beginning of the *.cpp file put this line:

int IntCell::storedValue = 0;

Edited 2 Years Ago by Ancient Dragon

Comments
Excellent advice as always!
This question has already been answered. Start a new discussion instead.