Home > Blockchain >  Accessing an instance of a class defined in main in another class
Accessing an instance of a class defined in main in another class

Time:09-17

The problem i've been facing is related to accessing an instance of a class, I'll explain it through a series of code snipets:

If I have a class Foo defined as defined below:

class Foo {
public:
Foo(){x=5}
private:
   int x;
} 

And I create an instance of that object in main as follows:

int main(){
   Foo a;
}

I then want to access that instance of that object in another class and store it:

class Bar{
public:
   Bar() {copy = a}
private:
   Foo copy;
}

How would that be possible? Is there a way around this? Any help is appreciated!

CodePudding user response:

The most natural way would be to pass the Foo object as an argument to the Bar constructor:

Bar(Foo a)
{
    std::cout << a.x << '\n';
}

For the updated question, I might pass the object as a constant reference instead of by value:

Bar(Foo const& a)
    : copy{ a }
{
}

This will initialize the member variable copy to be a copy of the Foo object that a references.


For the Qt special case, you should almost never make copies of QObject-derived objects. Instead you should have pointers to them:

class Bar
{
public:
    Bar(Foo* a)
        : pointer{ a }
    {
    }

private:
    Foo* pointer;
};
  • Related