Search

Meta

8.5 — Constructors

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:

0/1

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
Index
8.4 -- Access functions and encapsulation

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

    Thanks,
    Renu

  • Renu

    class Fraction
    {
    private:
    int m_nNumerator =10;
    int m_nDenominator=20;

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

    private:
    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?

    Thanks,
    Renu

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

    • 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

    Typo:

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

    thanks.

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

    construct.cc: In member function ‘double Fraction::GetFraction()':
    construct.cc:28: error: ‘nDenominator’ undeclared (first use of this function)
    construct.cc:28: 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!

    Cheers,

    Jamie

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

    Thanks,
    Paulius

  • 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 {
    private:
    float *array;
    public:
    //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?

    Tom

  • Vineet

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

    Thanks,
    Vineet

  • 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.
    cheers,
    andi

  • SWEngineer

    Simple well explained tutorial.

    Thanks.

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

    #include

    using namespace std;

    class Date
    {
    private:
    int m_nMonth;
    int m_nDay;
    int m_nYear;
    public:
    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;
    }

    Output:
    -858993460/-858993460/-858993460
    0/0/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

    Hey!
    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”
    #include
    #include
    #include

    using namespace std;

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

    public:
    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;
    public:
    Classname()
    {
    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.

    #include
    #include
    #include
    #include

    using namespace std;

    class Student
    {
    private:
    char *m_strName;
    char *m_strDept;
    int m_iAge;
    int m_iUSN;
    public:
    FILE *Datafile;
    Student()
    {
    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];
    }
    }
    ~Student()
    {
    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!.

Leave a Comment

  

  

  

seventeen + 9 =

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