12.5 — Constructors

When all members of a class (or struct) are public, we can use aggregate initialization to initialize the class (or struct) directly using list-initialization:

However, as soon as we make any member variables private, we’re no longer able to initialize classes in this way. It does make sense: if you can’t directly access a variable (because it’s private), you shouldn’t be able to directly initialize it.

So then how do we initialize a class with private member variables? The answer is through constructors.


A constructor is a special kind of class member function that is automatically called when an object of that class is instantiated. Constructors are typically used to initialize member variables of the class to appropriate default or user-provided values, or to do any setup steps necessary for the class to be used (e.g. open a file or database).

Unlike normal member functions, constructors have specific rules for how they must be named:

  1. Constructors must have the same name as the class (with the same capitalization)
  2. Constructors have no return type (not even void)

Default constructors

A constructor that takes no parameters (or has parameters that all have default values) is called a default constructor. The default constructor is called if no user-provided initialization values are provided.

Here is an example of a class that has a default constructor:

This class was designed to hold a fractional value as an integer numerator and denominator. We have defined a default constructor named Fraction (the same as the class).

Because we’re instantiating an object of type Fraction with no arguments, the default constructor will be called immediately after memory is allocated for the object, and our object will be initialized.

This program produces the result:


Note that our numerator and denominator were initialized with the values we set in our default constructor! Without a default constructor, the numerator and denominator would have garbage values until we explicitly assigned them reasonable values, or initialize them by other means (remember: fundamental variables aren’t initialized by default).

Also note we do this:

instead of this:

Because class type objects will initialize themselves via a default constructor when no initializer is provided, the empty braces are redundant in such cases and only serve to obscure readability.

Best practice

You do not need to value initialize (use empty braces) when defining a class object with no initializer. All members should have their own initializers, and even if they don’t, the default constructor for the class should initialize them.

Direct and uniform initialization using constructors with parameters

While the default constructor is great for ensuring our classes are initialized with reasonable default values, often times we want instances of our class to have specific values that we provide. Fortunately, constructors can also be declared with parameters. Here is an example of a constructor that takes two integer parameters that are used to initialize the numerator and denominator:

Note that we now have two constructors: a default constructor that will be called in the default case, and a second constructor that takes two parameters. These two constructors can coexist peacefully in the same class due to function overloading. In fact, you can define as many constructors as you want, so long as each has a unique signature (number and type of parameters).

So how do we use this constructor with parameters? It’s simple! We can use list or direct initialization:

As always, we prefer list initialization. We’ll discover reasons (Templates and std::initializer_list) to use direct initialization when calling constructors later in the tutorials. There is another special constructor that might make brace initialization do something different, in that case we have to use direct initialization. We’ll talk about these constructors later.

Note that we have given the second parameter of the constructor with parameters a default value, so the following is also legal:

Default values for constructors work exactly the same way as with any other functions, so in the above case where we call six{ 6 }, the Fraction(int, int) function is called with the second parameter defaulted to value 1.

Best practice

Favor brace initialization to initialize class objects.

Copy initialization using equals with classes

Much like with fundamental variables, it’s also possible to initialize classes using copy initialization:

However, we recommend you avoid this form of initialization with classes, as it may be less efficient. Although direct initialization, uniform initialization, and copy initialization all work identically with fundamental types, copy-initialization does not work the same with classes (though the end-result is often the same). We’ll explore the differences in more detail in a future chapter.

Reducing your constructors

In the above two-constructor declaration of the Fraction class, the default constructor is actually somewhat redundant. We could simplify this class as follows:

Although this constructor is still a default constructor, it has now been defined in a way that it can accept one or two user-provided values as well.

When implementing your constructors, consider how you might keep the number of constructors down through smart defaulting of values.

A reminder about default parameters

The rules around defining and calling functions that have default parameters (described in lesson 8.12 -- Default arguments) apply to constructors too. To recap, when defining a function with default parameters, all default parameters must follow any non-default parameters, ie. there cannot be non-defaulted parameters after a defaulted parameter.

This may produce unexpected results for classes that have multiple default parameters of different types. Consider:

