简体   繁体   中英

Initializing data member of struct in C++

//Not able to figure out how we can initialize data member of an struct inside //struct . I believe this is against the guidelines of OOP . The below program is not showing any compiler error and runs fines and gives output 10 30

#include<iostream>
using namespace std;
struct Accumulator
{
    int counter = 0;
    int operator()(int i) { return counter += i; }
};
int main(void)
{
   Accumulator acc;
   cout << acc(10) << endl; //prints "10"
   cout << acc(20) << endl; //prints "30"
}

The rules regarding in class initialization have changed. Starting in C++11 you can initialize a non static class member directly in the class body. This is just syntactic sugar though. When you write

struct Accumulator
{
    int counter = 0;
    int operator()(int i) { return counter += i; }
};

The compiler will actually add the initialization of counter to the default constructor. So the above code would get translated to

struct Accumulator
{
    int counter;
    Accumulator() : counter(0) {}
    int operator()(int i) { return counter += i; }
};

This initialization is also suppressed if you supply your own initialization. If we had

struct Accumulator
{
    int counter = 0;
    int sum = 0;
    Accumulator() {}
    Accumulator(int counter) : counter(counter) {}
    int operator()(int i) { return counter += i; }
};

Then Accumulator() {} would actually be

Accumulator() : counter(0), sum(0) {}

and Accumulator(int counter) : counter(counter) {} would be

Accumulator(int counter) : counter(counter), sum(0) {}

That's done with the constructor , to which you can pass the initial value.

Something like:

struct Accumulator
{
    Accumulator(int initial = 0)
        : counter(initial)
    {}

    int counter;

    int operator()(int i) { return counter += i; }
};

int main(void)
{
    Accumulator acc(20);
    std::cout << acc(10) << '\n'; //prints "30"
    std::cout << acc(20) << '\n'; //prints "50"

    // Reset accumulator
    acc = Accumulator();  // Use constructors default argument
    std::cout << acc(10) << '\n'; //prints "10"
    std::cout << acc(20) << '\n'; //prints "30"
}

If you wonder why it's working without the constructor too, that's because the structure without a constructor is an aggregate and you can use aggregate initialization .

If you wonder about the initialization of the counter member, it's because it's a non-static data member and since the C++11 standard those can be initialized like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM