Constructor(?) inside a struct

G

Grumble

Hello all,

I came across the following definition (or is it declaration? I
never know):

struct OFFSET_AND_SIZE
{
INT64 offset;
UINT64 size;
OFFSET_AND_SIZE (INT64 o, UINT64 s) : offset (o), size (s) {}
};

(INT64 are UINT64 are not relevant to the discussion.)

I know some C, but very little C++ so I was somewhat puzzled. Is the
function inside the struct a constructor which will assign o to
offset and s to size?

So, I would write struct OFFSET_AND_SIZE toto(666, 999); and toto's
fields would be initialized as I expect, right?

What if I write struct OFFSET_AND_SIZE toto; would the compiler
complain, or would the fields remain undefined, as in C?
 
R

Ron Natalie

Grumble said:
Hello all,

I came across the following definition (or is it declaration? I
never know):

It's a definition.
I know some C, but very little C++ so I was somewhat puzzled. Is the
function inside the struct a constructor

It is a constructor. structs are the classes in C++, they can have constructors.
The only difference is the access control is public by default in struct.
which will assign o to offset and s to size?

More correctly, it will initialize o and s with those values.
So, I would write struct OFFSET_AND_SIZE toto(666, 999); and toto's
fields would be initialized as I expect, right?
Yes.

What if I write struct OFFSET_AND_SIZE toto; would the compiler
complain, or would the fields remain undefined, as in C?

It will complain. Once you declare ANY constructor, the implicit
default constructor is gone. Your class has no default constructor
so you can't initalize
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top