Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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




Last Updated : 03 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads