How are C++ Local and Global variables initialized by default?

The following is the same for both local and global variables. Basically, whenever you declare a variable, the compiler will call its default constructor unless you specify otherwise.

The language level types (e.g. pointers, 'int', 'float', 'bool', etc) "default constructor" does absolutely nothing, it just leaves the memory as it is when it is declared.  This means that they can be pretty much anything because you usually can't be sure what was in that memory previously or even where the memory came from.

If you create a class that doesn't have a constructor, the compiler will create one for you which simply calls the constructor of each of its members/variables. If you have a constructor with arguments, and no constructor without arguments, then compiler will throw an error that a matching constructor was not found.

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started