Can a struct
have a constructor in C++?
I have been trying to solve this problem but I am not getting the syntax.
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
}
};
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.
As the other answers mention, a struct is basically treated as a class in C++. This allows you to have a constructor which can be used to initialise the struct with default values. Below, the constructor takes sz
and b
as arguments, and initializes the other variables to some default values.
struct blocknode
{
unsigned int bsize;
bool free;
unsigned char *bptr;
blocknode *next;
blocknode *prev;
blocknode(unsigned int sz, unsigned char *b, bool f = true,
blocknode *p = 0, blocknode *n = 0) :
bsize(sz), free(f), bptr(b), prev(p), next(n) {}
};
Usage:
unsigned char *bptr = new unsigned char[1024];
blocknode *fblock = new blocknode(1024, btpr);
In C++ both struct
& class
are equal except struct's
default member access specifier is public
& class has private
.
The reason for having struct
in C++ is C++ is a superset of C and must have backward compatible with legacy C types
.
For example if the language user tries to include some C header file legacy-c.h
in his C++ code & it contains struct Test {int x,y};
. Members of struct Test
should be accessible as like C.