What is the difference between struct and class in C++? When to use which?
Hello, colleagues!\n\nI've just started learning C++ and I can't understand the difference between struct and class. At first glance they look almost the same — both allow combining data and methods. But why does the language have two keywords for the same thing?\n\nI read that in C (where struct comes from) structures only store data, while in C++ methods were added to them. But here's an example:\n\n```cpp\nstruct Point {\n int x, y;\n void print() { cout << x << ", " << y; }\n};\n\nclass Circle {\n int radius;\n void draw() { /* ... */ }\n};\n```\n\nIf I try to do this:\n\n```cpp\nPoint p;\np.x = 10; // Works\nCircle c;\nc.radius = 5; // Error! radius — private\n```\n\nWhy did radius suddenly become private? I didn't specify anything like that! In struct everything is the opposite — fields are public by default
No answers yet.
Log in to leave an answer
Blogs