Initializing default values in a struct - c++

If I needed to initialize only a few select values of a C++ struct, would this be correct:
struct foo {
foo() : a(true), b(true) {}
bool a;
bool b;
bool c;
} bar;
Am I correct to assume I would end up with one struct item called bar with elements bar.a = true, bar.b = true and an undefined bar.c?

You don't even need to define a constructor
struct foo {
bool a = true;
bool b = true;
bool c;
} bar;
To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.
See a live example here: struct demo
According to C++ standard Section 8.5.12:
if no initialization is performed, an
object with automatic or dynamic storage duration has indeterminate value
For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.
If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

You can do it by using a constructor, like this:
struct Date
{
int day;
int month;
int year;
Date()
{
day=0;
month=0;
year=0;
}
};
or like this:
struct Date
{
int day;
int month;
int year;
Date():day(0),
month(0),
year(0){}
};
In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

An explicit default initialization can help:
struct foo {
bool a {};
bool b {};
bool c {};
} bar;
Behavior bool a {} is same as bool b = bool(); and return false.

Related

Access fields in a named union

I want to have a named union in the following struct so that I can memcpy it without knowing what field is "active".
struct Literal {
enum class Type : size_t {
INT = 1,
LONG,
FLOAT,
DOUBLE
} type;
union {
int li;
long ll;
float lf;
double ld;
} v;
constexpr Literal(int li): type{Type::INT}, v.li{li} {}
constexpr Literal(long ll): type{Type::LONG}, v.ll{ll} {}
constexpr Literal(float lf): type{Type::FLOAT}, v.lf{lf} {}
constexpr Literal(double ld): type{Type::DOUBLE}, v.ld{ld} {}
};
How can I initialize the fields in the constructors? Neither v.li{li} nor li{li} are working.
I also tried v{li} but it work only for the first constructor because it cast the 3 others to int.
EDIT: From #StoryTeller answer and comment:
struct Literal {
enum class Type : size_t {
INT = 1,
LONG,
FLOAT,
DOUBLE
} type;
union {
#define UNION_FIELDS int li; long ll; float lf; double ld;
union { UNION_FIELDS } value;
union { UNION_FIELDS };
};
};
You can only initialize direct members of Literal in its c'tors member initializer list. Aggregate initialization of the union member won't work due to narrowing conversions. So your options are to:
Name the union member type, and add appropriate c'tors to it.
Recurse in order to force the union fields into being treated as fields of the Literal class. Have a union of unions, and rely on the common initial sequence guarantee:
union {
union {
int li;
long ll;
float lf;
double ld;
} v;
union {
int li;
long ll;
float lf;
double ld;
};
};
constexpr Literal(int li): type{Type::INT}, li{li} {}
constexpr Literal(long ll): type{Type::LONG}, ll{ll} {}
constexpr Literal(float lf): type{Type::FLOAT}, lf{lf} {}
constexpr Literal(double ld): type{Type::DOUBLE}, ld{ld} {}
The above allows you to refer to each field by name, on account of the anonnymous union member, as well as lumping them together using the named v member. But I'll be the first to admit, it's ugly.

C++ and C non-member multiple structs initialization

How to initialize two or more structures with the same data? This has to be done at compile time to be as default data for const structures that are non-member global variables.
EDIT:
And what about C?
Works for me:
// header
struct Foo {
int a;
int b;
};
extern Foo const x;
extern Foo const y;
// cpp file
Foo const x{2, 3};
Foo const y = x;
Edit: reinterpreted the question a little.
One way is:
#define DATA { bla,bla,bla,bla }
var a = DATA;
var b = DATA;
You can use the copy constructor to initialize the structs. (This requires the use of a helper function to ensure correct order of initialization.) If the structures are POD, this should be as efficient as regular compile-time initialization:
struct A {
int a;
double c;
};
A initial_data() {
return { 1, 2.0 };
}
A a = initial_data();
A b = initial_data();

Is there a way in C++ to preinitialize structure or class without a constructors?

