What are the differences between struct and class in C++?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

In C++, both struct and class are used to define user-defined types that can contain data members (variables) and member functions. While they are very similar, there are key differences primarily in terms of default access specifiers and intended use cases.

Main Differences Between struct and class

1. Default Access Specifier

  • struct: Members are public by default.
  • class: Members are private by default.

Example:

struct StructExample { int a; // Public by default }; class ClassExample { int a; // Private by default };

2. Intended Usage

  • struct: Historically intended for grouping plain data (C-style structs). In modern C++, it is often used for lightweight objects, such as data transfer objects (DTOs).
  • class: Typically used for creating complex objects with encapsulation, inheritance, and polymorphism.

3. Inheritance Default

  • struct: Inheritance is public by default.
  • class: Inheritance is private by default.

Example:

struct Base {}; struct DerivedStruct : Base { // Public inheritance by default }; class DerivedClass : Base { // Private inheritance by default };

4. Use Cases

  • struct:
    • Used when you primarily need to group related data with minimal or no encapsulation.
    • Example: Representing a point in 2D space or a simple record.
  • class:
    • Used for defining objects with rich behavior, encapsulation, and complex relationships like inheritance.
    • Example: Representing an entity like a Car with attributes (e.g., speed, color) and methods (e.g., drive(), brake()).

5. Community Conventions

  • struct: Often used for POD (Plain Old Data) types, where you only define member variables and avoid complex functionality.
  • class: Preferred for defining objects with private members and encapsulated logic.

6. Technical Differences in Memory Layout or Performance

None. Both struct and class are identical in terms of memory layout, performance, and underlying functionality. The differences are purely in default behavior and convention.

Example Comparison

#include <iostream> using namespace std; // Struct example struct Point { int x; // Public by default int y; // Public by default void display() { // Methods can also be in a struct cout << "Point(" << x << ", " << y << ")" << endl; } }; // Class example class Circle { int radius; // Private by default public: Circle(int r) : radius(r) {} int getRadius() { return radius; } }; int main() { Point p = {5, 10}; p.display(); // Output: Point(5, 10) Circle c(7); cout << "Circle radius: " << c.getRadius() << endl; // Output: Circle radius: 7 return 0; }

When to Use struct vs class

  1. Use struct:

    • For simple data aggregation or POD types.
    • When you want everything public by default, like a lightweight DTO or configuration object.
  2. Use class:

    • For objects requiring encapsulation, inheritance, and polymorphism.
    • When you need control over member visibility with private, protected, and public access.

Summary

Featurestructclass
Default Access SpecifierPublicPrivate
Default InheritancePublicPrivate
Primary UseGrouping plain dataDefining complex objects
EncapsulationMinimalEncouraged

Both struct and class are powerful tools in C++. The choice depends on the specific use case and the level of encapsulation and complexity required. For mastering object-oriented concepts and system design, check out Grokking the System Design Interview or Grokking Advanced Coding Patterns for Interviews on DesignGurus.io!

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Is OpenAI a REST API?
How to prepare a Google interview?
Why should we hire you as a cloud engineer?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.