Passing Data Between Classes Using Pointers

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?

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
Class A
{
public:
void stuff(void)
  {
     pi = new float;
     *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?
Last edited on
closed account (o3hC5Di1)
Hi there,

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(new float) {} //use constructor to initialize number
        ~A() { delete number; } //use destructor to free the memory

        const double 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.

All the best,
NwN
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.
Topic archived. No new replies allowed.