Difference Between Structure and Class in C++ (original) (raw)

Last Updated : 3 Jun, 2026

In C++, both structures (struct) and classes (class) are user-defined data types used to group related data and functions into a single unit. They support almost the same features, including member functions, constructors, inheritance, and polymorphism. The primary differences between them lie in their default access control and inheritance behavior.

Structure

A structure is a user-defined data type that groups related variables under a single name. In C++, structures can also contain member functions, constructors, and other class-like features.

#include using namespace std;

struct Student{

int id;
string name;

};

int main(){

Student s;

s.id = 101;
s.name = "Rahul";

cout << s.id << " " << s.name;

return 0;

}

`

Explanation

Class

A class is a user-defined data type that encapsulates data and functions into a single unit. It is one of the fundamental building blocks of Object-Oriented Programming (OOP).

#include using namespace std;

class Student{

private: int id;

public: void setId(int i) { id = i; }

void display() {
    cout << id;
}

};

int main(){

Student s;

s.setId(101);
s.display();

return 0;

}

`

Explanation

Structure Members are Public by Default

C++ `

#include

using namespace std;

struct Test { // x is public int x; };

int main() { Test t; t.x = 20;

// works fine because x is public
cout << t.x;

}

`

**Explanation

Key Differences Between Structure and Class

Although structures and classes are functionally very similar, they differ in a few default behaviors.

Class Structure
Members of a class are private by default. Members of a structure are public by default.
It is declared using the **class keyword. It is declared using the **struct keyword.
Inheritance is private by default. Inheritance is public by default.
It is normally used for Object Oriented Programming. It also allows almost all features of a class, but is normally used for the grouping of different datatypes.