Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 03 Jun, 2022

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

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

Example 1: 

CPP




// C++ program to demonstrate a program without any error
#include <iostream>
 
using namespace std;
 
class myInteger {
private:
    int value;
 
    //...other things in class
};
 
int main()
{
    myInteger I1;
    getchar();
    return 0;
}

Example 2:

CPP




// C++ program to demonstrate a program which will throw an
// error
#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;
}


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!