C++ Structs vs Classes

‮/:sptth‬/www.theitroad.com

In C++, both structs and classes are used to define user-defined data types. While structs and classes are very similar in their functionality, there are a few differences between the two.

The main difference between structs and classes is the default access level. In a struct, all members are public by default, whereas in a class, all members are private by default. This means that you can access the members of a struct from outside the struct without using any access specifiers, but you cannot do the same for a class.

Here's an example of a struct:

struct MyStruct {
  int x;
  int y;
  void print() {
    std::cout << "x = " << x << ", y = " << y << std::endl;
  }
};

int main() {
  MyStruct obj;
  obj.x = 42;
  obj.y = 3;
  obj.print();
  return 0;
}

In this example, we've defined a struct called MyStruct with two member variables x and y, and a member function print that outputs the values of the member variables to the console. We've also created an object of the MyStruct struct called obj, and initialized its member variables to 42 and 3. We then call the print member function to output the values of the member variables.

Here's an example of a class:

class MyClass {
  private:
    int x;
    int y;
  public:
    void setValues(int value1, int value2) {
      x = value1;
      y = value2;
    }
    void print() {
      std::cout << "x = " << x << ", y = " << y << std::endl;
    }
};

int main() {
  MyClass obj;
  obj.setValues(42, 3);
  obj.print();
  return 0;
}

In this example, we've defined a class called MyClass with two private member variables x and y, and two public member functions setValues and print. The setValues member function is used to set the values of the private member variables, and the print member function is used to output the values of the member variables to the console. We've also created an object of the MyClass class called obj, and initialized its member variables using the setValues member function. We then call the print member function to output the values of the member variables.

In general, the choice between using a struct or a class depends on the specific use case and the coding style preferences of the programmer. If the data type is simple and does not have any complicated member functions or access rules, then a struct may be more appropriate. However, if the data type is more complex and requires more control over access to its members, then a class may be more appropriate.