PDA

View Full Version : Question about constructors and inheritance



Blackened Justice
25th February 2012, 00:34
Hey everyone,

I have a (rather simple) question about C++ and constructors/inheritance. Usually, when reading Qt tutorials, I see something like this for the definition of the class's constructor:

class MyWidget: public QWidget {
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
}

MyWidget::MyWidget(QWidget *parent = 0): QWidget(parent) {
// Code here
}


Is it any different from doing it like this:

class MyWidget: public QWidget {
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
}

MyWidget::MyWidget(QWidget *parent = 0) {
QWidget(parent)
// Code here
}


My guess is that QWidget(parent) is a call to the superclass's constructor, leaving the MyWidget constructor to initialize only what else it adds on to it. And maybe that's why it's put outside the body of the function. Put aren't they in practice the same?


Cheers

ChrisW67
25th February 2012, 07:03
The first example the constructor is using the initialisation list to control the construction of its inherited QWidget component. This is the only way to control the construction of the underlying inherited class(-es).

The second example is not doing what you think. MyWidget starts off with a default constructed QWidget at the point it enters the constructor body. Your code as written is treated as a declaration of another QWidget called parent by my compiler and generates a warning because the name clashes with the parameter. (Your compiler might make something else of it.) I suspect you intended to call the QWidget constructor directly, i.e. QWidget::QWidget(parent) : you cannot do this and it will generate an error. It would make little sense anyway, since the underlying QWidget is already present and constructed.

You can initialise member variables in either the initialisation list or by assignment in the constructor body. Have a read Should my constructors use "initialization lists" or "assignment"? (http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6)