C++ { } class initialization tip

Discussion in 'General Programming Support' started by tom_mai78101, Jul 29, 2016.

  1. tom_mai78101

    tom_mai78101 The Helper Connoisseur / Ex-MineCraft Host Staff Member

    Ratings:
    +984 / 4 / -1
    Code:
    #include <iostream>
    #include <cstdlib>
    
    class A {
    protected:
        int a0;
    
    public:
        void a(){
            std::cout << a0 << std::endl;
        }
    };
    
    int main(){
        A a = {};
        a.a();            //If a0 is not initialized, { } will set the uninitialized a0 to its default value, 0.
                        //If a0 is initialized, { } will do nothing about it.
    
        A b;            //If a0 is not initialized, simply constructing the class object will set a0 to garbage value, such as:
                        //0xFFFF FFFF CCCC CCCC or -858,993,460.
                        //This value means undefined unsigned long integer value, or uninitialized memory data.
                        //If a0 is initialized, then after the class object is constructed, the class member, a0,
                        //will have that initialized value set as its default.
        b.a();
    
        system("pause");
        return 0;
    }
    
    
     
  2. jonas

    jonas Well-Known Member

    Ratings:
    +42 / 4 / -0
    Much more interesting are Rvalue references and the corresponding std::move
     
  3. jonas

    jonas Well-Known Member

    Ratings:
    +42 / 4 / -0
    Btw, I'm pretty sure that your comment "A b; //If a0 is not initialized, simply constructing the class object will set a0 to garbage value" is incorrect. I think accessing b's a0 is simply undefined behavior. Your comment seems to imply that there is a non-deterministic but well-defined choice for the value, which is really not the case. In practice you may see such a non-deterministic choice because compilers are lazy and generate the "expected" code, but at the point that you take the value of b.a0 in the call of b.a() your compiler could just as well download a virus or simply crash your application (if they had a flag for each variable "initialized" and checked it before accessing the variable).
     
  4. tom_mai78101

    tom_mai78101 The Helper Connoisseur / Ex-MineCraft Host Staff Member

    Ratings:
    +984 / 4 / -1
    I wasn't really sure about that, since it generates the same output for GCC and MSVC++. But I am not well-versed in the grittier details underneath it, so I really don't know.
     

Share This Page