Pointer Member Variable Initialization in C++ Classes

后端 未结 4 1988
梦谈多话
梦谈多话 2020-12-17 09:34

This is going to sound so basic as to make one think I made zero effort to find the answer myself, but I swear I did search for about 20 minutes and found no answer.

相关标签:
4条回答
  • 2020-12-17 10:18

    Value will be undefined.

    You may have one "ultimate" ctor which will initialize all fields and add "short-cut" ctors with only part of parameters, which will pass these params to ultimate ctor along with default values for the rest of params.

    0 讨论(0)
  • 2020-12-17 10:22

    You're thinking correctly. If you don't initialise it, it could be anything.

    So the answer to your question is yet, either initialise it with something, or give it a NULL (or nullptr, in the most recent C++ standard).

    class A
    {
    };
    
    
    class B
    {
    private:
        A* a_;
    
    public:
        B() : a_(NULL) { };
        B(a* a) : a_(a) { };
    };
    

    Our default ctor here makes it NULL (replace with nullptr if needed), the second constructor will initialise it with the value passed (which isn't guaranteed to be good either!).

    0 讨论(0)
  • 2020-12-17 10:25

    The value will be uninitialised so yes you do need to explicitly initialise it to nullptr.

    Using smart pointers (std::unique_ptr, std::shared_ptr, boost::shared_ptr, etc.) would mean that you don't need to do this explicitly.

    0 讨论(0)
  • 2020-12-17 10:29

    the value of any uninitialized pointer is always garbage, it's some random memory address.

    in your constructors, you can use initializer lists to initialize your pointer

    simply

    MyClass::MyClass() : myPointer(nullptr)
    {
    }
    

    trying to reference an uninitialized pointer triggers undefined behavior. so ALWAYS initialize your pointer.

    0 讨论(0)
提交回复
热议问题