Can a struct have a constructor in C++?
I have been trying to solve this problem but not getting any syntax.
Can a struct have a constructor in C++?
I have been trying to solve this problem but not getting any syntax.
In C++ the only difference between a class and a struct is that class-members are private by default, while struct-members default to public. So structures can have constructors, and the syntax is the same as for classes.
Yes. A structure is just like a class, but defaults to public:
, in the class definition and when inheriting:
struct Foo
{
int bar;
Foo(void) :
bar(0)
{
}
}
Considering your other question, I would suggest you read through some tutorials. They will answer your questions faster and more complete than we will.
Yes structures and classes in C++ are the same except that structures members are public by default whereas classes members are private by default. Anything you can do in a class you should be able to do in a structure.
struct Foo
{
Foo()
{
// Initialize Foo
}
};
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.
In C++, we can declare/define the structure just like class and have the constructors/destructors for the Structures and have variables/functions defined in it. The only difference is the default scope of the variables/functions defined. Other than the above difference, mostly you should be able to imitate the functionality of class using structs.
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
I'd rather initialize inside the constructor so I don't need to keep the order.