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?
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.
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.
Pointers are just like any other variable: if you don't explicitly set them to a value, the value will be undefined (essentially random).
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.
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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With