Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default constructor does not initialize pointer to nullptr?

Tags:

c++

I wonder if I have a A* member in my class, shouldn't it we set to nullptr automatically if I have a constructor of my class in this form:

class MyCLass
{
    A* m_pointer;

public:
    MyCLass()
    {
    }
};

Does it matter if I do MyCLass* o = new MyCLass; or I do MyCLass* o = new MyCLass(); in C++11?

like image 215
Narek Avatar asked Oct 01 '14 13:10

Narek


People also ask

Are pointers initialized to nullptr?

A pointer can also be initialized to null using any integer constant expression that evaluates to 0, for example char *a=0; . Such a pointer is a null pointer. It does not point to any object.

What is the default value if you do not initialize a pointer?

static variables are initialized to 0, which does the right thing for pointers too (i.e., sets them to NULL, not all bits 0). This behavior is guaranteed by the standard.

What happens if you don't initialize a pointer C?

Pointers are just like any other variable: if you don't explicitly set them to a value, the value will be undefined (essentially random).

Does pointer need to be initialized?

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.


2 Answers

Pointers are "POD types"...a.k.a. "Plain Old Data". The rules for when and where they are default-initialized are summarized here:

Default initialization of POD types in C++

So no. It doesn't matter what your constructor for a class is, if it's a raw pointer as a member of the class. You aren't actually instantiating the class. So members like Foo * or std::vector<Foo> * or anything ending in * will not be initialized to nullptr.

The smart pointer classes are not POD. So if you use a unique_ptr<Foo> or a shared_ptr<Foo> that is creating instances of classes, that do have a constructor that makes them effectively null if you do not initialize them.

Does it matter if I do MyCLass* o = new MyCLass; or I do MyCLass* o = new MyCLass(); in C++11?

One question per question, please.

Do the parentheses after the type name make a difference with new?

like image 125
HostileFork says dont trust SE Avatar answered Oct 09 '22 09:10

HostileFork says dont trust SE


The default constructor, if compiler-generated or defaulted, will default-initialize all members. Any user-defined constructor will similarly default-initialize all members that don't have an explicit initializer in the initializer-list.

To default-initialize means "call the default constructor for classes, leave everything else uninitialized".

like image 29
Sebastian Redl Avatar answered Oct 09 '22 07:10

Sebastian Redl