Struct vs Class

Are Struct Members Private or Public by Default?

In C++, struct members are public by default, while class members are private. Here is how the default works, how to change it, and how C structs differ.

On this page
  1. The short answer
  2. A short example
  3. Making struct members private
  4. Inheritance defaults
  5. Should you rely on the default?
  6. Structs in C

The short answer

Is struct private or public by default? In C++, struct members are public by default. Class members are private by default. This applies to data members and member functions alike, and you can change it with an access label.

A short example

#include <iostream>

struct Car {
    int year;  // public by default
};

class Bike {
    int wheels;  // private by default
};

int main() {
    Car car;
    car.year = 2020;
    std::cout << car.year << '\n';  // prints 2020

    Bike bike;
    // bike.wheels = 2;  // If you uncomment this line, the compiler rejects it
}

The year field of Car can be set from main because it is public. The wheels field of Bike cannot, because the class default is private.

Making struct members private

A struct can use access labels just like a class:

struct Thermostat {
private:
    int degrees = 20;

public:
    void set(int value) { degrees = value; }
    int get() const { return degrees; }
};

Here degrees is hidden, so code outside the struct must use set and get. The access labels, including protected, are covered in access modifiers in c.

Inheritance defaults

The same default applies to base classes. struct Derived : Base inherits publicly by default, while class Derived : Base inherits privately. This affects whether code outside the class can treat a derived object as its base. The rules for inherited members are covered in inheritance in c.

Should you rely on the default?

You don’t have to. Writing public: explicitly on a struct makes the intent clear, and some teams do this so readers never have to remember the default. Either way, pick one habit and apply it across the project. For the full comparison of the two keywords, see c struct vs class.

Structs in C

C has no access labels at all. Every field of a C struct can be read and written by any code that can see the struct variable. The question of public or private defaults therefore applies only to C++.

The complete guide to struct vs class

Struct vs Class in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Shift Operators in C++

Learn how the << and >> shift operators work in C++, with binary examples, compound forms, precedence traps, undefined cases, and safe ways to use them.

C++ While Loop Syntax

Learn the C++ while loop syntax, how the condition is checked, and how to avoid infinite loops, with step-by-step examples you can compile and run.

While Loops 4 min read