26

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.

If a private c++ class member variable (non-static) is a pointer, and it is NOT initialized in the constructor (either through an initialization list or an assignment in the constructor), what will its value be when the class is fully instantiated?

Bonus question: If the answer to the above question is anything other than NULL, and I wish to always initialize a particular member pointer variable to NULL, and I have multiple constructors, do I really have to put an explicit initialization for that pointer in every constructor I write? And if so, how do the pros handle this? Surely nobody actually puts redundant initializers for the same member in all their constructors, do they?

EDIT: I wish I could've chosen two answers here. The smart pointers recommended by Bleep Bloop seem to be the elegantest approach, and it got the most up votes. But since I didn't actually use smart pointers in my work (yet), I chose the most illustrative answer that didn't use smart pointers as the answer.

6 Answers 6

14

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!).

Sign up to request clarification or add additional context in comments.

5 Comments

Great, thanks, well illustrated. What if you had a third constructor that did not take an A* pointer as an argument. Would it need to explicitly initialize a_ to NULL? Or can it somehow "chain" off of the initializer list you wrote for the no-arg constructor?
It would also need to initialize it to NULL / nullptr. What I tend to do if I have a multiple constructors that need to do common initialisation, is to implement a private commonConstruct() method which does default initialization for me.
Is there NULL and 0 the same? Could it be B():a_(0){}; with an identical effect?
@arjacsoh, yes it expands to 0 or 0L. However, in C++11, you actually have a nullptr keyword. The biggest advantage of this is that you can now distinguish between a pointer that is null, and an integer that is 0 :)
Can you please give a link to the standard that confirms your claim?
8

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.

1 Comment

This is certainly the better long term solution, and I will eventually use smart pointers. But I need to learn a bit more about them before I start using them so I am going with Moo-Juice's recommendation.
1

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.

Comments

1

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.

Comments

1

Even if the most voted answer is technically correct, I would suggest better approach is to initialise variable in class itself.

class A
{
};


class B
{
private:
    A* a_ = nullptr;

public:
    B() : { };
    B(a* a) : a_(a) { };
};

Comments

0

In C++, you are allowed to initialize values to member variables using the initialization list syntax. See this:

class AnyClass
{
};
class Xyz
{
    int n;
    AnyClass *p;
    Xyz() : n(55), p(new AnyClass())
    {
        // constructor body
    }
    ~Xyz() { delete p; }
};

The value of n becomes 55 and the pointer to the newly created AnyClass is initialized into p. Note that they are not assigned to n and p. They are initialized into the member variables.

When using new, you should delete it using delete When using new[], you should use delete[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.