Can someone please tell me the difference between Class and Structure in C++ ???
I cant find any..!!
Thanks

Dani AI

Generated

Short answer: C++ struct and class are the same language feature with one important syntactic difference and one related default for inheritance. was on the right track and 's suggestion that structs can't have functions is incorrect — both can have member functions, constructors/destructors, static members, nested types, virtual functions, templates, etc. For the formal language rules see class (cppreference).

A practical place this matters is when you forget an explicit access or inheritance keyword. For example:

struct Base { int x; };

struct D1 : Base { };   // inherits Base publicly
class  D2 : Base { };   // inherits Base privately

If you leave out public/private on a base, the default differs depending on whether you used struct or class. That difference is the only compile-time behavior that the keywords impose.

Style and ABI notes: by convention struct is often used for passive/public data aggregates and class for encapsulated types with private invariants, but that is just style. Whether a type is trivially copyable, standard-layout, or aggregate (important for C-compatibility and brace-initialization) depends on its members and special members, not whether you wrote struct or class — see aggregate initialization (cppreference). In short: pick struct when you want a simple data carrier with public fields; pick class when you intend encapsulation.

Recommended Answers

All 4 Replies

What is the "default access specifier" for each?

I think that in Class you can define functions and other variables
But in structure you only can define normal variables like int or float or even other struct variable

I agree to the default access specifier....
It's public for structure and private for class....
But as far as functions are concerned, i can create them in structure too...
Is that the only diff... access specifier ???
Thanks

No, you can have functions in a struct (when speaking of the C++ variety -- C structs can only have function pointers). The only difference between structs and classes is the default access specifier.

class MyClass
{
     int a;
}; 

struct MyStruct
{
     int a;
};

In each case is "a" public, private, or protected?
For class, the default is private. For struct, the default is public.

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.