I mean: I've a bunch of various structures/classes and all this a splendor shall be initialized with known in advance values. Those structures/classes will never be used other way except the preinitialized one, so there is no any need for constructor -- it's just a waste of extra memory, extra CPU cycles in program, and extra space in source code.
If you have access to a C++11 compiler, you can mark your constructors as constexpr to have them run at compile time. The benefit of this is that way down the road you can still construct your objects at runtime. e.g.
struct Point2D {
constexpr Point2D(int x, int y) : x_{x}, y_{y} {}
int x_, y_;
};
And now you can use Point2D's constructor to initialize it at compile time, instead of runtime:
Point2D p{3, 4}; // no runtime overhead.
Structures and classes can be initialized, in limited circumstances.
struct splendor {
int i, j;
char *name;
};
splendor iforus = { 1, 2, "Extra!" };
Additionally, if you never need the name of the type of the structure:
struct {
int k;
float q;
} anon_e_mouse = { 1, 2.3 };
You can just initialize the members at the point of declaration:
struct Foo
{
int i = 42;
double x = 3.1416;
std::string name = "John Doe";
};
This will set up the default values for all instances:
Foo f;
std::cout << f.i << std::endl; // prints 42
Note that this does not work with C++03, it requires C++11 support.
If a class (or struct) doesn't have a constructor, you can initialize it like so:
MyClass a = MyClass();
or
MyClass * b = new MyClass();
This is called value initialization and it usually amounts to zero-initialization.
C++11 gives you initializer_list.
#include <iostream>
struct s
{
int i;
};
int main() {
s s1={666};
s s2={42};
std::cout<<s1.i<<" "<<s2.i<<std::endl;
return 0;
}
You can also do in-class initialization for member.
#include <iostream>
struct s
{
int i=0;
};
int main() {
s s1; //s1.i = 0
//s s2={42}; //fails
std::cout<<s1.i<<" "<<std::endl;
return 0;
}
But you cant do bot at the same time.
It sounds like you are trying to implement the Singleton Pattern. When you do that, you still need a constructor (in fact, if you want to force it to be a singleton, you have to declare the default constructor as private).
class MySingleton
{
private:
// my data
MySingleton() { /* initialize my data */ }
public:
static MySingleton& GetInstance()
{
static MySingleton instance;
return instance;
}
// other functions
};

C++: Custom data type - typecasting and union issues

