Can a struct have a constructor in C++?
Hello! I just started learning C++ and encountered some confusion. In C language, I'm used to struct being just a set of data, and it cannot have any methods. But in C++, I see that struct seems similar to a class, but with public members by default.
My question: can a struct have a constructor? If yes, how does it work? I tried writing this code:
```cpp
#include
using namespace std;
struct Point {
int x;
int y;
// Attempt to add a constructor
Point(int a, int b) {
x = a;
y = b;
}
};
int main() {
Point p1(10, 20); // Error? Or does it work?
cout << p1.x << " " << p1.y;
return 0;
}
```
But I'm not sure if this is correct. The compiler doesn't seem to complain, but some books say that struct
No answers yet.
Log in to leave an answer
Blogs
How to Get a Job as a JavaScript Developer: Tips and Resume
HashMap vs Hashtable in Java: Differences and Internal Structure
Java from Zero to PRO: TOP YouTube Channels and Courses 2024
Code review in Kotlin: what to check and how to give feedback