Can a struct
have a constructor in C++?
I have been trying to solve this problem but I am not getting the syntax.
Yes, but if you have your structure in a union then you cannot. It is the same as a class.
struct Example
{
unsigned int mTest;
Example()
{
}
};
Unions will not allow constructors in the structs. You can make a constructor on the union though. This question relates to non-trivial constructors in unions.
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
I'd rather initialize inside the constructor so I don't need to keep the order.
In c++ struct and c++ class have only one difference by default struct members are public and class members are private.
/*Here, C++ program constructor in struct*/
#include <iostream>
using namespace std;
struct hello
{
public: //by default also it is public
hello();
~hello();
};
hello::hello()
{
cout<<"calling constructor...!"<<endl;
}
hello::~hello()
{
cout<<"calling destructor...!"<<endl;
}
int main()
{
hello obj; //creating a hello obj, calling hello constructor and destructor
return 0;
}
In C++ the only difference between a class
and a struct
is that members and base classes are private by default in classes, whereas they are public by default in structs.
So structs can have constructors, and the syntax is the same as for classes.
One more example but using this keyword when setting value in constructor:
#include <iostream>
using namespace std;
struct Node {
int value;
Node(int value) {
this->value = value;
}
void print()
{
cout << this->value << endl;
}
};
int main() {
Node n = Node(10);
n.print();
return 0;
}
Compiled with GCC 8.1.0.
Class, Structure and Union is described in below table in short.