With s4, we’ve attempted to construct a Something by providing only a double. This won’t compile, as the rules for how arguments match with default parameters won’t allow us to skip a non-rightmost parameter (in this case, the leftmost int parameter).

If we want to be able to construct a Something with only a double, we’ll need to add a second (non-default) constructor:

An implicitly generated default constructor

If your class has no constructors, C++ will automatically generate a public default constructor for you. This is sometimes called an implicit constructor (or implicitly generated constructor).

Consider the following class:

This class has no constructor. Therefore, the compiler will generate a constructor that allows us to create a Date object without arguments.

This particular implicit constructor allows us to create a Date object with no arguments, but doesn’t initialize any of the members unless we create the Date object with direct- or list-initialization (because all of the members are fundamental types, and those don’t get initialized upon creation). If Date had members that are class-types themselves, for example std::string, the constructors of those members would be called automatically.

To make sure the member variables get initialized, we can initialize them at their declaration.

Although you can’t see the implicitly generated constructor, you can prove it exists:

The above code compiles, because the date object will use the implicit constructor (which is public).

If your class has any other constructors, the implicitly generated constructor will not be provided. For example:

To allow construction of a Date without arguments, either add default arguments to the constructor, add an empty default constructor, or explicitly add a default constructor:

Using = default is almost the same as adding a default constructor with an empty body. The only difference is that = default allows us to safely initialize member variables even if they don’t have an initializer:

Using = default is longer than writing a constructor with an empty body, but expresses better what your intentions are (To create a default constructor), and it’s safer. = default also works for other special constructors, which we’ll talk about in the future.

Best practice

If you have constructors in your class and need a default constructor that does nothing, use = default.

Classes containing classes

A class may contain other classes as member variables. By default, when the outer class is constructed, the member variables will have their default constructors called. This happens before the body of the constructor executes.

This can be demonstrated thusly:

This prints:


When variable b is constructed, the B() constructor is called. Before the body of the constructor executes, m_a is initialized, calling the class A default constructor. This prints “A”. Then control returns back to the B constructor, and the body of the B constructor executes.

This makes sense when you think about it, as the B() constructor may want to use variable m_a -- so m_a had better be initialized first!

The difference to the last example in the previous section is that m_a is a class-type. class-type members get initialized even if we don’t explicitly initialize them.

In the next lesson, we’ll talk about how to initialize these class member variables.

Constructor notes

Many new programmers are confused about whether constructors create the objects or not. They do not -- the compiler sets up the memory allocation for the object prior to the constructor call.

Constructors actually serve two purposes. First, constructors determine who is allowed to create an object. That is, an object of a class can only be created if a matching constructor can be found.

Second, constructors can be used to initialize objects. Whether the constructor actually does an initialization is up to the programmer. It’s syntactically valid to have a constructor that does no initialization at all (the constructor still serves the purpose of allowing the object to be created, as per the above).

However, much like it is a best practice to initialize all local variables, it’s also a best practice to initialize all member variables on creation of the object. This can be done either via a constructor, or via other means we’ll show in future lessons.

Best practice

Always initialize all member variables in your objects.

Finally, constructors are only intended to be used for initialization when the object is created. You should not try to call a constructor to re-initialize an existing object. While it may compile, the results will not be what you intended (instead, the compiler will create a temporary object and then discard it).

Quiz time

Question #1

Write a class named Ball. Ball should have two private member variables with default values: m_color (“black”) and m_radius (10.0). Ball should provide constructors to set only m_color, set only m_radius, set both, or set neither value. For this quiz question, do not use default parameters for your constructors. Also write a function to print out the color and radius of the ball.

The following sample program should compile:

and produce the result:

color: black, radius: 10
color: blue, radius: 10
color: black, radius: 20
color: blue, radius: 20

Show Solution

b) Update your answer to the previous question to use constructors with default parameters. Use as few constructors as possible.

Show Solution

Question #2

What happens if you don’t declare a default constructor?

Show Solution

12.6 -- Constructor member initializer lists
12.4 -- Access functions and encapsulation

