C++11 Initialization of template class member in template class - templates

I have a bunch of template classes, based on an enumeration type. Here is the source code:
#include <iostream>
// An enum type
enum class ENUMR : unsigned char {
SYSTEM1,
SYSTEM2,
UNKNOWN
};
// template class; will later be specialized based on ENUMR enumerators
template<ENUMR S>
class System
{};
// specialized System class, for enumerator SYSTEM1
template<>
class System<ENUMR::SYSTEM1>
{
private:
static constexpr char identifier { 'G' };
};
// An observation class recorded from a certain System instance
template<ENUMR Sys,short int Freq>
class Obs {
public:
Obs():
m_system {System<Sys> {} }, // does not work
m_frequency {Freq}
{};
//{
// m_system = System<Sys> {}; // works
//}
private:
System<Sys> m_system;
short int m_frequency;
};
// dummy code to test the template classes
int main ()
{
System<ENUMR::SYSTEM1> s1;
System<ENUMR::UNKNOWN> s2;
System<ENUMR::SYSTEM1> s3 (System<ENUMR::SYSTEM1>);
Obs<ENUMR::SYSTEM1, 1> obs;
std::cout <<"\n";
return 0;
}
Initialization of the member (template) variable Obs::m_system produces a compile-time error, when performed as m_system {System<Sys> {} }. However, when the same variable is initialized as m_system = System<Sys> {}; the source codes gets compiled (the respective lines in the source code above are commented).
Does that mean that the assignment operator works, but the copy constructor fails? If so, why?
When compiled against the gcc version 4.8.3 i get the following error message:
test.cpp: In instantiation of ‘Obs<Sys, Freq>::Obs() [with ENUMR Sys = (ENUMR)0u; short int Freq = 1]’:
test.cpp:43:28: required from here
test.cpp:25:22: error: too many initializers for ‘System<(ENUMR)0u>’
m_frequency {Freq} {};

If you change
m_system{ System<Sys>{} },
m_frequency{ Freq }
to
m_system( System<Sys>{} ),
m_frequency( Freq )
it will compile. Note however, that the first initializer creates a default constructed temporary, and then uses the copy constructor to initialize the member. Since you want m_system to be default constructed, that initializer can be omitted.

System<ENUMR::SYSTEM1> is an aggregate, so the mem-initializer m_system { System<Sys>{} } performs aggregate-initialization. Since System<ENUMR::SYSTEM1> has no corresponding member - indeed it has no members at all - for the corresponding initializer System<Sys>{}, you get the error indicating there are too many initializers.
If System<ENUMR::SYSTEM1> were not an aggregate, the effect of that mem-initializer would be to direct-list-initialize m_system from a value-initialized temporary of the same type. Since the move/copy constructors are defaulted, you could achieve the equivalent effect for both the aggregate and non-aggregate case by directly value-initializing m_system with an empty brace initializer: m_system {}. (DEMO)

Related

cppcheck: member variable not initialized in the constructor

The following code, as far as I can tell, correctly initializes the variables of the derived class B:
#include <utility>
struct A {
int i;
};
struct B : A {
int j;
explicit B(A&& a) : A(std::move(a)), j{i} { }
};
int main()
{
A a{3};
B b(std::move(a));
return 0;
}
Running cppcheck with --enable=all gives the warning:
[test.cpp:9]: (warning) Member variable 'A::i' is not initialized in
the constructor. Maybe it should be initialized directly in the class
A?
Is there a reason for this (false, I think) warning?
Yes, this looks like a false positive. Base class subobjects are initialized before direct member subobjects and A(std::move(a)) will use the implicit move constructor which initializes this->i with a.i, so this->i will be initialized before the initialization of this->j is performed (which reads this->i).
The argument given to the constructor in main is also completely initialized via aggregate initialization, so a.i's value will not be indeterminate either.

Chain member initializers

Is it possible to refer to class members inside "in class initializers"?
Example:
struct Example
{
std::string a = "Hello";
std::string b = a + "World";
};
It seems to work (compiles and runs) but is it ok to do?
This is allowed in default initializers since C++11. Scroll down to the "Usage" section and look at the first example. I copied the explanation and example here for easier reference:
The name of a non-static data member or a non-static member function can only appear in the following three situations:
As a part of class member access expression, in which the class either has this member or is derived from a class that has this member, including the implicit this-> member access expressions that appear when a non-static member name is used in any of the contexts where this is allowed (inside member function bodies, in member initializer lists, in the in-class default member initializers).
struct S
{
int m;
int n;
int x = m; // OK: implicit this-> allowed in default initializers (C++11)
S(int i) : m(i), n(m) // OK: implicit this-> allowed in member initializer lists
{
this->f(); // explicit member access expression
f(); // implicit this-> allowed in member function bodies
}
void f();
};
#include<bits/stdc++.h>
using namespace std;
struct Example
{
string a = "Hello";
string b = a + "World";
};
int main(){
Example val ;
val.a = "Salom";
cout<<val.a<<" "<<val.b;
}
it is okey, you can do it .
but captures the initial result you have If you give a a new value b will not be updated

