Passing Data From One Class to Another

N

Nobody You Know

I need a member variable in class A known within an instance of class
B, even though B does not instantiate A.

My solution was to make the member variable private static, and create
a public static accessor function that returns the variable's value. I
reference this function in class B as ClassA::GetValueOfVariable().

Although this works, I wonder if there is a better way.
 
V

Victor Bazarov

Nobody You Know said:
I need a member variable in class A

"Variable in class" certainly hints at a static data member. Is
that what you're saying here? Or do you mean "any variable
declared in the class A definition", i.e. it could be non-static?
known within an instance of class
B, even though B does not instantiate A.

So,

class A {
SomeOtherType membervariable; // non-static for now
...
};

class B {
RetValType somememberfunction() { // non-static member func
???
You have to define the term "known"
and where the A comes from (see below)
???
}
};
My solution was to make the member variable private static, and create
a public static accessor function that returns the variable's value. I
reference this function in class B as ClassA::GetValueOfVariable().

Although this works, I wonder if there is a better way.

Well, whether that member is static or not is unspecified in your
statement. If it's to be static, your solution is fine. If it is
to be non-static (but per instance of A), your solution is simply
wrong, don't you think?

An instance of B can "know" an instance of A, if the A is passed to
B's member function as an argument, even if B does not instantiate
the A itself. That may change the solution, no?

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,187
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top