8.5 — Constructors

When all members of a class (or struct) are public, we can initialize the class (or struct) directly using an initialization list or uniform initialization (in C++11):

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 should always have the same name as the class (with the same capitalization)
  2. Constructors have no return type (not even void)

Note that constructors are only intended to be used for initialization. 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).

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! This is such a useful feature that almost every class includes a default constructor. Without a default constructor, the numerator and denominator would have garbage values until we explicitly assigned them reasonable values (remember: fundamental variables aren’t initialized by default).

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 just use the direct initialization form of initialization:

This particular fraction will be initialized to the fraction 5/3!

In C++11, we can also use uniform initialization:

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 function, 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.

Rule: Use direct or uniform initialization with your classes

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.

Rule: Do not copy initialize your classes

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.

Classes without default constructors

If your class has no other constructors, C++ will automatically create an empty default constructor for you. Because the empty default constructor does not initialize any of the class’s member variables, if you use it to allocate an object of your class, the member variables of the class will not be initialized (similar to what happens when you declare an int, double, or other basic data type).

For example:

In the above example, because we declared a Date object, but there is no default constructor, m_month, m_day, and m_year were never initialized. Consequently, they will hold garbage values.

However, if you do have other non-default constructors in your class, but no default constructor, C++ will not create an empty default constructor for you. In this case, the class will not be instantiatiable without parameters. For example:

Generally speaking, it’s a good idea to always provide at least one constructor in your class. This will prevent C++ from creating an empty default constructor, ensuring that users don’t instantiate objects of your class that have uninitialized members (unless you intend for that to happen).

Rule: Provide at least one constructor for your class, even if it’s an empty default constructor.

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!

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

Quiz time

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

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

Show Solution

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

Show Solution

8.5a -- Constructor member initializer lists
8.4 -- Access functions and encapsulation

