C/C++ Struct vs Class

In C programming, there is no class keyword − only structures (struct) are available. However, understanding the conceptual differences between struct and class is important for C programmers who may work with C++. In C, structures are used to group related data together.

Syntax

struct structure_name {
    data_type member1;
    data_type member2;
    // ... more members
};

Example: Basic Structure in C

In C, all structure members are accessible by default −

#include <stdio.h>

struct my_struct {
    int x;
    int y;
};

int main() {
    struct my_struct my_obj = {10, 20};
    printf("x = %d, y = %d\n", my_obj.x, my_obj.y);
    return 0;
}
x = 10, y = 20

Example: Structure with Functions (Function Pointers)

C structures can contain function pointers to simulate object-oriented behavior −

#include <stdio.h>

struct calculator {
    int a;
    int b;
    int (*add)(int, int);
    int (*multiply)(int, int);
};

int add_func(int x, int y) {
    return x + y;
}

int multiply_func(int x, int y) {
    return x * y;
}

int main() {
    struct calculator calc = {5, 3, add_func, multiply_func};
    
    printf("Addition: %d\n", calc.add(calc.a, calc.b));
    printf("Multiplication: %d\n", calc.multiply(calc.a, calc.b));
    return 0;
}
Addition: 8
Multiplication: 15

Key Differences (C vs C++)

Feature C struct C++ struct C++ class
Default Access All public Public Private
Member Functions No (only function pointers) Yes Yes
Inheritance No Public by default Private by default

Example: Typedef with Structures

Using typedef makes structure usage cleaner in C −

#include <stdio.h>
#include <string.h>

typedef struct {
    char name[50];
    int age;
    float salary;
} Employee;

int main() {
    Employee emp1;
    strcpy(emp1.name, "John Doe");
    emp1.age = 30;
    emp1.salary = 50000.0;
    
    printf("Name: %s\n", emp1.name);
    printf("Age: %d\n", emp1.age);
    printf("Salary: %.2f\n", emp1.salary);
    return 0;
}
Name: John Doe
Age: 30
Salary: 50000.00

Conclusion

In C, structures provide a way to group related data and can use function pointers for behavior. While C lacks the class concept, structures serve as the foundation for data organization and can simulate object-oriented features when combined with function pointers.

Updated on: 2026-03-15T10:27:22+05:30

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements