I need reliable information about "this" subject:
class MyClass, public QWidget
{
public:
MyClass( QWidget * parent = NULL )
:QWidget( parent ),
mpAnotherWidget( new QWidget( this ) ){};
private:
QWidget * mpAnotherWidget;
};
Of course, calling virtual functions in contructor OR initialization list is a bad idea. The Question is: can this code
mpAnotherWidget( new QWidget( this ) )
lead to undefined behavior?! And if so: why ?
Please quote your sources if you can! Thanks!
Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.
Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.
When do we use Initializer List in C++? Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .
It depends on what QWidget
does with the pointer it is given. It is perfectly fine to pass around a reference or pointer to a half-constructed object as long as the called code does not access the underlying object. You need to look into the documentation of QWidget
to know whether it touches the object or just stores the pointer.
In the particular case of Qt, reading the documentation, it is calling the constructor of QWidget
, the argument is of type QWidget*
, and this
is only used to cast to the base pointer. Obtaining the pointer to the base is guaranteed in 12.7/3 as the requirement for the conversion is that the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B shall have started. The pointer is then passed to the QWidget
constructor that may use it in any way it wants, since the constructor for the base QWidget
has already completed before the constructor for the mpAnotherWidget
starts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With