Aggregate classes can be aggregate initialized using an initializer list:
struct Agg {
string a;
int b;
}
Agg a = {"A string", 0};
They are mainly used as a tupple-like return value like so:
struct Response {
bool success;
string body; // Body is only set if success is true
}
Response foo() {
if(failed) return {false, ""};
return {true, "content"};
}
As you can see all four requirements have to be fulfilled for this to be meaningful (before c++11).
All of its data members are public
It's pretty much just a tuple of objects.
It does not define any constructors
Well, either you initialize all members (via aggregate initialization) or you default initialize all members (with the default constructor).
It has no in-class initializers
Same as above
It has no base classes or virtual functions
It's tuple-like, so base classes would destroy that and virtual functions don't make sense since you wouldn't inherit from such a class.
I hope this clears it up a bit. Remember that this is was invented before C++11 where std::tuple
wouldn't exist so you would have used an aggregate class to return multiple values. Nowadays in most use cases you could use tuple
aswell but it is not my favorite.
std::tuple
vs aggregate classes
- An aggregate class can define member functions
- An aggregate class can overload operators.
- An aggregate can define useful names for its attributes
- etc.. to expand
Most of the time, aggregate classes are the way to go. tuple should only be used if you really want nothing else but returning a tuple of objects, and then "breaking it into its pieces". Member functions don't make sense most of the time but aggregate classes can still overload the cast operator for example.
Use tuples only when you only want to do nothing but retuning a bunch of objects together, without a need to "name" them (via member names in aggregates)