How clear all object in contructor?

class A has many fields:
class A{
int a0;
int a1;
int a2;
int a3;
A();
}

contructor A can clear field by field:
A:A()
{
a0 = 0;
a1 = 0;
a2 = 0;
a3 = 0;
}
but how do better?
One solution is
A:A()
{
memset(this, 0, sizeof(A));
}
but fields of subclass will not clear
1
2
3
A:A() : a0(0), a1(0), a2(0), a3(0)
{
}

https://isocpp.org/wiki/faq/ctors#init-lists
Last edited on
But if is way to zero whole object memory?
Do not zero the whole object memory of a class object. You don't know what's in it. It can contain more than just the variables you defined in the class definition. You could zero out something important and cause yourself big problems.

In a really simple class with really simple objects inside it, you might get away with it, but it's still a bad idea.
Last edited on
Just further:

A constructor's purpose is to initialise the member variables: you should have valid values to put in them, why do you want to zero them?

If you have an array of 4 elements it's very easy to initialize all of them to zero.

1
2
3
4
5
6
7
8
9
10
11
12
class A
{
public:
	A();
private:
	int a[4];
};

A::A()
:	a{} // initilizes all array elements to zero
{
}
Last edited on
Topic archived. No new replies allowed.