Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ all differences between 'struct' and 'class'? [duplicate]

Tags:

c++

class

struct

Possible Duplicate:
What are the differences between struct and class in C++

I used to think that the only differences between C++ classes were the private-by-default class member access modifiers and the laid-out-like-C guarantee.

It turns out I was wrong, because this code doesn't compile:

class { int value; } var = { 42 };

whereas this does:

struct { int value; } var = { 42 };

I can't figure out why there's a difference, but there apparently is in Visual C++ 2008:

error C2552: 'var' : non-aggregates cannot be initialized with initializer list

So, yes, I will ask a many-times-over duplicate question (hopefully without duplicate answers!):

What are all the differences between structs and classes in C++?

Of course, feel free to close this if you find that I've missed something in the other questions -- I certainly might have. But I didn't see this being discussed in any of the answers, so I thought I'd ask.

like image 604
user541686 Avatar asked Aug 25 '11 11:08

user541686


1 Answers

You can use {} initializer for aggregates only1 and the first one is not an aggregate, as it has one private data member.

The Standard says in section §8.5.1/1,

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

1. Well, I meant, in C++03, you can use {} for aggregates ONLY, but in C++11, you can use {} even with non-aggregates (if the non-aggregate class is properly implemented to handle this).

Also see this for detail answer (on {} initializer):

  • What is assignment via curly braces called? and can it be controlled?
like image 198
Nawaz Avatar answered Sep 23 '22 07:09

Nawaz