When to use Struct and when to make a class?

Hello Forum,

I just finished the video on structs and in it I noticed that Ben says that a struct is like a class. The largest problem I have with implementing code on my own or learning math is that I never seem to know when to use what tools. :unamused:

So Ben says that structs are public by default but I still don’t understand. Why would I use a struct when I could make a new class (CPP file) instead? Is the answer just that structs contain only a few lines?

If anyone could make this clearer to me I think it will really help me when it comes time to write my own code.

Thank you.

1 Like

They are pretty much a stylistic choice. People tend to use them when they want to create a simple data type, and don’t care to much about encapsulating it.

struct Point
    int x;
    int y;
    int x;

int main()
    Point p;
    p.x = 1;
    p.y = 2;
    p.z = 3;
    return 0;

Though you could technically achieve exactly the same thing with a class just by putting that under public:. Which is why I said it’s more of a stylistic choice.


Can’t seem to edit previous post but obviously the struct should have x, y and z. Not two x’s.

1 Like

Privacy & Terms