Skip to content
Related Articles

Related Articles

Improve Article

Does C++ compiler create default constructor when we write our own?

  • Difficulty Level : Easy
  • Last Updated : 17 May, 2021

In C++, compiler by default creates default constructor for every class. But, if we define our own constructor, compiler doesn’t create the default constructor. This is so because default constructor does not take any argument and if two default constructor are created, it is difficult for the compiler which default constructor should be called.

For example, program 1 compiles without any error, but compilation of program 2 fails with error “no matching function for call to `myInteger::myInteger()’ ” 
Program 1  

CPP




#include<iostream>
 
using namespace std;
 
class myInteger
{
   private:
     int value;
      
     //...other things in class 
};
 
int main()
{
  myInteger I1;
  getchar();
  return 0;
}

Program 2:

CPP




#include<iostream>
 
using namespace std;
 
class myInteger
{
   private:
     int value;
   public:
     myInteger(int v)  // parameterized constructor
     {  value = v;  }
    
     //...other things in class 
};
 
int main()
{
  myInteger I1;
  getchar();
  return 0;
}

Please write comments if you find anything incorrect in the above GFact or you want to share more information about the topic discussed above.
References: 
http://en.wikipedia.org/wiki/Default_constructor 
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr375.htm
 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :