C++ Compiler behavior regerding struct constructors

From: Karl M (Karl.M_at_email.com)
Date: 12/19/04


Date: Sun, 19 Dec 2004 08:09:55 -0500

Hi everyone,
I just notice some strange behaviors on the MS C++ compiler regarding struct
default constructor, see the example bellow:
struct MyStruct
{
    int a[5];
};
class MyClass
{
public:
    MyClass();
    ~MyClass();
protected:
    MyStruct m_MyStruct;
};
//#1:
MyClass::MyClass() //The default ctor for the class does not init the struct
with NULL(maybe there is no default ctor for struct yet?)
{
}
//#2 if I define the class ctor like this:
MyClass::MyClass() : m_MyStruct() //The default ctor for the class does init
the struct with NULL(call m_MyStruct() default ctor, now there is one!)
{
}
//#3 or like this:
MyClass::MyClass()
{
    m_MyStruct = MyStruct(); // dose init the struct with NULL using a local
stack var init with NULL
}
//Now if I define the struct like this:
struct MyStruct
{
    MyStruct()
    {
        int i;
        for(i=0;i<5;i++)
            a[i] = NULL;
    }
    int a[5];
};
//#1 will init the struct with NULL because uses the defined struct ctor but
generate almost the same bin (asm) code as case #2 and #3 (the init stack
var) without the struct ctor defined!
I guess I don't understand when the compiler knows about the struct default
constructor and when dose not (and expect for one defined).

Thank you
Karl M



Relevant Pages

  • Re: C++ Compiler behavior regerding struct constructors
    ... C++ guarantees zero initialization for static variables of primitive type, ... MyStruct m_MyStruct = MyStruct; ... > struct MyStruct ... > MyClass::MyClass//The default ctor for the class does not init the ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Self Assignment check in Copy ctor
    ... > AlgoMan wrote: ... >> Do you need to provide a self assignment check in a copy ctor ...
    (comp.lang.cpp)
  • Calling a struct constructor in a class constructor body
    ... I need to call the struct ctor in the class default ctor body see below: ... struct MyStruct ...
    (microsoft.public.dotnet.languages.vc)
  • Re: defined in constructor
    ... "JSmith" wrote in message ... >> So this line only appears inside the ctor and the implementation of the ... >> is only in the cpp file? ... it should be global and please know that the struct is not defind ...
    (microsoft.public.vc.language)
  • Struggling with bsearch - on a struct!
    ... I have a struct with a string and a long member. ... item with nKey: 7. ... int compare(const void *val1, const void *val2); ... struct mystruct* sp1 = val1; ...
    (comp.lang.c)