514 comments to 12.5 — Constructors

  • MidZ

    // Empty user-provided constructor
        Date2() {};
    Isn't that an unnecessary semicolon? It confused me a bit

  • Waldo Lemmer

    - Section "A reminder about default parameters":
      > ie. there cannot be a non-defaulted parameters after a defaulted parameter

      "a" shouldn't be there

    I think "Rule" should be "Best practice"

  • Szymon :)

    Wouldn't it neater to initialize the variables in the same line they were declared instead of in every constructor?

  • EternalSkid

    Hi alex and nascardriver! I had something that i didn't quite understand, are you able to explain it to me?

    Why will it not compile? Will it not undergo numeric type conversion?

    • Alex

      Brace-initialization disallows narrowing conversions, so the compiler won't convert a double to an int implicitly in this case.

      You could use direct initialization instead, or do this:

  • Haldhar Patel

    1."the compiler sets up the memory allocation for the object prior to the constructor call."

    2."the constructor still serves the purpose of allowing the object to be created "

    According to the above two statements I don't understand one thing:
    >if the compiler sets the memory allocation prior to the constructor call then how constructor serves the purpose of allowing the object is created(is creation of object is different than allocation of memory for the object?

    Example :

    >According to the above facts when the compiler sees this statement it will allocate memory for the object and then constructor call will happen(statement 1) ,
    >but if no default constructor is found then what will happen?, the constructor will not allow the object to be created(statement 2 from above) , but the compiler allocated memory already , what will compiler do then -- frees the memory again or just keep it ?

    >> I think I have not understood the above statements , is it like when the statement "ClassType object;" is executed the constructors are first checked , and if no constructors are found based on the statement , the constructor will not allow the compiler to allocate memory and if a constructor is found, memory is allocated by the constructor and then constructor call happens to initialize the member , is this the case?

    • Alex

      At compile time, the compiler checks to make sure there is a valid constructor -- if not, the program won't compile.
      At runtime, memory has been set aside for the object prior to construction. Then the constructor is actually called.

  • vitrums

    In the beginning of this chapter you wrote:

    These namings really made me scratch my head. Isn't it inconsistent with chapter "1.4 — Variable assignment and initialization", where you said I quote:

    "To provide a more consistent initialization mechanism, there’s list initialization (also sometimes called uniform initialization or brace initialization) that uses curly braces."

    Also you provided this code snippet:

    "List initialization comes in two forms:"

    What I made out of it so far, is that for uniform initialization you would imply "direct list initialization". Also it seems like the order of the words is not random. I.e. you say "initialization list" as in Foo foo1 = { 4, 5 } vs "list initialization", when it can be both direct or copy list initializations.

    I need some clarifications here. Thank you!

    • nascardriver

      C++ is liberal in its use of "list" and "initialization", see my comment here

      I've adjusted the first example to only show "list-initialization", since that's the official term.

  • spaceman

    In the following code, member int variable x gets initialized to 0 even though it is not explicitly initialized at declaration nor at the default constructor. If I change the vector member to be another variable (such as int for example) x doesn't get initialized, as expected. It appears that the vector member somehow initialize the x variable, do you know if this has an explanation? THANKS!

    • nascardriver

      `x` is uninitialized, accessing it invokes undefined behavior. The other member variables of `Buffer` have no effect on `x`.

      clang-tidy warns

      You're not explicitly initializing `buffer` or `x`, so they get default-initialized. Default-initialization of a class-type, such as `std::vector`, invokes that type's default constructor, hence `buffer` is initialized. Default-initialization of a fundamental type, such as `int`, initializes the variable to an indeterminate value, ie. it is uninitialized.

  • XiangShuang

    The first can compile, but the second and the third can not, for uninitaialized local variable used. I can not understand.

    • nascardriver

      TL;DR: They're all uninitilized and invoke undefined behavior. Initialize everything unless you know what you're doing.

      I'm calling your classes `Person1, Person2, Person3` from top to bottom for reference. They all follow the same rules currently.

      This is default-initialization(1), because default-initialization is used "when a variable with automatic, static, or thread-local storage duration is declared with no initializer"(1)

      # `Person1`

      `Person1` is a class type and has a constructor, the constructor gets called. This again causes default-initialization(1) of the member variables, because default-initialization also happens "when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called."(1).

      `Person1::age` is neither a class-type nor an array, so "nothing is done". `Person1::age` is uninitialized when used in line 22, invoking undefined behavior. clang-tidy warns

      # `Person2`

      Same as `Person1`

      # `Person3`

      Same as `Person1`, because "no user-declared constructors of any kind are provided for a class type"(2) and "If the implicitly-declared default constructor is not defined as deleted, it is defined [...] and it has the same effect as a user-defined constructor with empty body and empty initializer list"(3)

      Simply initialize all variables (`age` and `p`) and this won't happen.
      `Person1` and `Person2` would use value-initialization(4) to initialize `age` to 0, because that happens "when a non-static data member or a base class is initialized using a member initializer with an empty pair of parentheses or braces (since C++11);"
      `Person3` is an aggregate (All members are public and there is no constructor), `Person3 p{}` would perform `value-initialization` of `Person3::age`, because "If the [...] initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers [...]"(5)

      Initialization in C++ is hard, don't worry about not understanding it and expect me to have made a mistake. If you initialize everything, you won't have problems. When you start to understand initializations, you can start to omit initializers for performance benefits.


  • kio

    Hi Alex and Nascardriver,

    Please update the solution with direct initialization :)

    • Alex

      This isn't an initialization, it's an assignment (and thus must use operator=).

      We cover member initialization lists in the next lesson, which allows us to initialize these variables rather than assign values to them.

  • chai

    Hi there. For clarity. Are brace , uniform and list initialization one and the same?

  • Aphamino


    In question #1 I was getting the error message [no instance of constructor "Ball::Ball" matches the argument list]. I eventually ended copying the given solution letter by letter and still it didn't compile until I noticed that I hadn't declared the string parameter "const" in one of the "Ball" constructors:

    Specifically the line

    wouldn't compile in main until I added the "const" keyword in front of the constructor parameter. I can't understand what was the problem. Can someone clarify this for me?

    P.S. I couldn't get the code tags to work after several editing attempts. :(

    P.P.S. I reread the chapter 10.3. (Passing arguments by reference) and there it said as a rule (in a green box) that

    "When passing an argument by reference, always use a const reference unless you need to change the value of the argument."

    The way how understand this is that it's optional to use the const keyword and it's preferred to do so if we don't want the function to change the referenced value. On the other hand I can leave the const-keyword off if I wanted to, but then my code didn't compile, so I'm guessing there's something else going on(?).

    • nascardriver

      References cannot bind to r-values.

      This creates a temporary (r-value) `std::string` as the `color` argument.

      It wouldn't make sense to be able to call the constructor in this way if `color` is non-const, because the modifications that the constructor does to `color` wouldn't be visible to the caller.

    • digiCrab

      I believe the reason why you cannot do that is because the argument "blue" you feed into the constructor is literals. Literals -- as mentioned in "1.9 — Introduction to literals and operators", are all const values.

      You cannot feed a variable `const std::string` to non-const function argument `std::string`.

  • kio

    Hi Alex and Nascardriver,

    In the following example is it necessary to write

    m_radius, because it's already defined in the default constructor?
    Is this best practice or you have included it due to a better understanding of the chapter?

    • nascardriver


      The default constructor doesn't get called if this constructor gets called. The default constructor only gets called when a `Ball` is created without arguments.

  • J34NP3T3R

    in the first example how does it work ?
    does it automatically create a default constructor ?

    how does it know which value goes to which variable when we initialize with ?

  • J34NP3T3R

    how come the compiler accepts this function with or without a semi colon ; ?


  • Oran

    Would it be better to use std::string_view instead of std::string in quiz #1?

  • Love these exercises! So enjoyable :)

  • Aqib

    (Question 1 part b)Is it also a correct way to do it using r-value reference or i am wrong even though my program is running fine ?

  • Aqib

Leave a Comment

Put all code inside code tags: [code]your code here[/code]