Re: Default ctor, etc generated by compiler for structs?
"Victor Bazarov" <v.Abazarov@comAcast.net> wrote in message
news:guqdnUgq2703oO7bnZ2dnUVZ_j2dnZ2d@comcast.com...
JohnQ wrote:
Are a default constructor, destructor, copy constructor and assignment
operator generated by the compiler for a struct if they are not
explicitely defined?
If by a struct you mean POD, then yes, but only conceptually.
Different from an identical class? Conceptually how?
If by a struct you mean any class where you only specify data
members, then it depends on the data members.
Lately, I've been pondering, "when does a struct stop being a struct?". To
me, that's when its not the same size as a C struct or not layed out the
same. So obviously, when a virtual function gets added, then "a struct stops
being a struct". I think I can add non-virtual member functions, non-virtual
destructor and operators ad infinitum and the "struct will still be a
struct" (right?). Even though some explicit syntax would make things more
evident:
struct A
{
int data;
};
struct B
{
int data;
B(int val){ data = val; } // OK, not virtual
};
class StructWrapper
{
A a_struct;
public:
A(int val){ a_struct.data = val; }
operator A&(){ return a_struct; }
};
Where struct B can be used identically to struct A or StructWrapper (I
hope!) as the layouts and sizes are the same (assume the operator is being
used for StructWrapper when I say "can be used identically").
sizeof(A)==sizeof(B)==sizeof(StructWrapper)
But a_struct in StructWrapper would have to be made public to guarantee the
same layout as A and B?
I think the answer is yes, because "there is no difference between a
struct and a class except the public/private access specification"
(and a few minor other things). When I create a class, I always start
by declaring the default constructor, copy constructor and assignment
operator private with no implementation. I don't do that for structs
though (I consider structs like they were in C, but they really are
not in the implementation as far as I know). I'm thinking that I
don't handle structs the same because I trust the compiler to do the
right thing in the case of structs whereas bitwise copy for a class
may not be what is desired, for example.
What's "bitwise copy"? I don't know of that concept in C++.
The equivalent of doing a memcpy of the class or struct (whether I used the
right terminology or not I don't know... "bytewise" seems more appropriate).
Is the above reasoning OK? Should I continue NOT declaring/defining
the default stuff for structs?
It's up to you. And the ability of the compiler to generate the
functions you don't declare/define depends on the data members.
OK, so from what I gather, the compiler may or may not generate the
functions/operators depending on the data members. Is it that if there is
any non-POD data member, then the functions/operators get generated? Is it
always the full set (?): default constructor, copy constructor, assignment
operator, (destructor?).
John