Can you define variables in a class/struct?

I used to own the C++ Primer 4th Edition which stated that definitions should not appear in headers. But the new edition has this:

1
2
3
4
5
6
7
8
9
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <string>
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
#endif 


There are definitions in the header( units_sold = 0 ). So is this contradictory information?
Last edited on
> There are definitions in the header( units_sold = 0 ). So is this contradictory information?

These are default member initialisers. They came with C++11.

For more information, see: 'Member initialization' in http://en.cppreference.com/w/cpp/language/data_members
These are default member initialisers. They came with C++11.


So what is the difference between default member initialisers and normal definitons?

Also, am I allowed to define methods in classes/structs/headers? (still don't understand the difference)
> So what is the difference between default member initialisers and normal definitons?

1.
If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored. http://en.cppreference.com/w/cpp/language/data_members

2. Only a brace-or-equal-initialiser is accepted as a default member initialiser
Last edited on
Topic archived. No new replies allowed.