On classes and structs
Oct. 12th, 2011 11:32 pmWhen you create a class in C++, it will execute a constructor which allows you to automatically initialize all of the members to a known set of values. This is a good thing, because otherwise you will get whatever random garbage is sitting at the spot in memory. If other classes are members of the class that is being constructed, they will automatically call their default constructors so that they are properly initialized.
If you create a struct in C++, you must initialize it by hand. If the struct contains classes, their constructors will not be called automatically, so they will be filled with random garbage.
It is important to know this and apply this knowledge lest your application crash in interesting fashion.
Happily, I already knew this.
Update: And you can have a constructor for your struct in C++, so if you bother to write the constructor, you can do the initialization trivially, because then the default constructor for your classes will be called. I learn something new every day. :)
You still need to actually write the constructor though...
If you create a struct in C++, you must initialize it by hand. If the struct contains classes, their constructors will not be called automatically, so they will be filled with random garbage.
It is important to know this and apply this knowledge lest your application crash in interesting fashion.
Happily, I already knew this.
Update: And you can have a constructor for your struct in C++, so if you bother to write the constructor, you can do the initialization trivially, because then the default constructor for your classes will be called. I learn something new every day. :)
You still need to actually write the constructor though...
no subject
Date: 2011-10-13 04:07 pm (UTC)Even if it were officially documented to work properly, it feels wrong to me to have a class as a member of a struct.
no subject
Date: 2011-10-14 12:20 am (UTC)class foo
{
public:
foo() { x = 5; } // default ctor
int x; // a member variable
}
struct bar
{
foo m1;
}
class baz
{
public:
foo m2;
}
bar a; // a struct bar containing a foo
baz b; // an object of class baz containing a foo
So b.m1.x is initialized to 5 when object b is constructed
but a.m1.x is NOT initialized when struct a is constructed?
That's strange. I'd always believed that structs and classes were the
same thing, except that all struct members were public by default. Apparently there's more to it than that.
no subject
Date: 2011-10-14 03:37 am (UTC)All this is based on the implementation in Visual Studio 2010.