Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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



Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 03 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads