C++ for setting all object's member values to zero not at declaration..

Anyone know C++ way in setting all of an object's member values to zero not at declaration/definition and not using memset?
Last edited on
You provide, as part of the interface of the class, a procedure that modifies the object in desired way.
We can assign an anonymous value-initialised object of the same type.
Value initialisation: https://en.cppreference.com/w/cpp/language/value_initialization

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
    struct A
    {
        // A does not have a user-declared / user-written default constructor

        int i = 22 ;
        int j ; // no default member initialiser
        double d ; // no default member initialiser
        int* p ; // no default member initialiser
    };

    A a ; // a.i == 22 (default initialisation of the other members j, d and p does nothing)
    a.i = -99 ; // a.i == -99

    // assign a value-initialised object of type A
    a = {} ;  // a.i == 22, a.j == 0, a.d = 0.0, a.p == nullptr
    std::cout << a.i << ' ' << a.j << ' ' << std::fixed << a.d << ' ' << a.p << '\n' ;
}

http://coliru.stacked-crooked.com/a/0fdb515c9ba7fdc5
https://rextester.com/XWLUK78130
Topic archived. No new replies allowed.