C++ Interview Questions

22 Questions
C++ Programming

C++ Programming

Embedded SystemsIoTOther

Question 10

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

Answer:

In C++, both struct and class are used to define user-defined data types that can encapsulate data members and member functions. However, there are key differences between them:

  1. Default Access Modifier:

    • struct: Members of a struct are public by default.
    • class: Members of a class are private by default.
    struct MyStruct {
        int x; // public by default
    };
    
    class MyClass {
        int x; // private by default
    };
  2. Inheritance Access Specifier:

    • struct: Inheritance is public by default.
    • class: Inheritance is private by default.
    struct BaseStruct {};
    struct DerivedStruct : BaseStruct {}; // public inheritance
    
    class BaseClass {};
    class DerivedClass : BaseClass {}; // private inheritance
  3. Use Case:

    • struct: Typically used for passive objects with public data members (PODs - Plain Old Data structures).
    • class: Used for objects with private data members, encapsulation, and methods to manipulate the data.
  4. Encapsulation: While both can encapsulate data and methods, class is generally used when encapsulation and data hiding are more crucial.

  5. Friendship and Member Functions: Both struct and class can have member functions, constructors, destructors, and friend functions. The use and syntax are identical for both.

  6. Flexibility: Both can be used interchangeably in many cases, but using class can make the code more readable by explicitly conveying the intent of encapsulation and object-oriented design principles.

Example:

struct Point {
    int x, y;
    Point(int a, int b) : x(a), y(b) {}
    void display() const {
        std::cout << "Point(" << x << ", " << y << ")\n";
    }
};

class Circle {
private:
    Point center;
    double radius;
public:
    Circle(Point c, double r) : center(c), radius(r) {}
    void display() const {
        std::cout << "Circle with center ";
        center.display();
        std::cout << " and radius " << radius << "\n";
    }
};

int main() {
    Point p(1, 2);
    Circle c(p, 5.0);
    p.display();
    c.display();
    return 0;
}

In this example, Point is a struct with public data members and methods, suitable for a simple data structure. Circle is a class with private data members and public methods, demonstrating encapsulation. While the differences are subtle, using class for more complex objects and struct for simpler data structures can enhance code clarity and maintainability.

Recent job openings