Initializing class members with {}

Someone gave me (part of) the following code:
struct MyStruct
{
int x = {};
int y = {};
};
I never saw this syntax before, what does initialization with {} mean?
This is default member initializer (since C++11),
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.
The initialization itself is copy-list-initialization (since C++11), as the effect, the data member x and y would be value-initialized (and zero-initialized as built-in type) to 0.
Since the C++11 standard there are two ways to initialize member variables:
Using the constructor initialization list as "usual":
struct Foo
{
int x;
Foo()
: x(0)
{
}
};
Use the new inline initialization where members are getting their "default" values using normal initialization syntax:
struct Foo
{
int x = 0;
};
Both these ways are for many values and types equivalent.

seeking clarification on constexpr function

Consider the following code segment:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:
//constexpr A (){i = 0;}
constexpr A ():i(0){}
void show (void){cout << i << endl; return;}
private:
int i;
};
class B
{
public:
constexpr B(A a){this->a = a;}
//constexpr B(A a):a(a){}
void show (void){a.show(); return;}
private:
A a;
};
int main (void)
{
A a;
B b(a);
b.show();
return (0);
}
Inside the definition of class A, if the current constructor definition is replaced by the definition commented out:
//constexpr A (){i = 0;}
the following compilation error ensues (note that line numbers correspond to original code):
g++ -ggdb -std=c++17 -Wall -Werror=pedantic -Wextra -c code.cpp
code.cpp: In constructor ‘constexpr A::A()’:
code.cpp:8:30: error: member ‘A::i’ must be initialized by mem-initializer in ‘constexpr’ constructor
constexpr A (){i = 0;}
^
code.cpp:12:13: note: declared here
int i;
^
make: *** [makefile:20: code.o] Error 1
However, the code compiles perfectly with either definition for the constructor of class B (the current as well as the definition commented out in the source code reproduced.)
I have looked at the following pages with the objective of understanding what is going on here:
constexpr specifier (since C++11)
Constant expressions
I must admit that I am not able to figure out why the member initializer list is mandated in the case of the constructor for A, and not in the case of B.
Appreciate your thoughts.
A has a default constructor (which is constexpr by the way). The relevant requirements for a constexpr constructor that you are citing are as follows:
for the constructor of a class or struct, ... every non-variant
non-static data member must be initialized.
The only requirement that it is "initialized". Not "explicitly initialized". A default constructor will meet the initialization requirement. A has a default constructor. So your B's a class member gets initialized by its default constructor, meeting this requirement, so you don't have to explicitly initialize it in B's constructor's initialization list.
On the other hand, your garden variety int does not have a default constructor. For that reason, A's constexpr constructor must initialize it explicitly.

In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?

