Search code examples
c++qtinheritanceprivate-members

QT: Private member instead of inheritance? What is the reason? Is this a specific concept?


Some time ago I programmed a GUI with QT Designer / QT Creator. For this question I will first state a schematic of how the general process of creating a GUI with the mentioned IDE works:

  1. Creating the design with the QT Designer -> Get .ui files
  2. The .ui files are translated into header files and you especially get something like "UIbasisclass.h" (with class UIbasisclass) .
  3. You create something like an "UIsubclass.h" (with class UIsubclass) yourself making one private member UIbasisclass ui.

Code within class UIsubclass:

...
        private:

       Ui::UIbasisclass ui;
...

Finally you will create an object of UIsubclass in the main method -> Code:

...
    UIsubclass *MyGUI = new UIsubclass();
...

where the constructor of UIsubclass consists among other code of:

...
    ui.setupUi(this); 
...

In short: We have a UIsubclass that is mostly responsible for applicational methods, but also has a private member of UIbasisclass named ui that consists mostly of design code. When we create an object of UIsubclass its private member UIbasisclass ui is initialized within the constructor of UIsubclass with the object of UIsubclass itself (?). [see: this pointer]

My questions are now:

  1. Why isn't there used inheritance in the way that UIsubclass inherits from UIbasisclass? Instead one object of UIbasisclass becomes member of UIsubclass.

  2. Is this some specific advantageous concept (if yes which advantages has it or how is it named?) or is it "just" a necessity of the QT code structure?

Let me know if I have to specify my questions or if there are any questions.


Solution

  • You can do with private inheritance, it is even documented in Qt documentation.

    The use of a private member for ui is the default because of the templates used by Qt Creator, Qt itself does not care.