Clear struct, which is member of class in C++

Viewed 92

I want to clear a structure, which is a member of class. Example

struct MyStruct
{
    int my_int;
    char my_array[10];
};

class MyClass {        
   public:       
       MyStruct some_struct;
       void myMethod() {  
           // Here I want to reset my structure
           MyStruct = {};
       }
};

My assumptions are:

  1. MyStruct does not have a constructor, this is POD type.
  2. POD type will are initialized by zeros.

Is it correct? Will my_int be zero and my_array be filled with zeros?

2 Answers

Your intuition is correct (but your syntax is off). MyStruct is an aggregate type and some_struct = {} is assignment to a value-initialized aggregate, which becomes zero-initialization because you are using an initializer consisting of empty braces {}. During zero initialization, each element of the array is zero initialized.

It is instead :

some_struct = {}

Here is the testing code:

#include <iostream>
struct MyStruct
{
    int my_int;
    char my_array[10];
};

class MyClass {
   public:
       MyStruct some_struct;
       void myMethod() {
           // Here I want to reset my structure
           some_struct = {};
       }
};

int main()
{
    MyClass test;
    test.some_struct={1, {1,1,1,1,1,1,1,1,1,1}};

    std::cout << "my_int "<< test.some_struct.my_int<<std::endl;
    for (int i: test.some_struct.my_array)
    {
        std::cout << i << "-";
    }

    test.myMethod();
    std::cout << std::endl;
    std::cout << "my_int "<< test.some_struct.my_int<<std::endl;
    for (int i: test.some_struct.my_array)
    {
        std::cout << i << "-";
    }
}

Related