Does a C++ Struct Have a Default Constructor

Does a c++ struct have a default constructor?

The simple answer is yes.

It has a default constructor.

Note: struct and class are identical (apart from the default state of the accesses specifiers).

But whether it initializes the members will depends on how the actual object is declared. In your example no the member is not initialized and a has indeterminate value.

void func()
{
_bar_ a; // Members are NOT initialized.
_bar_ b = _bar_(); // Members are zero-initialized
// From C++14
_bar_ c{}; // New Brace initializer (Members are zero-initialized)

_bar_* aP = new _bar_; // Members are NOT initialized.
_bar_* bP = new _bar_(); // Members are zero-initialized
// From C++14
_bar_ cP = new _bar_{}; // New Brace initializer (Members are zero-initialized)
}

// static storage duration objects
// i.e. objects at the global scope.
_bar_ c; // Members are zero-initialized.

The exact details are explained in the standard at 8.5 Initializers [dcl.init] paragraphs 4-10. But the following is a simplistic summary for this situation.

A structure without a user defined constructor has a compiler generated constructor. But what it does depends on how it is used and it will either default initialize its members (which for POD types is usually nothing) or it may zero initialize its members (which for POD usually means set its members to zero).

PS. Don't use a _ as the first character in a type name. You will bump into problems.

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

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.

default value for struct member in C

Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.

So no this is not possible in C.

Instead you can write a function which does the initialization for structure instance.

Alternatively, You could do:

struct MyStruct_s 
{
int id;
} MyStruct_default = {3};

typedef struct MyStruct_s MyStruct;

And then always initialize your new instances as:

MyStruct mInstance = MyStruct_default;

is there a difference between a struct in c++ and a struct in c#?

In C# you use structs to define value types (as opposed to reference types declared by classes).

In C++, a struct is the same thing as a class with a default accessibility level of public.

So the question should be: are structs in C# different from classes in C++ and, yes, they are: You cannot derive from C# structs, you cannot have virtual functions, you cannot define default constructors, you don't have destructors etc.

Initialization of a C++ Struct with a user defined constructor

In C++11 or later, your first example is correct. It will initialize the class members as part of the construction process and this will happen before the body the struct State constructor is called. Prior to C++11, the in-class initialization of members in that manner is not valid and will not compile. You would instead write the following parts differently, using an initializer list, which produces the same behavior in as your C++11 code.

struct State
{
State() : maxDepth(5), verticies(NULL), ambient(0.2)
{ ...
}

int maxDepth;
std::unique_ptr<Point[]> vertices;
Colour ambient;
};

If you write code to set the class members in the body of your constructor, they will be set twice. Once before the struct's constructor executes via the members' default constructors, then again when you set their values in the struct's ctor's body. An int, or other primitive type, doesn't have a default constructor, so it would be uninitialized before the code in the struct ctor body sets it. But an object like the std::unique_ptr would be set twice since it does have a default CTOR that would be used before the struct ctor body runs.

Constructor for structs in C

In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity)

Object* Object_new(int id, int value) { 
Object* p = malloc(sizeof(Object));
p->id = id;
p->value = value;
return p;
}

...
Object* p1 = Object_new(id++, myValue);

Default constructor in C

You can create initializer functions that take a pointer to a structure. This was common practice.

Also functions that create a struct and initialize it (like a factory) - so there is never a time where the struct is "uninitialized" in the "client" code. Of course - that assumes people follow the convention and use the "constructor"/factory...

horrible pseudo code with NO error checking on malloc or free

somestruct* somestruct_factory(/* per haps some initializer agrs? */)
{
malloc some stuff
fill in some stuff
return pointer to malloced stuff
}

void somestruct_destructor(somestruct*)
{
do cleanup stuff and also free pointer
free(somestruct);
}

Someone will probably come along and explain how some early C++ preprocessors/compilers worked to do this all in C.

Why is a constructor necessary in a const member struct?

From §8.5 [dcl.init]/7:

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

The default constructor of AClass default-initializes the const member (see below), so that member must have a user-provided default constructor. Using = default does not result in a user-provided default constructor, as can be seen in §8.4.2 [dcl.fct.def.default]/4:

A function is user-provided if it is user-declared and not explicitly defaulted or
deleted on its first declaration.


The member is default-initialized per §12.6.2 [class.base.init]/8:

In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then

— if the entity is a non-static data member that has a brace-or-equal-initializer , the entity is initialized as specified in 8.5;

— otherwise, if the entity is an anonymous union or a variant member (9.5), no initialization is performed;

otherwise, the entity is default-initialized (8.5).



Related Topics



Leave a reply



Submit