Language Selector

8.5 — Constructors


A constructor is a special kind of class member function that is executed when an object of that class is instantiated. Constructors are typically used to initialize member variables of the class to appropriate default values, or to allow the user to easily initialize those member variables to whatever values are desired.

Unlike normal 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)

A constructor that takes no parameters (or has all optional parameters) is called a default constructor.

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). When we create an instance of the Fraction class, this default constructor will be called immediately after memory is allocated, and our object will be initialized. For example, the following snippet:

produces the output:


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.

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. 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:

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

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

In this case, our default constructor is actually somewhat redundant. We could simplify this class as follows:

This constructor has been defined in a way that allows it to serve as both a default and a non-default constructor!

Classes without default constructors

What happens if we do not declare a default constructor and then instantiate our class? The answer is that C++ will allocate space for our class instance, but will not initialize the members of the class (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_nMonth, m_nDay, and m_nYear were never initialized. Consequently, they will hold garbage values. Generally speaking, this is why providing a default constructor is almost always a good idea:

8.6 -- Destructors
8.4 -- Access functions and encapsulation

63 comments to 8.5 — Constructors

  • Cody

    As a review you could include protecting m_nDenominator from invalid assumptions by making sure it is not set to 0. This is because, if I remember correctly, dividing anything by zero will probably cause the program to crash so the function GetFraction() would most likely crash the program if the denominator is 0.

  • Abhishek

    what’s assert() ?

  • Renu

    double GetFraction() { return static_cast(m_nNumerator)/nDenominator; }

    “m_nNumerator)/nDenominator” should be “m_nNumerator)/m_nDenominator ”
    at all three places in the tutorial.


  • 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?


    • 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.

    • prabodh

      hi renu,

      there is not specific reason why we can not initialize private data in class … It’s C++ basic rule that user shouldn’t initialize private,protected or public data inside class without using function or constructor…..

      • Vivek

        I believe this may be because the time you are declaring your classes, memory is not allocated to it. It’s merely a declaration of the class where you are trying to initialize the member variable whose memory hasn’t yet alloted.

  • Tom


    “Date cToday(9, 5, 2007); // cDate is initialized to Sept 5th, 2007 ”

    Should be:

    “Date cToday(9, 5, 2007); // cToday is initialized to Sept 5th, 2007 ”

    [ Fixed. Thanks! -Alex ]

    • gantashalavenki

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

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

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


  • Spock

    So I tried compiling a really simple example from above (constructors with parameters) using

    So this is pretty much exactly what you have, except that I included a simple main so that I could see if it compiles, however I get: In member function ‘double Fraction::GetFraction()’: error: ‘nDenominator’ undeclared (first use of this function) error: (each undeclared identifier is reported only once for each function it appera in).

    This should have been foolprooooof! HELP!

  • Maryam

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

  • Vijendra

  • 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.

  • Hi Alex,

    A small suggestion on preventing the pain of date ambiguity!

    Could mean 9th May 2007 or 5th Sept 2007, in fact it means the former everywhere except the US.

    Definitely means 2007 September 5th for everyone!

    As long as you’re training new programers (and doing an excellent job too) I’d say this is another well recommended habit to learn in case you work on a project with an international team in the future!



  • 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

  • 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………..

  • Hi Alex. This has been some very helpful reading. I’m better understanding what is going on with the OOP side of C++.

    At the moment I don’t have the code in front of me, but here’s the summary:
    I attempted to initialize an array of values that are intended to be constant. In the object constructor, the array is initialized as a pointer, say:

    class Foo {
    float *array;
    //some public variables
    // more stuff here

    Now I’m not sure what is the best way to proceed. Right now it is initialized in a function say,

    Foo::foobar() {
    //set array size
    //set individual constant values.
    // foobar’s functions

    It works to do it this way, but I know it is a kludge to initialize an array of constant values every time the function is called.

    It looks like I could do this by making a public function to do this, but how can I prevent this from being changed by functions not belonging to the class? Maybe I just need to keep reading your tutorials and I’ll find out.

    But, if you find this an interesting topic, then what is the best way to initialize an array of constants that is global to the class in an object oriented language?

  • Ha. I figured it out. My problem was not from misusing the constructor, but that I had a loop in a cleanup function that was setting everything to 0. This was meant to clean up other arrays that DO need to be reset each time the cleanup function was called, but for some reason I put my array of constants in the cleanup, and it was doing exactly what I told it to do.

    Anyone who says computers do exactly what you tell them to do…
    +1 to that. :)

  • Aakash

    Using a constructor, how would you initialize a string type with a string value?

  • 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.

  • Tom

    I didn’t see any comments about #include before it is used.

    I assume that it is necessary for constructors?


  • Vineet

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


  • 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.

  • SWEngineer

    Simple well explained tutorial.


  • ccc

    Hi Alex,

    Thank you so much for such a great tutorial. However, I would like to use this section to indicate what is consistently missing in this tutorial. When discussing class, I think many reader will be more interested in object in the heap than stack.

    In the above example, because we declared a Date object, but there is no default constructor, m_nMonth, m_nDay, and m_nYear were never initialized. Consequently, they will hold garbage values. Generally speaking, this is why providing a default constructor is almost always a good idea:

    will be true for stack object but it will not be true for heap object. For example:


    using namespace std;

    class Date
    int m_nMonth;
    int m_nDay;
    int m_nYear;
    int getMonth(){return m_nMonth;}
    int getDay(){return m_nDay;}
    int getYear(){return m_nYear;}

    int main()
    Date cDate;
    // cDate’s member variables now contain garbage
    // Who knows what date we’ll get?

    cout << cDate.getMonth() << "/" << cDate.getDay() << "/" << cDate.getYear() << endl;
    Date *pDate = new Date();
    cout <getMonth() << "/" <getDay() << "/" <getYear() << endl;

    return 0;


    I found this tutorial purposely omit this distinction. Is there reason for it. However, no matter what. It is really really the greatest c++ tutorial ever. Thank you so much Alex for your hard work.

  • spidey

    I joined in new and think I have the answer to Renu’s query(just a few years late, though) which is 3rd from the top.

    Renu, classes are just the blueprint of how you want your object to look like and behave. It does not allocate any memory unless and untill an object fot it is instantiated. The very obvious reason why constructors are called only when an object is created. On the other hand, since static variables ought to get shared amongst multiple object, it has to be defined within the class itself. Otherwise, each instance might try to set a different value for it and ‘static’ would lose its very meaning :( Moreover, trying to initialize a non-static variable inside a class would be synonymous to trying to install a television in the blueprint architechture of your living room(which is actually lying on the paper) 😛

  • vitalreddy

    HI…This is good tutorial..very nice… i studied the whole constructors but in this lesson i have some doubt about constructors…..please give explanation about object because object can create memory?…why again constructor create memory….how to it create….without constructor we can’t create memory.? please give me reply for this one…………:)

  • 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;

  • 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;

  • Vinay

    Hi, i have developed a code that can capture and display students name, age, department and university seat number. In this code, i have used the new operator for dynamic allocation of arrays. I’d like to know how this code can be further optimized using parametric constructor, copy operator and equal to operator.


    using namespace std;

    class Student
    char *m_strName;
    char *m_strDept;
    int m_iAge;
    int m_iUSN;
    FILE *Datafile;
    int n =0;
    int i=0;
    int m_iUSN = 0;
    int m_iAge=0;
    cout << "Enter the size of n: " <> n;
    for(i=0; i<n ; i++)
    m_strName = new char[i];
    m_strDept = new char[i];
    delete[] m_strName;
    delete[] m_strDept;

    void Data_entry()
    cout << "Enter the Name of the Student: " <> m_strName;
    cout << "Enter the Department Name: " <> m_strDept;
    cout <<"Enter the Students Age: " <> m_iAge;
    cout << "Enter the Students USN: "<> m_iUSN;
    void Print_data()
    cout << "Students Name: " << m_strName;
    cout << "Department: "<< m_strDept;
    cout << "Age: " << m_iAge;
    cout << "m_iUSN: "<>a;

    return 0;

    How can i add insert an option to add new student? so that the code can take in data of multiple students and save it on a file. I have done the dynamic allocation of the arrays and getting results, but my guide tells me, i can further simply the code by using parameter constructors, copy constructor and equal to operator. Any help would be great!.

  • vijay

    Create two classes rectifier and transistor.ln rectifier create a constructor that takes a transistor as an argument.create a function that takes a rectifier and call that function with a transistor to show that it works.
    Now Make the rectifier constructor explicit to demonstrate that the automatic type conversion is this prevented. Modify the call to your function so that the conversion is made explicitly and thus succeeds.oops concept.

  • 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…

  • 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?

    • Alex

      As of C++11, you can now set default values directly on member variables of structs and classes. Prior to C++11 (when this tutorial was written), you couldn’t do that. I’ll definitely mention that when I rewrite the lesson!

  • 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 and non-performant. 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…)

  • 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

    oh yes constructor is a class memeber function got it.

  • 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.

  • 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.

  • 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

    Ohhh! we can have constructor with same name as of class. In this case we can have only one constructor within a class. Correct me if there is some other way to do so.

Leave a Comment




8 − two =

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