Md_Asher
Md_Asher

Reputation: 69

C++ Accessing variables in a function in one class from a different class

I'm trying to code a program with multiple classes such the one of the class reads the variables from a text file and the other classes use these variables for further processing. The problem I'm facing is that I'm having trouble passing the variables from one class to another class, I did try "friend" class and also tried to use constructors but failed to get the desired output. The best I could do was suppose I have class 1 and class 2, and I have a variable "A=10" declared and initialised in class 1, with the help of constructor I inherit it in class 2; when I print it in class 1, it gives a correct output as 10 but when I print it in class 2 it gives an output as 293e30 (address location) Please guide me on how to this.

Class1
{
public:
    membfunc()
    {
        int A;
        A = 10;
    }
}

Class2
{
public:
    membfunc2()
    {
        int B;
        B = A + 10;
    }
    membfunc3()
    {
        int C, D;
        C = A + 10;
        D = B + C;
    }
}

If i print variables, i expect to get A = 10, B = 20, C = 20, D = 40 But what I get is A = 10, B=(252e30) + 10

Upvotes: 2

Views: 5793

Answers (1)

Sesh Sadasivam
Sesh Sadasivam

Reputation: 39

I think your problem was that you were defining local variables in your member functions, instead of creating member variables of a class object.

Here is some code based on your sample to demonstrate how member variables work:

class Class1
{
public:
    int A;

    void membfunc()
    {
        A=10;
    }

};

class Class2
{
public:
     int B;
     int C;
     int D;

     void membfunc2(Class1& class1Object)
     {
        B = class1Object.A + 10;
     }
     void membfunc3(Class1& class1Object)
     {
        C = class1Object.A + 10;
        D = B + C;
     }
};

(Full code sample here: http://ideone.com/cwZ6DM.)

You can learn more about member variables (properties and fields) here: http://www.cplusplus.com/doc/tutorial/classes/.

Upvotes: 2

Related Questions