You learn something new every day...

A

Allan Bruce

Whilst reading Accelarated C++, I found out that structs in C++ are almost
identical to classes. i.e.

struct Foo
{
public:
Get();
private
int mNum;
};

is the same as:

class Foo
{
public:
Get();
private
int mNum;
};

Apparantly the difference between structs and classes is that a class has
default private access, and a struct has default public access! Well, I
never!

Are there any other differences?
Thanks
Allan
 
J

Jack Applin

Allan said:
Apparantly the difference between structs and classes is that a class has
default private access, and a struct has default public access! Well, I
never!

Are there any other differences?

Yes. A struct defaults to public inheritance, whereas a class defaults
to private inheritance. This code compiles:

struct foo {
int a;
};

struct bar : foo {
} b;

int main() {
int i = b.a;
}

This code should not compile, because b.a is inaccessible:

struct foo {
int a;
};

class bar : foo {
} b;

int main() {
int i = b.a;
}
 
B

Buster

Jack said:
Yes. A struct defaults to public inheritance, whereas a class defaults
to private inheritance.

[I wrote "No."]

You're right, of course. I took the OP's "has default public access"
to mean access to base subobjects as well as access to members.
 
J

jeffc

Allan Bruce said:
Apparantly the difference between structs and classes is that a class has
default private access, and a struct has default public access! Well, I
never!

Are there any other differences?

Similar idea when inheriting regarding the default, but otherwise they are
more or less 2 words for the same thing. Some programmers will use "struct"
when the "class" has no functions, but this is a style issue, not technical
issue.
 
R

Razmig K

jeffc said:
Similar idea when inheriting regarding the default, but otherwise they are
more or less 2 words for the same thing. Some programmers will use "struct"
when the "class" has no functions, but this is a style issue, not technical
issue.

To quote Bjarne Stroustrup:

- Which style you use depends on circumstances and taste. I usually
prefer to use struct for classes that have all data public. I think of
such classes as "not quite proper types, just data structures" .
Constructors and access functions can be quite useful even for such
structures, but as a shorthand rather than guarantors of properties of
the type.

- Use public data (structs) only when it really is just data an no
invariant is meaningful for the data members.

Source: The C++ Programming Language, Third Edition
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,440
Latest member
YoungBorel

Latest Threads

Top