185 comments to 8.5 — Constructors

  • Omri

    When a class say n_class is present with a constructor of which all its parameters x,y,z have defalt values it turns out that, as expected:
    n_class b(x);
    n_class d(x,y);
    n_clasd e(x,y,z);
    compile and b,d,e "behave".
    Following this pattern of argument elimination, it is tempting to create a default n_class object c as follows:
    n_class c();  
    This compiles but c does not "behave".
    Variable c is not recognized as an n_class object and an attempt to use it as such leads to an error.
    Thus a default n_class object is created (not strictly following the pattern of argument elimination) as follows:
    n_class c;
    Is this observation correct?
    On the other hand, creating a default anomynous object of type n_class and launching a member function, say print() using it is done as follows:
    Quite confusing…

    • Alex

      Yeah, it’s confusing. C++ tends to overload a lot of symbols for different purposes, and this means statements that look similar may have different interpretations by the compiler. The statements for instantiation of a class variable and forward declaration of a function end up looking really similar:

      In the above case, the compiler differentiates the two based on whether the argument is a type or a value. But then consider this:

      With no type or value, should the compiler interpret this as an instantiation of variable x or a forward declaration for function x?

      The way the C++ designers resolved this was as follows:

  • omri

    Hello Alex,
    Thank you for the reply.
    To me this means that Fraction(6) from above is indeed not an explicit call to Fraction(…) but rather a syntax to create an anonimous Fraction(…) object, use it in the statement, afterwhich it is perhaps immediately deleted by the system.
    Since Fraction(…) does not return anything (as it is a constructor), this makes sense to me.
    Did I get it right?
    If yes, perhaps this syntax should be mentioned in the article and it not being a function call (despite the similarity) pointed at. Just a thought…

    • Alex

      Yes, you have it right. I talk more about anonymous objects later in this chapter.

      I thought about mentioning the fact that it’s not a function call, but it’s more of an interesting bit of trivia than anything actually useful. 🙂

  • Omri

    Regarding from above:
    "B contains A as a member variable",
    is it not more accurate to say:
    "B contains a type A as a member variable"
    "B contains a class A as a member variable"?

  • Omri

    Hello Alex,
    Regarding from above:
    "Note that constructors are only used for initialization. They can not be explicitly called."
    As I understand you did explicitly call the constructor when you copy initialized above, and also, in examples given in a later blog you did call the constructor explicitly to create what I think is an anonimous object as you needed it. Please correct me.

    • Alex

      A few things here:
      * First, constructors actually can be called explicitly, but there’s rarely a case where you’d actually want to do so.
      * Second, when we do copy initialization, we’re not actually calling the constructor directly (even though it looks like it). We’re actually telling the compiler to create the object, and that has the biproduct of calling the constructor once the memory has been set up.

      I’ve updated the article to clarify what I was trying to get at: “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).”

  • Alexander Kindel

    What is the difference between setting default values for class members using a default constructor and setting default values when one declares the members? In other words, is there a difference between



    • Alex

      In the former case, those values will be assigned to all objects created using that specific Ball() default constructor.
      In the latter case, those values will be assigned to all objects created using any constructor, unless the specific constructor used to create the Ball overrides those defaults.

      In your specific case, because you only have one constructor, and it initializes the members to the same values in both cases, this is essentially identical (outside of the fact that the latter case does an initialization, and the former case does an assignment)

  • mandy

    for the Fraction class, how can you get the user to input mixed fraction as default? for example: instead of adding 1/2 + 2 1/2 they’ll have to input as 0 1/2 + 2 1/2
    I got my fraction class to work down to reduce result but I can’t get the mixed number input to work only straight fraction. Please advise.
    oh btw, thanks for creating this site. I use it instead of my cs school book:)

    • Alex

      I’ve read your comment three times and I’m still not sure what you’re asking. Can you clarify?

      If you’re asking how to enter a value like 2 1/2, you could do it as a constructor that takes three numbers: a whole value, a numerator, and a denominator. You can reduce the numerator and denominator and leave the whole value alone.

  • Cassey

    Hi i am a beginner and have problem to understand the default construct. I was given a simple question but i can’t solve it. Please help me

    Implement a default constructor for the following class:

    class Student
    int StuMatricNum;
    string StuName;
    double StuGPA;

    Student ( );
    viod DisplayCollegeProfile( );

    //i look through many tutorial but still confused with constructor.

  • Dekasi

    Hi, Alex. I want to ask you why you say that we need to provide at least one constructor even if it is empty default constructor. Is it different from the one that C++ will provide for us (if we don’t provide any)?

    I noticed that you use a reference string variable in the 1st solution of the quiz. Why you use it as a refernce instead of normal string variable?

    • Alex

      As the lesson says, if you don’t provide at least one constructor, the compiler will provide an empty default constructor for you. This is almost never desired, as it means your member variables may not be getting initialized properly.

      You should always pass class objects by (const) reference to avoid making an unnecessary copy.

  • Rohit

    In the topic classes within classes when b is constructed B() will b called which contains only printing statement, then how will it call class A constructor because m_a is not initialized in B() constructor?

    • Alex

      Member variables that are classes (e.g. m_a) that are not explicitly initialized are initialized using the default constructor. So m_a is initialized using the default constructor for class A.

      • Rohit

        My question is in this piece of code :
        B() { std::cout << "B\n"; }
        when b object is declared B() constructor will be called and only the printing statement which says "B" must print because B() constructor is not accessing the the m_a variable in its statements. According to me the output should be "B".
        Please clear my doubt if I am wrong somewhere

        • Alex

          When a class object (such as b) is created, all members of that class are also created. The constructor gives you the opportunity to initialize these members. For class members, if you do not explicitly initialize them, they will be initialized using the default constructor. That’s what’s happening here. The B() constructor is not initializing m_a. However, m_a still needs to be created as part of the B object. So it uses the A default constructor to do so.

  • Rafael Rossi

    What is the difference between:


    • Alex

      With the ampersand, color is a reference to the original std::string argument passed in. No copy is made.

      Without the ampersand, the argument passed in passed by value, causing the argument to be copied into parameter color. This means we can change color without changing the original argument, but at the cost of making a copy.

      In almost all cases, passing a class by const reference is better.

  • vaseem

    rather than any constructor

  • vaseem

    why default constructor has not any return type?

    • Alex

      Constructors are never called directly by the end user. They are called implicitly when an object is created, and the return value of object creation is the object itself.

      The language designers through it was clearer to omit any return type for constructors (and destructors) as a way to denote them as “special” functions.

  • Martin

    Thank you for these great tutorials! They are the best I know so far.

    Just wanted to let you know that there is a wrong indentation for the default constructor in quiz 1 and the comments.

  • simberdavid

    hey why won’t this work?

    • Alex

      It doesn’t work because it has a few problems:
      1) You spelled denominator wrong inside the constructor.
      2) You forgot to include the () for the function calls inside function main().

      Fix those and it will run, though it’s not a great idea to do input in a constructor (it’s better to do the input outside of the class, then pass the values to the constructor).

  • Luzaritz

    Hi Alex

    May I suggest you include in the lesson the way C++ handles defaulting parameters when calling a constructor? Without knowledge of the rule, new learners cannot really answer the 1b quiz. And what about

    in 1b, which would provide a (first) default constructor, according to "has parameters that all have default values". Here, what is legal, and could be reasonably added to the lesson?

    • Alex

      Default parameters for constructors are handled in the exact same way as default values for any function. I’ve added a note to the lesson since this was implied rather than stated.

      A class can only have one default constructor, so if you gave radius a default value as per your suggestion, the compiler would error on the second constructor since both constructors would be defined as default constructors.

  • Zachary Fojtasek

    for 1b, why can I not use just this?:

    • Alex

      Because std::string is a class, and you should pass classes by const reference instead of by value, so they aren’t copied.

      • Zachary Fojtasek

        What I mean is, the code won’t compile if I use that as my only Constructor.

        • Alex

          Yes, the way default parameters work is that you can only default the rightmost parameters, and when you supply your arguments, you can’t skip any of the leftmost arguments.

          In the case of Ball twenty(20.0), you’ve skipped providing an argument for the color.

          • Nurlan

            One more question about default parameters. Why we can’t use uniform initialization for default parameters in case it is used as constructor default parameters or as function default parameters?
            In either cases uniform initialization doesn’t work, the default parameter only accepts copy initialization even it is C++11 compatible.

            For  example:
            class Date
                int m_year;
                int m_month;
                int m_day;

            //int day=22 accepts,                                                                                                       
                Date(int year, int month, int day{22}) //not int day{22}
                    m_year = year;
                    m_month = month;
                    m_day = day;

                // No default constructor provided

            int main()
                   Date today(2020, 10, 14); // today is initialized to Oct 14th, 2020

                return 0;
            Thanks in advance!

            • Alex

              I’m actually not sure why default parameters are required to use the copy initialization syntax. I did a quick search and wasn’t able to dig up anything on the subject either. So for now, this remains a mystery. 🙂

      • Zachary Fojtasek

        UPDATE: I figured it out, it has to do with the rules for default parameters, but now I am confused about something else:

  • Sam

    Just tried something out:
    If create an implicit default constructor (by compiler) and create an instance like so:

    Then there’s a warning that the "thing" is unreferenced and its members contain garbage values.
    But if create an instance like so:

    Then the warning goes away and all members are initialized in type-dependent zero-state (like if you initialize any type with empty brackets of uniform initialization). The same result happens if you create an explicit default constructor like so:

    And in this case, it doesn’t matter how you create an instance (1st or 2nd variant I provided).
    A bit confusing!
    p.s. just run it in MVS 2015

    • Alex

      This only works if you don’t define _any_ constructors yourself (which is something you shouldn’t do), because then the class is treated like a plain-old-data struct, and can be initialized thusly. This violates encapsulation principles.

  • Zachary Fojtasek

    Can a class contain an object of the same class as a member variable? Or perhaps an array containing other objects of the same class?

  • Deepanshu

    Hi Alex,
    You wrote in this article, "Before the body of the constructor executes, m_a is initialized, calling the class A default constructor". I am unable to understand it. How the m_a will get initialized before the body of constructor B()? Please explain.

    • Alex

      When you instantiate a class, three things happen: First, the appropriate constructor for the class is called. Then, there’s an initialization stage, where all initializations happen. Then the body of the constructor executes.

      Now, consider what would happen if your code has this:

      In this case, because you’ve supplied no parameters to the constructor, variable a (of type A) will be initialized using the A class default constructor.

      Similarly, because we haven’t specified anything for the initialization portion of our constructor, member variable m_a (of type A) will use the A class default constructor to initialize.

      In the very next lesson, we’ll show you how to initialize your variables yourself rather than just relying on the default constructor.

      Make sense?

  • Gapo

    Hey Alex could you please explain this code from your quiz, I don’t quite understand it.

    • Alex

      This function is a constructor for class Ball, which means it can be called to construct an object of type Ball. It also makes use of default parameters, which will be used if you don’t pass in a corresponding argument.

      This function will handle instantiating a Ball object in 3 different ways:

      Because this constructor works with no parameters, it’s considered a default constructor.

      Note that this constructor will not allow you to only pass in a radius (and use the default color).

  • Hi Alex,

    Another question about the line

    I simplify the code just to have one constructor. I had information about the memory address when the m_color and MyColor object is created. The Address of both object are different. So m_color is, I think a copy of the MyColor object. According of what you explain on previous comments about the const, if the object was passed by reference, I think the address of both objects should be the same. My question is why the address of m_color and MyColor are different?

    MyColor is blue, MyColor addres = 0x7ffd2efcced0
    color: blue, radius: 10
    Class Ball m_color address = 0x7ffd2efccec0
    MyColor is red, MyColor addres = 0x7ffd2efcced0
    color: blue, radius: 10
    Class Ball m_color address = 0x7ffd2efccec0

    • Alex

      They have different addresses because MyColor and m_color are different variables. MyColor is a local variable living in function main(), and m_color is a separate variable that lives inside variable blue.

      • Hi Alex,

        I finally understand my mistake by reading again the comments of this thread and the section "7.3-Passing arguments by reference".

        By using

        the variable color is not copied to the constructor but it is used to copy the variable color to the variable m_color. This is why the address of both variable are different. Am I correct?

  • tawanda

    hie , thank you for this article. i am receiving an error:
    19    2 [Error] ‘Invoice::Invoice(std::string, std::string, int, int)’ is private

    96    71[Error] within this context

    here is my code

  • In the section "Classes without default constructors" above, you talk about how the implicitly defined default constructor for "Date" class would result in the member variables of "date" object holding garbage values. However, from some programming that I’ve been doing, it looks like if the member variables are actually Class objects themselves, then this implicitly defined default constructor does not assign them garbage values but calls their own default constructors. Is this observation technically correct and generally valid?

    • Alex

      Yes, if a member variable is a class, then the constructor for that member variable will be called as part of the construction of the outer class. I’ll update the lesson to make this clear.

  • Rahul

    Hey Alex,
    Why you use assert() in the example under heading"Direct and uniform initialization using constructors with parameters"?
    What is the purpose of using this function?

  • shahadat hussain

    please help me i am very problem
    what is constructore or
    use why

  • Christos

    Thank you Alex.

    I tried to initialize something that wasn’t existing yet. When I started reading the next chapter, I realized how obvious it was.

  • Christos

    Hi Alex,

    Thank you for your great job. You have made the most complete and comprehensible guide.

    May I ask you, why when I use "{ }" inside the constructors to set the members, vb2015 return me the error "C2064: term does not evaluate to a function taking 1 arguments"?

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <cassert>

    using namespace std;

    class Ball
        string m_color;
        double m_radius;

            m_color = "black";
            m_radius = 10.0;

        Ball(const string &color)
            m_color{ color };
            m_radius{ 10.0 };

        Ball(double radius)
            m_color{ "black" };
            m_radius{ radius };

        Ball(const string &color, double radius)
            m_color{ color };
            m_radius = { radius };

        void print()
            cout << m_color << " / " << m_radius << endl;

    int main()
        Ball def;

        Ball blue("blue");

        Ball twenty(20.0);

        Ball blueTwenty("blue", 20.0);

        return 0;

    • Alex

      This is invalid. You can not initialize members inside the constructor body, you can only assign. Assignment can only be done via operator=.

      If you want to initialize members, it must be done before the constructor body, via a constructor member initialization list (covered next lesson).

  • Will

    Is it a good practice to always provide a default "garbage" constructor, such that we can use std::array to store objects of this class?

    • Alex

      Generally, you will always want your classes to have at least one public constructor (otherwise, how will you construct them). Whether you allow that constructor to be a “default” constructor or not is really up to you and what makes sense for the class. For classes that just hold data values, you’ll almost definitely want a default constructor. For classes that require the user to provide some input in order to do a job (e.g. pass the class a filename to work with) there’s no default value that really makes sense, so in that case, no, you wouldn’t want a default constructor.

      If you want to create an array of a class that doesn’t have a default constructors, there are other ways to do that (such as having the array hold a pointer to the class object rather than the actual class object).

      • Will

        Can you illustrate a way to create an array of a class that doesn’t have a default constructor other than using pointers? I know we can use uniform initialisation. But considering the following code:

        There are two problems with it. First, the code become very ugly if the length of the array is very long. Second, there is clearly some relationship between each element. Is there a way to use a loop to construct the array so that we can save some effort as well as improve maintainability?

  • Lam Gia Khang

    I have some confuse about this line of code:

    Why we have the ampersand "&" before parameter color here? Because when I try it, the program still ran okay without "&". So I don’t know what is it used for??

  • Matthieu B.

    The code contained in the following code frame causes a compiler error since "default" is a reserved keyword:

  • Connor

    Hello again Alex. I was fooling around with classes and I’ve encountered an error when using two unique class constructors:

    My compiler (VS ’15) keeps giving me an error in that there is more than one default constructor. For some reason these aren’t existing in Harmony. WHAT AM I DOING WRONG??????

    • Alex

      A class can only have one default constructor, and you’ve declared two. When you instantiate object point1, is the compiler supposed to call the constructor with no parameters (in which case, m_x = 0 and m_y = 0) or the constructor that has all defaulted parameters (in which case, m_x = 10 and m_y = 10)? It can’t tell, so it’s giving you an error.

      • Connor


        a default constructor taking no parameters and

        a constructor taking two parameters? I was under the impression that NUMBER 1 was a constructor taking no parameters and NUMBER 2 was a constructor with parameters? you had said in the topic
        "Direct and uniform initialization using constructors with parameters"
        that we can have two constructors living in harmony, a default case and one taking two parameters…but when I try to define them as above I get the error (however, copying and pasting your example works just fine). Can you please elaborate on how the compiler is interpreting these constructors? Why isn’t the one with parameters simply overloaded?

        Again - thank you for the time and effort you’ve put into these tutorials.

        • Alex

          Yes, multiple constructors can live in harmony. However, a class can only have ONE default constructor, and both of your constructors qualify as default constructors (because they can both be called with no parameters).

          So when you do this:

          The compiler doesn’t know which constructor to call. Both are valid resolutions.

  • Rob G.


    I am trying to force the program to use a default value in the initialization parameters of object date_2 while I provide 2. Is this possible, and if so how do I do it?

  • Alex

    I still don’t understand what you’re looking for. 🙁 Is this it?

  • Jim


    I was able to figure out how to compile and run all the constructor Faction examples you showed in this lesson, Fraction six{6}; etc.. But I can’t figure out how to use directly initialization with int x {5};.  This has to be simple, but I’ve tried to do this a lot of ways without any luck.

    Can you please give me some idea of how to do this.  Thanks

    • Alex

      • Jim

        I guess I didn’t make my post clear. I did it exactly as you showed only with int x {5} and no y.  How does the program know what to use x for? I would have assumed it should replace the numerator value but I’m probably wrong. I even tried numerator = x, used m_numerator = x, vice versa and same other ways. But nothing worked. Can you show it used in an example program please?

  • subh samal

    Hi Alex,

    In question 1b (Quiz time), we can use a default constructor as below to handle all cases except Ball twenty(20.0);(my block of code is not exactly same to 1b.)
    Ball (string color2 = "black", double radius2 = 10.0)   //this is able to handle no parameter, only color, both color and radius.
             color = color2;
             radius = radius2;
    So my question is why it is not able to act as a constructor for the object with only radius parameter (eg: Ball twenty(20.0)) ? I can ask more elaborately in case my question is not understood!

    • Alex

      Unfortunately, C++ does not have the capability to “skip” arguments in a function call. I wish you could do something like this:

      I’m sure the C++ designers had a good reason for disallowing this, but if so, I don’t know what it is.

      • Darren

        Hazarding speculation, could be to do with: type checking; order the arguments are passed to functions; the number of arguments supplied; dealing with the ‘this’ pointer for member functions. In other-words, not a Scooby. (Scooby-do rhymes with "clue"). But yes it would be nice to be able to use this syntax. (BTW "Ball ball" - has someone been watching the ‘Goldbergs’ by any chance?).

  • Jim

    I see so by defining a class we are essentially creating an object with that classes name like Fraction used in this lesson. In that class we defined 2 private parameters. After which we used constructors Fraction with or without parameters, only we now define the parameters as public  So constructors are similar to a function since they both can have arguments passed to them. We then use get and return to supply the input and output.

    You did say there a many classes predefined in C++, however how do we know what they are? What does the #include <cassert> header cover.

    • Alex

      Constructors are not similar to functions, they ARE functions (just ones with a special purpose).

      The only way I’m aware of to see all the classes in C++ is to look at reference material. Much of what’s in the standard library are classes (e.g. std::cin and std::cout are objects of class ostream).

      The cassert header includes the assert function.

  • Shiva

    Alex, are constructors ever made private? If yes, can you give an example scenario?

    • Alex

      Yes, they are occasionally used. For example, if you make a default constructor private, then you can’t instantiate your class externally. This can be useful when you want more control over if or how many class objects are instantiated. Private constructors are mostly used for implementing Singletons and Factories. Consider:

  • Connor

    Hello Alex,
    for quiz Q1, when I define

    the << between "Color: " and m_color gives an error: no opererator "<<" matches these operands.
    What am I doing wrong?

    • Alex

      I’m not sure, I don’t see anything obviously wrong.

      Some things to check:
      1) Erase the entire line and re-type it to ensure you don’t have any invisible characters or fancy quotes
      2) Make sure you’ve included the string header
      3) Make sure m_color is a variable of some type that can be output via <<, like std::string or char[].

      • Connor

        OMG, you’re right - I forgot to

        I was pulling my hair out for hours trying to solve this one…don’t quit my day job I suppose.

        • Darren

          Very good example of the process of learning. Now if you seen that error again you’ll know to check for missing header file includes as a first port of call.

  • Vegeta

    Hey, in quiz 1b you created these two constructors:

    While I created these two (I used char pointer):

    So basically in my main function the user can write both:

    Is it better? It looks convenient. Or is that bad practice?

    • Alex

      I’ve actually never seen anybody ask this before. I think it’s generally a good idea to enforce a specific parameter ordering. A lack of consistency tends to lead to potential errors, especially in the future as you look to extend the code (what happens when you add a third parameter to the constructor?).

      Also, your example doesn’t quite work: if you define a ball with no parameters, the compiler won’t be able to determine which of the two constructors to call.

      • jo

        Dont you think that an advantage of the unsorted arguments is, if you ask a user "Enter color and/or radius of a ball!" it doesnt matter in which order the user provides the input?

        You can build the constructor like this and to ensure define works.

        • Alex

          > if you ask a user “Enter color and/or radius of a ball!” it doesnt matter in which order the user provides the input?

          There are a number of challenges with this kind of approach:
          1) The more ways there are for a user to do something, the more way there are for something to go wrong. It’s better to be more explicit about what you expect the user to do (enter the color first, and the radius second, or vice-versa, but pick one).
          2) Because radius and color are different types, they’re not interchangable. So you’re going to have to parse the user input to determine whether they entered (color, radius) or (radius, color). If you’re doing that, you now have a deterministic ordering, so you might as well call the constructor the same way every time.
          3) Having constructors that allow either ordering leads to less extensibility later. When you add a 3rd parameter are you going to write 7 more constructors to have every permutation?
          4) If two of the parameters are the same type, this doesn’t work, because you can’t disambiguate which is which.

  • Nachiket

    I have just started learning C++. I have one question in very first code on this page. What is the difference between following two lines?


  • George


    Can you tell me how class string uses constructor in this way: std::string()
    Overloaded parenthesis operator or something else?

    I also found somewhere something like this: XClass foo = XClass();

    Thanks in advance!

  • Aaron

    Thanks again for the free textbook online!

    For the constructors for the Ball class, it seems to be adequate to provide only two of them: one with the 2 parameters as optional (with default values), and another with only the 2nd parameter as required. For example:

    If the user provides no arguments, both arguments, or a string argument, the first constructor is called. With a type double argument, the second is used. Anything wrong with this?

    • Alex

      Not at all! I’ve updated the quiz question to have the reader do things both ways (without and with default parameters), because I think it’s instructive. Thanks for the thought!

  • Ishtmeet Singh

    Hi Alex,
    In your first quiz question:

    why did you write const string instead of using string only? And why are we passing string by reference instead of value?

    • Alex

      Because it’s better to pass non-fundamental variables by const reference than by value. That avoids making an unnecessary copy when the argument is passed to the parameter.

  • Brett

    Shouldn’t it be:

    instead of:

    for the examples on this page?

  • Lokesh

    In quiz-2 solution, you have said:
    "The compiler creates an empty one for you. If there are no other constructors, this created constructor is public. Otherwise it is private."
    I think you should omit the part "Otherwise it is private" as it creates confusion. If there are other constructors(whether it is default or non-default), the compiler would not create any constructor. Hence, you would have to define your own default constructor. So, the answer should be something like:
    "If there are no other constructors defined, the compiler will create an empty default constructor. This automatically created constructor would be public.
    However, if there are other constructors that take parameters, we would have to define our own default constructor and explicitly make it public using the public access specifier."
    See, that’s why I commented earlier that the concept is a bit twisty.

  • Lokesh

    In the default constructor code example, shouldn’t the pre-processor directive such as #include be at the top of code file by convention?

  • Kiran C K

    Hi Alex,

    I was writing a code that just instantiates an object with default constructor and the member function does the other works. here is my code:

    Here are my questions:
    1. I have declared a default constructor under

    . But if it is not defined, it shows error as

    when creating an object. I am wondering that if the class members are private, would the default constructors would also be private. If that is the case, what would be the access if a class has both private and public members?

    2. Without defining the above public default constructor, if I created an object as

    , it shows the error

    And I get the similar error for all the three member functions.


    are doing the same thing. Then why is the compiler shows two different error messages?

    I am using Code::Blocks IDE GCC compiler

    • Alex

      1) If you don’t provide _any_ constructors, C++ will provide a public default constructor for you. In this case, since you have a private non-default constructor, if you remove the public default constructor, C++ won’t provide one for you. This means your class has no default constructors, which means it can’t be instantiated directly.

      2) I think the compiler may be getting confused and thinking that pass is a function, and that Booking pass() is a forward declaration rather than a variable definition.

  • Vaibhav

    Hi alex,
    The first example for default constructor that you gave- while calling Fraction default in the int main my compiler is showing error ,whereas instead of using the word default if i use anything else it works..What is happening wrong!?
    The compiler shows error as improper use of typedef ‘Fraction’

    • Alex

      default is a keyword in C++11, so your compiler is probably getting confused. I’ve updated the example to give the variable a different name.

  • Aditya

    Why does the constructor have to be public? We haven’t called it right? Does being private mean that even the compiler can’t access it?

    • Aditya

      So it dawned on me that we are calling the constructor when we define the object. Please correct me if i’m wrong.

    • Alex

      If a constructor is public, then it can be used by instantiated objects. If the constructor is private, then instantiated objects can not use it (but in C++11 it can still be called by other constructors).

      For example, making a default constructor private means that you can’t instantiate objects like this:

  • Matt

    Hello Alex -

    Why do you use the following in the constructor for the Ball class:

    Is there a reason for using a reference variable for the string "color"? Thank you.

    • Alex

      Yes, without the reference, C++ would make a copy of the argument passed into parameter color every time the Ball constructor was called. Since color is a class, this is likely to be slow, and unnecessary.

      Passing in a const reference allows us to avoid making a copy of the argument passed into color and just use the argument itself.

  • Josh

    "If there are no other constructors in the class, the created default constructor will be public. Otherwise, it will be private (disallowing creation of the object via the default constructor)."

    As far as I known, if user provides non default constructor(s), the default constructor will not be created. Hence, it should not be private, perhaps, I misunderstand it. Could you please help clarify it, thanks a lot.

    • Alex

      You’re correct, my mistake. However, the practical effect is the same: the class can’t be instantiated without parameters. I’ve updated the lesson to be accurate in this regard.

  • Sophie

    Can you maybe explain why in quiz question 1 the variable color is passed by (const) reference in the constructor (i.e. const std::string &color)? Why is this preferred over passing the variable by value?

    • Alex

      Passing an argument by value would cause the compiler to copy the argument’s value into the parameter. For fundamental types (int, bool, double, enums, and data-only structs) this is fine, because doing so is trivial and fast. For other types (especially classes, such as std::string), making a copy can be expensive. In these cases, it’s better to pass by const reference, to avoid making a copy.

      In short, pass fundamental types by value (or reference, if you need the function to modify the argument), pass classes by const reference.

  • Anthony

    Hey, great tuts. They’ve helped a lot while I get through school. I just wanted to clarify something. Say I have the following constructor:

    and in my main I have this:

    Now, this sets the first name as Test. Say I only know the last name or the payrate. Do I need to make two different constructors only specifying payrate or lastName? Just want to make sure I’m not wasting time typing out all these constructors that aren’t needed. Thanks in advance.

    • Alex

      Yes, if you only know last name or payrate, you’d need to make separate constructors for those. You’d also need to have some way to distinguish first name from last name -- since both are strings, the compiler probably wouldn’t be able to infer which you’d intended.

      • Lyle

        I see you can provide variations of the constructors to handle different # of inputs, and I get that.
        Can/how do you do the case where you want to supply just the 3rd argument, ala something like constructorname(,,argument) ?

        Related  - do you have an example of creating a list/vector/array of many instantances of a class object (containing references to additional sub classes) - and how to safely write to file ( and later reconstruct from same) in a portable and unambiguous manner to file ?   If not, what is the correct terminology to search for examples of it ?

        Excellent and clear tutorials all the way through. Thank you so much.

        • Alex

          There’s no way to write a function (constructor or otherwise) that allow you to provide default values for non-rightmost parameters.

          If you want a constructor where you only need to pass in the 3rd argument, then consider writing a constructor that takes one argument, which would be the third argument from the other constructor:

          constructorname(type arg3)

          This will work so long as that constructor has a unique signature.

          As for creating a list/vector/array of a class object:

          This only works if YourClass has a default constructor.

          If YourClass doesn’t have a default constructor, you can construct these using an initialization list:

          std::vector also has a form to initialize every element with the same object:

          Writing stuff to files is tricky, and probably a good topic for an entire lesson or two. I don’t have anything of that nature yet, but I’ll add it to my to do list for consideration.

          • Lyle

            Thanks, it’s a good topic - the whole file I/O space, maybe XML or other text format as well as binary - in and out. ?

            "many instantances " …  that’s "many instances" …

  • Aleksandar

    I would just like to say thanks for creating this amazing web site. It helped me a lot while learning C++. My professors are really bad at explaining things and I can hardly understand anything that they are saying. They also give very few examples and there is just a lot of theory. Now, after studying by reading these tutorials, I really think I have a chance to pass this exam. Thank you once again. 😀
    I wish you were teaching at my university. 😀

  • Gopal

    Hi Alex,

    Can we define more then one Constructor (and Destructor) within a Class? Note: not by function overloading but all together different Constructors with different names.

  • Gopal

    A question not related to Constructor: Why uninitialized variable always contains garbage valve? Why is not just simply 0 or 0000 0000?

    • Alex

      C++ doesn’t initialize variables by default because there’s a performance cost to doing so. If you want an initialized variable, do it yourself. 🙂

      It’s worth noting that many uninitialized variables will contain the value 0, when the memory allocated for the variable happens to be set to 0. In this case, the 0 is a garbage value. Running the program again may produce a different result.

  • Mr D

    Ok, so in your last example of the chapter, you create a class that has a default constructor value, but also accepts an argument to user-define the value of the constructor? And the user-defined one takes precedence? Hence:

    • Alex

      There is only one constructor here, and it is the default constructor. It just so happens that this default constructor takes an optional parameter that can be used to specify the month.

      In the first case, you’re calling the default constructor and using the default value for parameter nMonth.
      In the second case, you’re also calling the default constructor but with a supplied value for parameter nMonth.

  • vish

    oh yes constructor is a class memeber function got it.

  • vish

    Thanx Alex. Now i found constructor a very useful and powerful member of a class. i read this chapter twice and i got it. Sometimes constructor itself looks like function. i think i ll get use to with more practice.

  • vish

    i am not understanding here. i can initialize numerator and denominator in my main fuction why i use constructor?
    or the thing is that constructor used for default initialization but if i do not want a default initialization why would i use constructor?

    • Alex

      If numerator and denominator are private members of the class, how do you intend to initialize them from your main function? I suppose you could use public functions (e.g. setNumerator()) to do so, but this is clunky. I think you’ll agree that:

      is easier than:

      The entire purpose of constructors is to initialize a newly created object. You can provide multiple flavors of constructors to handle different types of initialization: one for default initialization, one or more for initialization where the user provides input values, and others for other types of initializations (e.g. conversions from other types, etc…)

  • Alex, why we can’t initialize a member variable when declaring it. Code::Blocks has no problem with this program:

    And the output is:

    I heard that we can’t initialize member variables like this(but code::blocks does not throw any error). Is that true? If not, then why use constructors?

  • Shivam Tripathi

    hii alex…after a long tym m back …:)

    m li’l bit confused about constructor’s (ctor) actual definition…in wikipedia it’s written that " ctor is a sub-routine invoked to ‘create an object’ "…but u mentioned (and also i hv heard from  a lot of person saying) that ‘ctors’ come in existence when ‘object is created’…

    so what’s actually true…do ctor’s come in existence when object is created….or ‘object’ come in existence when ‘ctor’ is called…

  • kekie

    Okay, so default constructors with optional parameters I get, but I don’t really see the point of default constructors with no parameters. Why not just set the member vars where they’re declared?

    So, to clarify, why do this;

    int m_var;
    m_var = 6;

    When you can do this;
    int m_var = 6;

    • Alex

      You couldn’t do this before C++11.

      Now that you can, I agree that it’s better to favor the non-static member initialization form than a default constructor with no parameters.

  • rmusty

    Hi, I tried making a program that utilizes constructors and takes the users name and birthday as an input and outputs his/her age. I am getting the following problem:
    (56): error C2228: left of ‘.calc’ must have class/struct/union
    (57): error C2228: left of ‘.output’ must have class/struct/union

    My code:

    #include “stdafx.h”

    using namespace std;

    class Person
    char c_strName[25];
    int c_month;
    int c_day;
    int c_year;
    int c_age;

    Person(char *strName = “No Name”, int month = 1, int day = 1, int year = 1900)
    strncpy_s(c_strName, strName, 25);
    c_month = month;
    c_day = day;
    c_year = year;

    void calc()
    time_t now = time(0);
    tm *locTime = localtime(&now);

    int curMonth = 1 + (locTime -> tm_mon);
    int curDay = locTime -> tm_mday;
    int curYear = 1900 + (locTime -> tm_year);

    c_age = curYear - c_year;

    if(((curMonth - c_month) > 0) && ((curDay - c_day) > 0))
    c_age = c_age - 1;

    void output()
    cout << "Your age is: " << c_age << endl;


    int _tmain(int argc, _TCHAR* argv[])
    Person cBob();
    cBob.calc(); // ERROR POINTS TO THIS LINE
    cBob.output(); // ERROR POINTS TO THIS LINE

    return 0;

    • McGlear

      In case somebody has a similar problem:

      When creating an instance of a class, you have to omit the parentheses! You are not calling a function but creating an instance of your Person class.

      int _tmain(int argc, _TCHAR* argv[])
      Person cBob; // This should do the trick
      cBob.calc(); // No error anymore
      cBob.output(); // Compiles fine as well.

      return 0;

  • gantashalavenki

    can we call constructor manually like any other member functions?….after intializing varialbes using constructor can we call constructor once again to reinitialize?

  • SWEngineer

    Simple well explained tutorial.


  • andi

    Hi Alex,
    Just want to say … it’s really great tutorial. Thanx it helps me a lot. i like the way you make your explaination, it’s simple and easy to understand.

  • Vineet

    Your tutorial is nice and gives a clear understanding of constructors.


  • Mark

    I haven’t programmed for many years as OOP seemed too scary but it’s all coming together really clearly now thanks to this this site. I’m starting to see the elegance of this language. Many thanks Alex for your clear and concise tutorial.

  • Ramakrishna

    hello Alex,
    This is the first time iam seeing this site actually iam
    from non computer background, eventhen iam able to understand easily..
    Really good job
    thanks Alexji………..

  • Paulius

    Hi Alex,
    I have the following class:

    and using this

    initializes posX to 10. Is there a way, i can initialize first constructor parameter to default value, and second one to something else?

    I want to do something like this: (ofc, this example doesn’t compile)


    • codeez

      No, remember parameters replace from left to right. It wouldn’t hurt to just call it with point(0, 10); though.

    • bruno

      If you always want to call

      Meaning that if just one parameter is given, x will be default and y will be the int.
      Then you could just reverse the order of you parameters

  • Vishal

    hello alex,
    When i compiled following program i got an error that-

    Ambiguity between Con::Con(int) & Con::Con(float)
    my query is that Why this is so? We can do same thing with functions(i did it in this program too) then why cant with Constructors???

    • baldo

      The error appears because the compiler treats the number 10.8 as double by default. That is why you get the ambiguity error. Replace 10.8 with 10.8f so the compiler knows that the number is a float number.

  • Maryam

    THANKU guys…. i was facing problem in parameterized constructor. thanks a lot again…

  • Do constructors must have same name as class or can have different name?


  • It’s really help full for students like for me .
    I had recommended this to my fiends too.

  • Renu

    class Fraction
    int m_nNumerator =10;
    int m_nDenominator=20;

    Fraction() // default constructor …….

    I tried initialising m_nNumerator =10 and int m_nDenominator=20

    got this error ” only static const can be initialised ….”

    Then I tried

    static const int m_nValue=22;
    int m_nNumerator ;
    int m_nDenominator;
    It worked.

    Could you please explain? Does that mean private member variable cannot be initialised when they are declared? If so ,is there any specific reason for that?


    • (Edit: This comment is now outdated due to a change in C++11 -- see next comment in this thread)

      In a class, you can’t initialize values on the line they are declared like that. Non-static class values should be initialized in the constructor body or initialization list. Static class values should be initialized in the body of the class definition.

      I am not sure what the reasoning is for this design decision. I presume simply because the constructor is the function that is supposed to initialize your values. If you were allowed to do default values this way, then many variables would be initialized twice (once in the declaration, once in the constructor). This would be both inefficient and confusing.

      • Connor

        Hello Alex,
        when I initialize the class variables after declaring them the program will still compile without error.

        could this just be the way my compiler is set up (I’m using code::blocks) or am I not grasping the concept?

        • Alex

          This is one of my favorite features of C++11. Starting with C++11, it’s now possible to assign struct and class members a default value using standard initialization syntax. This means you don’t have to initialize these values in the constructors.

          If you have a value initialized both on the declaration line AND in the constructor, the constructor will take precedence. e.g:

          m_whatever will be initialized to 9.

  • Abhishek

    what’s assert() ?

    • I talk about assert in section 7.12. In short, it’s a way to test whether an expression is true, and if not, stop the program at that point.

      • J3ANP3T3R

        Hey Alex sorry to be a huge bother but im going back a few lesson pages because i’m having trouble with constructors. if i pass some parameters to a class i wanted to find out which section is going to take precedence ( the default values or the initialized values ). so i try to run a test on visual studio 2015 and something is wrong with my code and i couldn’t quite figure it out.

        i got this on main()

        this will print some wacky numbers … it was originally not INT but std::string but that would print empty for me so i tried to make them integers. got any idea ? 🙁

        • Alex

          The problem here is that your constructor parameters have the same name as the member variables. So when you do m_fname = 4, you’re assigning the value of 4 to the parameter, not the member variable.

          The best way to fix this is to ensure your parameters have unique names (e.g. don’t start them with m_, they’re not member variables).

          • J3ANP3T3R

            Thanks alex that fixed it i changed it to :

            because to continue with testing. i am now playing around with the "default" parameters. the problem now is this prints some weird values -858993460 -858993460 -858993460 …  is there something wrong with my using of data type INT ?

            • Alex

              No, but you’re still not assigning values to m_fname, m_mname, and m_lname.

              Your constructor should be:

          • J3ANP3T3R

            im so stupid… got twisted with my own variable names. got it alex thanks again

          • J3ANP3T3R

            hey Alex can i ask how do you force an empty parameter ? just for testing. like if i have

            Person(int pfname=10, int pmname=11, int plname=12)

            i wanted to force int pmname=11 to fire and ill pass a value to pfname and plname except pmname.

            • Alex

              C++ doesn’t provide any way to use the defaulted value for a middle parameter. If you want to use defaulted parameters, those parameters must be on the right.

              I’m sure C++ has a good reason for this, but I don’t know what it is. 🙂

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter