I am having the darnest time passing data between two classes
Okay, so I have two classes, Class A and Class B.
Class A generates a number, say 3.14. It then uses a pointer to send that along to B. I know I need to use the -> operator to send it over, but I cant figure it out. Can anyone give me a tip?
Class A
{
public:
void stuff(void)
{
pi = newfloat;
*pi = 3.14;
}
private:
float number;
float *pi;
//maybe something like pi -> B::acceptPi(*pi); ?
};
Class B
{
public:
//And then to get the data into B?
void accetpPi(float* pPi)
{
piB = pPi;
}
private:
float radius;
B* piB;
};
So basically how would I make a pointer for pi in A so I can send it to and then use it in B?
Your code contains some strange things for a C++ program, my guess is you're coming from C?
Here's an example of what your class A should look like:
1 2 3 4 5 6 7 8 9 10
class A {
public:
A() : number(newfloat) {} //use constructor to initialize number
~A() { delete number; } //use destructor to free the memory
constdouble pi = 3.14;
private:
float* number;
};
Now, as for passing that "number" into class B - don't do piB=pBi, because when an object of class A deletes, it should also free the memory it has allocated, at which point piB will be pointing to garbage.
Rather, you want to make a copy of the value of pPi and allocate a new float holding that value for class B.
Note that using raw pointers in C++ is discouraged in favour of references and smart pointers, which will save you a lot of debugging headaches down the road.
Hope that helps, please do let us know if you have any further questions.
Yeah I realize that the code is weird. To be honest I didn't really put any time in writing that snippet, just an example. I'm just trying to learn pointers now and All I can make the two classes fine, just need to figure out how to send a variable from one class to another by using a pointer.