C++ - Initializing Variables in Header VS With Constructor

C++ Initialize const class member variable in header file or in constructor?

They both are not exacly the same, with the constructor initialisation one disadvantage is that you need to maintain the order of initialisation
Also if you use .cpp and .h, you may need to always switch to cpp to find the initialised values.

This is already answered in this question C++11 member initializer list vs in-class initializer?

Is it good practice to initialize a member variable of a class in the header file?

Initializing a member in the class body is completely equivalent to doing it in the member initializer list in the construcor. (But if you provide initializers in both places, member-init-list overrides initializers in class body.)

Initializing in the class body whenever possible is a good practice, because it's less error prone (you'll immediately notice if you forget to initialize a newly added member; see DRY).

Constructor initializer list vs initializing in the header file

This:

MyClass::MyClass()
{
variable1 = 10;
boolean2 = false;
};

is not initialization! The members will be initialized before the body of the constructor runs and then you are assigning values. What you mean is probably the difference between

Initializer list

MyClass::MyClass() : variable1(10), boolean2(false) {}

and in class initialization (available since C++11 I believe) in the header:

struct MyClass {
int variable1 = 10;
boolean2 = false;
};

In both the last cases, the values are used to initialize the members, so there is no difference in speed. However, in the first case you are doing more than you actually want to (initialization + assignment) and you should avoid it if possible.

The subtle difference between in-class initialization and initializer list (see eg here) is that

variable1 = 10; 

may involve a copy. This can be circumvented by using direct-list-initialization:

 struct MyClass {
int variable1{10};
bool boolean2{false};
};

However, for an int and a bool this wont make any difference whatsoever.

Initializing variables in header C++

Aside from the obvious incorrect naming (which I assume was simply a matter of hastily creating an analogous example and is not the actual issue in your code), you need to declare the variable as extern in your .h/.hpp file. You cannot have an extern variable that is also static since the (one of the) use(s) of static is to keep the variable contained to within a single .cpp file.

If you change:

static int testNumber = 10;

in your A.h file to:

extern int testNumber;

and then in your A.cpp file do something like:

#include "A.h"
int testNumber = 10;

Now go ahead and run:

int main() {
//changeNumber();
std::cout << testNumber << std::endl; // prints 10
changeTestNumber(); // changes to 15
std::cout << testNumber << std::endl; // prints 15
std::cin.ignore();
return 0;
}

Be sure to fix the function names!

Initialize member-variables in header-file

The compiler suggests one solution: add -std=c++11 flag to the compiler to enable this C++11 feature. This would add a lot of other features that make C++ programming a lot more enjoyable.

If switching to C++11 is not an option for you, use initializer list in the constructor:

MyClass() : FILENAME("prices.txt"), temp(new double[SIZE]) {}

Note: Since you create a temp in the dynamic memory area, you need to add a destructor, a copy constructor, and an assignment operator. You would be better off using a dynamic container, e.g. std::vector for your data, because it simplifies your memory management code.

C++ 11 standards - initialize member variables in header

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.

C++ 11 - If I initialize a variable in a class header file, is a default constructor generated?

Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler generate a new default constructor?

No. cppreference gives you some hint:

3 Implicitly-declared default constructor

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

If some user-declared constructors are present, the user may still force the automatic generation of a default constructor by the compiler that would be implicitly-declared otherwise with the keyword default. (since C++11)

There is no reasoning about how the members look like, only if other constructors are present. And in your case the other constructor is still present.

Question: If the header file is changed so that the variable myInteger is set to a value, does the compiler modify the behavior of the constructor defined above to be like the following?

Yes. See also cppreference


  1. Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

Default member initializers are quite valuable. You write the initial value once and it is applied automatically in every constructor (that does not provide its own member initializer). It would even be applied in an implicitly declared/defined default constructor (which you don't have in your example).



Related Topics



Leave a reply



Submit