Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are default constructors called automatically for member variables?

Say I have this class:

//Awesome.h
class Awesome
{
    public:
        Awesome();
    private:
        membertype member;
}

//Awesome.cpp
#include "Awesome.h"

Awesome::Awesome()
:member()
{
}

If I omit the member() in the initialization list of the constructor of Awesome, will the constructor of member be called automatically? And is it only called when I don't include member in the initialization list?

like image 397
Lanaru Avatar asked Aug 16 '12 18:08

Lanaru


People also ask

Is default constructor called automatically?

Is a default constructor automatically provided? If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.

Are constructors called automatically?

A constructor in C++ is a special method that is automatically called when an object of a class is created.

Is the default constructor automatically called C++?

A constructor is automatically called when an object is created. It must be placed in public section of class. If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body).

How default constructor is called?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


1 Answers

Yes. When a variable is not given in the initalizer list, then it is default constructed automatically.

Default contruction means, that if membertype is a class or struct, then it will be default contructed, if it's a built-in array, then each element will be default constructed and if it's a build-in type, then no initialization will be performed (unless the Awesome object has static or thread-local storage duration). The last case means that the member variable can (and often will) contain unpredictable garbage in case the Awesome object is created on the stack or allocated on the heap.

like image 68
Ralph Tandetzky Avatar answered Sep 22 '22 05:09

Ralph Tandetzky