Use variable between classes

Hi,
I'm new to c++ and i was wondering if there is a way to use a variable from one class in another by sending it's value to the other class?

for example variable a is in class A and I want to use variable a in class B.

How can this be done?




Last edited on
Hi piper355,

if you just want to use the value of the data member of class A to initialise another data member in class B, then you can simply pass that variable to class B's constructor. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class A
{
public:
   A(double value) : variable(value) {}
   
   double accessorFunction() const {return variable;}

private:
   double variable;
};

class B
{
public:
   B(double x) : anotherVariable(x) {}

private:
   double anotherVariable;
};


int main()
{
       A Object(3.0); //A::variable is now 3.0

       B AnotherObject(Object.accessorFunction()); //now B::anotherVaiable = 3.0

       return 0;
}


Hope this helps!
When I try this it just gives me a bunch of errors in class A that weren't there before.
code/errors plz
those two classes look perfect, did you just directly copy and paste them?
Last edited on
@piper355
When I try this it just gives me a bunch of errors in class A that weren't there before.

What exactly are the errors your getting?

@firedraco
code/errors plz

Yes, the code would help too piper355
Topic archived. No new replies allowed.