C ++ all the differences between "struct" and "class"?

Possible duplicate:
What are the differences between structure and class in C ++

I used to think that the only differences between C ++ classes were the default class, access modifiers for the member, and the guarantee of the folded type.

It turns out I was wrong because this code does not compile:

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

then how it does:

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

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

error C2552: 'var' : non-aggregates cannot be initialized using the list of initializers

So yes, I will ask a duplicate duplicate question (I hope without duplicate answers!):

What are all the differences between C ++ structures and classes?

Of course, feel free to close this if you discover that I missed something on other issues - of course I could. But I did not see this being discussed in any of the answers, so I thought I'd ask.

+6
source share
4 answers

You can use the initializer {} only for aggregates 1 and the first is not an aggregate, since it has one private data element.

The standard says in section Β§8.5.1 / 1,

An aggregate is an array or class (section 9) without the user declaring constructors (12.1), there are no private or protected non-static data elements (section 11), there are no base classes (section 10), and there are no virtual functions (10.3).

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

Also see this for a detailed answer (in {} initializer):

+15
source

This is not the difference between class and struct , but between aggregates and non-aggregates. You cannot use an initialization list with a non-aggregate type, but this is not related to the class or struct :

 class { public: int value; } var = {42}; // compiles struct { private: int value; } var = {42}; // error 
+4
source

Difference between public and private.

Try this instead:

 class { public: int value; } var = { 42 }; 
+3
source

Class members seem to be private, and any inheritance is private when the structure is open.

Someone else will have to give you more details, though, sorry.

+1
source

Source: https://habr.com/ru/post/895864/


All Articles