All Courses
OOP: ACCESS SPECIFIERS

Default Access in `class` and `struct`

In C++, class and struct are very similar.

The main difference is default access.

Default Access in class

Members of a class are private by default.

class MyClass {
    int value; // private by default
};

Default Access in struct

Members of a struct are public by default.

struct Point {
    int x; // public by default
    int y; // public by default
};

Complete Example

#include <iostream>

class Counter {
    int value = 0; // private by default

public:
    void increment() {
        value++;
    }

    int getValue() const {
        return value;
    }
};

struct Point {
    int x = 0; // public by default
    int y = 0; // public by default
};

int main() {
    Counter counter;
    counter.increment();
    std::cout << counter.getValue() << '\n';

    Point point;
    point.x = 10;
    point.y = 20;
    std::cout << point.x << ", " << point.y << '\n';
}

Inheritance Defaults

Default inheritance also differs:

class Child : Parent {};  // private inheritance by default
struct Child2 : Parent {}; // public inheritance by default

In this course, write the inheritance mode explicitly.

class Child : public Parent {};

When To Use Which?

Use struct for simple public data bundles.

struct Point {
    int x;
    int y;
};

Use class for objects with behavior, validation, invariants, or private state.

Viva Answer

In C++, class and struct are almost the same except for default access. Members of a class are private by default, while members of a struct are public by default. Class inheritance defaults to private, while struct inheritance defaults to public.

Quick Check

  • What is default access in a class?
  • What is default access in a struct?
  • When is struct appropriate?
  • Why should inheritance mode be written explicitly?