Difference b/w ‘struct’ & ‘class’

In C++, both struct and class are used to define custom data types. However, they have some key differences in terms of access control. Let’s explore the differences between struct and class with examples.

Key Differences between struct and class

  1. Data Members :
    • struct: Members of a struct are public by default.
    • class: Members of a class are private by default.
  2. Usage:
    • struct: Typically used for simple data structures without complex functionality.
    • class: Typically used for objects with both data and behavior (methods).

Example: Struct vs Class

Let’s consider an example where we define a struct and a class with the same members.

Code for struct:

#include <iostream>
using namespace std;

struct Rectangle {
    int length;     // Public by default
    int breadth;    // Public by default

    int area() {
        return length * breadth;
    }
};

int main() {
    Rectangle rect;
    rect.length = 10;
    rect.breadth = 5;

    cout << "Area (using struct): " << rect.area() << endl;
    return 0;
}

Output:

Area (using struct): 50

Code for class:

#include <iostream>
using namespace std;

class Rectangle {
    int length;     // Private by default
    int breadth;    // Private by default


    int area() {
        return length * breadth;
    }
};

int main() {
    Rectangle rect;

    cout << "Area (using class): " << rect.area() << endl;
    return 0;
}

Output:

ERROR!
/tmp/1ZiwDa1cAK.cpp: In function 'int main()':
/tmp/1ZiwDa1cAK.cpp:17:48: error: 'int Rectangle::area()' is private within this context
   17 |     cout << "Area (using class): " << rect.area() << endl;
      |                                       ~~~~~~~~~^~
/tmp/1ZiwDa1cAK.cpp:9:9: note: declared private here
    9 |     int area() {
      |         ^~~~

Correct Code for class:

#include <iostream>
using namespace std;
 
class Rectangle {
    int length;     // Private by default
    int breadth;    // Private by default
 
public:
    void setDimensions(int l, int b) {
        length = l;
        breadth = b;
    }
 
    int area() {
        return length * breadth;
    }
};
 
int main() {
    Rectangle rect;
    rect.setDimensions(10, 5);  // Use a public method to set dimensions
 
    cout << "Area (using class): " << rect.area() << endl;
    return 0;
}

Output:

Area (using class): 50

    Leave a Reply

    Your email address will not be published.

    Need Help?