Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Member Variable Initialization in C++ Classes

Tags:

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.

like image 743
John Fitzpatrick Avatar asked Dec 06 '11 21:12

John Fitzpatrick


People also ask

How do you initialize a pointer to a class?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator ( & ). The address-of operator ( & ) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number .

How do you initialize a member variable?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.

Do pointers need to be initialized in C?

You need to initialize a pointer by assigning it a valid address. Most of the compilers does not signal an error or a warning for uninitialized pointer?! You can initialize a pointer to 0 or NULL, i.e., it points to nothing.


1 Answers

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

like image 100
Moo-Juice Avatar answered Oct 07 '22 06:10

Moo-Juice