acessing multi variables declared and initialised in one class from a different class
Im 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 im facing is that im 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 a output as 293e30 (adress location)
Please guide me on how to this.
Thank you in advance
Code:
Class 1
{
public:
membfunc()
{
int A;
A=10;
}
}
Class 2
{
public:
membfunc2()
{
int B;
B=A+10;
}
membfunc3()
{
int C, D;
C=A+10;
D=B+C;
}
}
the expected output when printed should be
A=10, B=20, C=20, D=40.
but the output which im getting is
A=10, B=(262e12)+10
Re: acessing multi variables declared and initialised in one class from a different c
When posting code, please use code tags. Go Advanced, select the formatted code and click '#'.
Your code makes no sense and won't even compile. Class 2 doesn't inherit anything from Class 1 ?? In the code below, Class2 inherits from Class1 (Class2 is-a Class1) and Class3 includes a Class1 (Class3 has-a Class1). Consider
Code:
#include <iostream>
using namespace std;
class Class3;
class Class1 {
public:
Class1(int i = 10) : A(i) { }
friend Class3;
protected:
int A;
};
class Class2 : public Class1 {
public:
Class2() : Class1(5), B(A + 10) {}
void display() const
{
cout << "A: " << A << " B: " << B << endl;
}
private:
int B;
};
class Class3 {
public:
Class3(int c = 20) : c1(), C(c + 20) {}
void display() const
{
cout << "A: " << c1.A << " C: " << C << endl;
}
private:
Class1 c1;
int C;
};
int main()
{
Class2 c2;
c2.display();
Class3 c3;
c3.display();
}