Sharing pointer to object

I have an object that is created in the .ino file but shared with some other objects.

in the .ino file:

FOO *foo;  // Object to be shared
BAR *bar;  // Object that needs to use foo
bar->setFoo(foo);  // passing the pointer to foo to bar

in FOO.cpp:
void doThis() { Serial.println("Do something"); }

in BAR.cpp:
void setFoo(FOO foo) {
_foo = foo;   // make a copy of the pointer to foo
_foo->doThis(); // Invoke a method in foo

My question is simple: is this the best way to fulfill this programming need or is there a better way?

If every BAR can have only one FOO then BAR should be a child of FOO.

I like to use constructors for this sort of thing, if the relationship between a bar and its foo does not change over the bar's lifetime.

Have a look at the link in my sig, where I go through a couple of ways of associating a thing with another thing. The first couple of sections don't tell you anyting you don't already know, but I show code with aggregate objects built by reference and by composition, using C++ constructors to wire them together into a sketch.

You should post some REAL code.

foo and bar are pointers, but they are NOT initialized. You should NEVER pass an uninitialized pointer to a function.

You are passing a pointer to the setFoo() function (NOT method), which expects an object. Why?

_foo = foo;   // make a copy of the pointer to foo

It does not, since, in that function, foo is NOT a pointer. No idea what type _foo is.

_foo->doThis(); // Invoke a method in foo

From this, it appears that _foo is a pointer, but, it has NOT been properly initialized, so you can NOT use it to call a function.

And, since doThis() is a function, NOT a method, you can NOT call doThis() that way.

References solve the uninitialized pointers problem.

#include <iostream>

using namespace std;

class Foo {
    Foo(int number) : number(number) {}
    void doThis() { cout << "The number is " << number << endl; }
    const int number;

class Bar {
    Bar(Foo &foo) : foo(foo) {}
    void doFoo() { foo.doThis(); }
    Foo &foo;

int main() {
    Foo foo(42);
    Bar bar(foo);
    bar.doFoo();  // "The number is 42"