Internally and about the generated code, is there a really difference between :
MyClass::MyClass(): _capacity(15), _data(NULL), _len(0)
{
}
and
MyClass::MyClass()
{
_capacity=15;
_data=NULL;
_len=0
}
thanks...
You need to use initialization list to initialize constant members,references and base class
When you need to initialize constant member, references and pass parameters to base class constructors, as mentioned in comments, you need to use initialization list.
struct aa
{
int i;
const int ci; // constant member
aa() : i(0) {} // will fail, constant member not initialized
};
struct aa
{
int i;
const int ci;
aa() : i(0) { ci = 3;} // will fail, ci is constant
};
struct aa
{
int i;
const int ci;
aa() : i(0), ci(3) {} // works
};
Example (non exhaustive) class/struct contains reference:
struct bb {};
struct aa
{
bb& rb;
aa(bb& b ) : rb(b) {}
};
// usage:
bb b;
aa a(b);
And example of initializing base class that requires a parameter (e.g. no default constructor):
struct bb {};
struct dd
{
char c;
dd(char x) : c(x) {}
};
struct aa : dd
{
bb& rb;
aa(bb& b ) : dd('a'), rb(b) {}
};
Assuming that those values are primitive types, then no, there's no difference. Initialization lists only make a difference when you have objects as members, since instead of using default initialization followed by assignment, the initialization list lets you initialize the object to its final value. This can actually be noticeably faster.
Yes. In the first case you can declare _capacity, _data and _len as constants:
class MyClass
{
private:
const int _capacity;
const void *_data;
const int _len;
// ...
};
This would be important if you want to ensure const-ness of these instance variables while computing their values at runtime, for example:
MyClass::MyClass() :
_capacity(someMethod()),
_data(someOtherMethod()),
_len(yetAnotherMethod())
{
}
const instances must be initialized in the initializer list or the underlying types must provide public parameterless constructors (which primitive types do).
I think this link http://www.cplusplus.com/forum/articles/17820/ gives an excellent explanation - especially for those new to C++.
The reason why intialiser lists are more efficient is that within the constructor body, only assignments take place, not initialisation. So if you are dealing with a non-built-in type, the default constructor for that object has already been called before the body of the constructor has been entered. Inside the constructor body, you are assigning a value to that object.
In effect, this is a call to the default constructor followed by a call to the copy-assignment operator. The initialiser list allows you to call the copy constructor directly, and this can sometimes be significantly faster (recall that the initialiser list is before the body of the constructor)
I'll add that if you have members of class type with no default constructor available, initialization is the only way to construct your class.
A big difference is that the assignment can initialize members of a parent class; the initializer only works on members declared at the current class scope.
Depends on the types involved. The difference is similar between
std::string a;
a = "hai";
and
std::string a("hai");
where the second form is initialization list- that is, it makes a difference if the type requires constructor arguments or is more efficient with constructor arguments.
The real difference boils down to how the gcc compiler generate machine code and lay down the memory. Explain:
(phase1) Before the init body (including the init list): the compiler allocate required memory for the class. The class is alive already!
(phase2) In the init body: since the memory is allocated, every assignment now indicates an operation on the already exiting/'initialized' variable.
There are certainly other ways to handle const type members. But to ease their life, the gcc compiler writers decide to set up some rules
const type members must be initialized before the init body.
After phase1, any write operation only valid for non-constant members.
There is only one way to initialize base class instances and non-static member variables and that is using the initializer list.
If you don't specify a base or non-static member variable in your constructor's initializer list then that member or base will either be default-initialized (if the member/base is a non-POD class type or array of non-POD class types) or left uninitialized otherwise.
Once the constructor body is entered, all bases or members will have been initialized or left uninitialized (i.e. they will have an indeterminate value). There is no opportunity in the constructor body to influence how they should be initialized.
You may be able to assign new values to members in the constructor body but it is not possible to assign to const members or members of class type which have been made non-assignable and it is not possible to rebind references.
For built in types and some user-defined types, assigning in the constructor body may have exactly the same effect as initializing with the same value in the initializer list.
If you fail to name a member or base in an initializer list and that entity is a reference, has class type with no accessible user-declared default constructor, is const qualified and has POD type or is a POD class type or array of POD class type containing a const qualified member (directly or indirectly) then the program is ill-formed.
If you write an initializer list, you do all in one step; if you don't write an initilizer list, you'll do 2 steps: one for declaration and one for asign the value.
There is a difference between initialization list and initialization statement in a constructor.
Let's consider below code:
#include <initializer_list>
#include <iostream>
#include <algorithm>
#include <numeric>
class MyBase {
public:
MyBase() {
std::cout << __FUNCTION__ << std::endl;
}
};
class MyClass : public MyBase {
public:
MyClass::MyClass() : _capacity( 15 ), _data( NULL ), _len( 0 ) {
std::cout << __FUNCTION__ << std::endl;
}
private:
int _capacity;
int* _data;
int _len;
};
class MyClass2 : public MyBase {
public:
MyClass2::MyClass2() {
std::cout << __FUNCTION__ << std::endl;
_capacity = 15;
_data = NULL;
_len = 0;
}
private:
int _capacity;
int* _data;
int _len;
};
int main() {
MyClass c;
MyClass2 d;
return 0;
}
When MyClass is used, all the members will be initialized before the first statement in a constructor executed.
But, when MyClass2 is used, all the members are not initialized when the first statement in a constructor executed.
In later case, there may be regression problem when someone added some code in a constructor before a certain member is initialized.
Here is a point that I did not see others refer to it:
class temp{
public:
temp(int var);
};
The temp class does not have a default ctor. When we use it in another class as follow:
class mainClass{
public:
mainClass(){}
private:
int a;
temp obj;
};
the code will not compile, cause the compiler does not know how to initialize obj, cause it has just an explicit ctor which receives an int value, so we have to change the ctor as follow:
mainClass(int sth):obj(sth){}
So, it is not just about const and references!