What I'm trying to do is create a new custom data type that behaves like all other primitive types. Specifically, this data type appears like a Fixed Point fraction.
I've created a class to represent this data type, called "class FixedPoint", and in it there are ways to typecast from "FixedPoint" to "int" or "double" or "unsigned int", etc. That is fine.
Now, what if I want to cast from "int" to "FixedPoint"? Originally my solution was to have a constructor:
FixedPoint(int i) { /* some conversion from 'int' to 'FixedPoint' in here */ }
This works...but you cannot put it into a union like so:
union {
FixedPoint p;
};
This will break, because "FixedPoint" does not have an implicit trivial constructor (we just defined a constructor, "FixedPoint(int i)").
To summarize, the whole issue is "we want to cast from some type T to type FixedPoint without explicitly defining a constructor so we can use our type FixedPoint in a union".
What I think the solution is but cannot find any evidence online:
Define an overloaded global typecast operator to cast from "int" to "FixedPoint".
Is there a way to do this without using class constructors? I'd like to be able to use this class in a union. What I've tried (in global scope):
operator (FixedPoint f, int a) { ... } //compiler complains about this is not a method or non-static.
And a little example to show unions don't like constructors (they like POD)
class bob
{
public:
bob(int a) { m_num = a; }
private:
int m_num;
};
void duck()
{
union
{
bob a;
};
}
This error seen in Visual Studio is:
error C2620: member 'duck::<unnamed-tag>::a' of union 'duck::<unnamed-tag>' has user-defined constructor or non-trivial default constructor
Any ideas?
Thanks
I am having a hard time at seeing what you would try to use this for. It seems smelly to have to constantly ensure that sizeof(FixedPoint) == sizeof(int) and, assuming that, there are other hidden gotchas, like endianness. Maybe I should back up a little bit here, unions only "convert" a value from one type to another in that it takes a chunk of memory and references it as a different type. i.e.
union BadConverter
{
int integer;
double fraction;
};
BadConverter.fraction = 100.0/33.0;
BadConverter.integer = ?;
I am pretty sure integer is not going to be 3, it is going to whatever the memory chunk of the double is that the integer bytes share with it.
Unions don't seem to be a very good fit for this sort of thing. I would think just defining a bunch of assignment operators from all the primitive types. i.e.
class FixedPoint
{
FixedPoint& operator=(int value);
FixedPoint& operator=(double value);
..etc..
//Maybe something like this?
template<typename T>
FixedPoint& operator=(const T& value)
{
value = boost::lexical_cast<int>(value);
return *this;
}
}
Custom conversion operators must be a member of the class that is being converted from. A non-trivial constructor is not required.
EDIT: I reworked the example to utilize a union since this is what you were asking about.
EDIT2: See below if you are trying to go the other way (construction) and don't want constructors.
#include <string>
#include <sstream>
using namespace std;
class FixedPoint
{
public:
operator std::string() const
{
stringstream ss;
ss << x_ << ", " << y_;
return ss.str();
}
int x_, y_;
};
union Items
{
FixedPoint point_;
int val_;
};
int main()
{
Items i;
i.point_.x_ = 42;
i.point_.y_ = 84;
string s = i.point_;
}
If you're trying to go the other way -- eg, from an int to FixedPoint in my example -- then the normal way to do this is indeed to use a conversion constructor. Given that you don't want a non-trivial constructor, you have to resort to a conversion function.
FixedPoint make_fixed_point(int x, int y)
{
FixedPoint ret;
ret.x_ = x;
ret.y_ = y;
return ret;
}
union Items
{
FixedPoint point_;
int val_;
};
int main()
{
Items i;
i.point_ = make_fixed_point(111,222);
}
Can't you just add a default constructor that'll allow it to be part of the union.
For example:
class bob
{
public:
bob(int a=0) { m_num = a; }
private:
int m_num;
};
void duck()
{
union
{
bob a;
};
}
By giving the a=0 default, it should be able to be put in a union. I didn't try it myself, though.

Are members of a C++ struct initialized to 0 by default?

I have this struct:
struct Snapshot
{
double x;
int y;
};
I want x and y to be 0. Will they be 0 by default or do I have to do:
Snapshot s = {0,0};
What are the other ways to zero out the structure?
They are not null if you don't initialize the struct.
Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members
The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:
struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members
The second will make p.s.{x,y} zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors
struct Snapshot {
int x;
double y;
Snapshot():x(0),y(0) { }
// other ctors / functions...
};
Will initialize both x and y to 0. Note that you can use x(), y() to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.
No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor
Snapshot() : x(0), y(0) {
}
This ensures that all uses of Snapshot will have initialized values.
In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):
int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0
void foo() {
struct { int a, b; } bar; // undefined
static struct { int c, d; } quux; // 0, 0
}
With POD you can also write
Snapshot s = {};
You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.
or like this:
struct init
{
template <typename T>
operator T * ()
{
return new T();
}
};
Snapshot* s = init();
In C++, use no-argument constructors. In C you can't have constructors, so use either memset or - the interesting solution - designated initializers:
struct Snapshot s = { .x = 0.0, .y = 0.0 };
Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:
Snapshot s;
memset(&s, 0, sizeof (s));
or similarly
Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));
I wouldn't go so far as to use calloc() in a C++ program though.
I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.
Move pod members to a base class to shorten your initializer list:
struct foo_pod
{
int x;
int y;
int z;
};
struct foo : foo_pod
{
std::string name;
foo(std::string name)
: foo_pod()
, name(name)
{
}
};
int main()
{
foo f("bar");
printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}
I know this question is super old, but this question popped up for me on google and I found this other way and figured I'd add it here:
Snapshot s {};
I'm not sure what C/C++ language version you need for this syntax.