What is the difference between a structure and a class in C++?

balakiran_bs used Ask the Experts™
In C++, Structure also supports Encapsulation,
Data hiding, Inheritance, polymorphism, operator
overloading and the concept of friend functions.

Constructors & Destructors too.

It behaves exactly similar to that of a class.

Then, what is the difference between the two ?

The default scope of structure is public and class
is private. Is it the only difference ?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Yes, You said it.

C++ extends the "C" struct to allow behavioral methods to be bound to the data.  The C++ class then extends the structure to include access specifiers which control access to the data and methods.  A structure by default offers public access to it's members and a class offers private access to it's members.

The following table summarizes the difference between the C, C++ structure and class.

                   "C" struct    "C++" struct    "C++" class
attributes             X               X               X
methods                                X               X
default access      "public"      "public"        "private"


I read this somewhere but just can't remember the source:

"In C++ a struct is equivalent to a class with all members public."
Basicly class is a struct, the only difference is that C++ allows you to do smart manipulations on that struct, during compile time.
when you define a member function, it works just like C function. but when you start inhariting and doing some polymorphism, C++ adds a function pointer to that "struct" and dose changes that pointer to the correct function associated with the class and it's inharitance.
operator overloading behaves similarly.
as a rule, everything you can write in C++ you can do in C , it will only be harder to implement.


I think you need to check your facts and understanding of struct vs. class before you start posting such stuff.

In fact the declaration:

struct basestruct {
 // Whatever...

struct derivedstruct : public basestruct {
 // Whatever...

Is entirely legal in C++.

jhance, You're right, what I meant in my comment to show diffrence between struct in C and class in C++.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial