Qt6 topics merged with General

Access variables between multiple classes/objects

  • I have 3-4 classes that need to all share some variables between each other. I wasn't sure which approach to take but I have thought of a couple of ideas. Is there a way to connect all 3 classes to one so that they can all access their protected/private variables? or would it be best to create a class that has the purpose of storing these variables? If so, how would I then pass the instance of that object between multiple classes?

  • @AaronKelsey

    Sounds like a typical example for inheritance https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm

  • @koahnig It isn't inheritance, the classes do not have a "is-a" relationship. They're pages which share user entered information. I should have been more specific in my original post.

  • Moderators

    techenically it can be done with inheritance, but that would also requiere singletons and stuff, urgh let's not go there.

    The cleanest way I can see for this special case, is make a class/struct that holds all the data you want to "share" make the variables accessable via getters and setters, if your class is derived from QObject, you could emit a "changed"signal to update the other classes.

    Than in the top most parent class create that class + all of the other 4 and pass a reference around and store the pointer in a member variable

Log in to reply