As I noticed everybody says that THE ONLY difference between classes and structs is access mode.
But I have noticed that initialization is also different.
I mean if we have
struct SA{int n;};
class CA{public:int n;}
then we can write
SA sa = {2};
but we cannot write
CA ca = {2}; // compile error
Is not a difference also?

Recommended Answers

All 5 Replies

What compiler? Your statements work fine in VC++ 2008

just realised the access ;)

But that should be fine, what compiler error do you get?

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).

It's possible to initialize class CA object (see OP) with initializer-clause { ... } in the standard C++.
However it's impossible to initialize with { ... } struct SS object:

struct S {};
struct SS: S { int x; };
SS ss = { 1 }; // error: SS is not an aggregate (has parent).

You can use a struct in practically (this means: in most cases, but not always) the same way as a class (because technically structs are classes in C++), consider the following example:

[B]struct[/B] s {
void disp();
s(int num);
[B]private:[/B]
	int n;
};

s::s(int num) {
	n = num;
}

void s::disp() {
	cout << "n = " << n << endl;
}

and it's class equivalent:

[B]class[/B] s {
int n;
[B]public:[/B]
    void disp();
    s(int num);
};

s::s(int num) {
	n = num;
}

void s::disp() {
	cout << "n = " << n << endl;
}

But most of the time the struct is just used as a POD datatype (= Plain Old Data, which means the structs are used like they did before in C: to group related variables)
If you want a class in C++, the preferred way is declaring it by using the class keyword and not by using the struct keyword (however it's possible, as you can see in the above example)
The only difference between a struct and a class is the data's access specifier which is different by default: in a struct all data is made public by default, in a class it's just the opposite: all the data is private by default.

>But I have noticed that initialization is also different.
Use a constructor like in the above example :)

commented: thanks I'm digging you'r post +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.