-2

Is it necessary to initialize member variables with nullptr or Q_NULLPTR in header files? If yes, why is it so required, when I do proper initialize it the ctor initialization list.

in MyDialog.h,

QDialog* m_Dialog = Q_NULLPTR;

and in MyDialog.cpp...I do

MDialog()::MDialog()
  : QDialog()
  , m_Dialog(new QDialog())
  { 
  }

And in destructor, I do proper delete n setting it to nullptr.

Why is the below required?

QDialog* m_Dialog = Q_NULLPTR;
Sayan Bera
  • 135
  • 2
  • 16
  • Why people are downvoting? I don't have clear knowledge on this so asked? – Sayan Bera Apr 12 '18 at 05:40
  • `Why is the below required?` ... I'm curious as to why you might think it is? Was there an error or warning message that you saw somewhere? – Steve Apr 12 '18 at 06:04
  • No error or warning, It's just I came across this kind of code for the first time, so wanted to have a better understanding for this. – Sayan Bera Apr 12 '18 at 06:17

1 Answers1

0

It is not required that you use

QDialog* m_Dialog = Q_NULLPTR;

to initialize the member variable.

The above syntactic form is useful when there are many constructors in which you'll want to initialize the member variable with the same value. It reduces duplicate code.

If your class has the only constructor that you posted, you could leave the member variable declaration as

QDialog* m_Dialog;

without adversely affecting your program.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • @R Sahu, and why this kind of code is used `QDialog* m_Dialog= nullptr;` `m_Dialog= new QDialog(this, Qt::FramelessWindowHint);` why 2 lines are requried, is this any c++ 11 standards? – Sayan Bera Apr 12 '18 at 06:11
  • @SayanBera, first of all, the language allows it. That's not always a good reason to use it. In this particular case, It's possible that (a) it's a coding style that company insists on, or (b) the developer who wrote the class prefers that coding style, or (c) some other reason that we don't know about. – R Sahu Apr 12 '18 at 06:17
  • Yeah...I guess it the option (b), but maybe this is unnecessary ie, twice initialization. – Sayan Bera Apr 12 '18 at 06:19