Open In App

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

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

No, the C++ compiler doesn't create a default constructor when we define any type of constructor manually in the class.

Explanation

The default constructor is used to create an object's instance without any arguments. In C++, the compiler implicitly creates a default constructor for every class which doesn't have user defined constructor so that at least a simple instance of the class can be created. But if we define our own constructor, the compiler assumes that we know what we are doing and doesn't need default constructor (as if we have needed it, we would have defined it just like the other one). So, it doesn't create the default constructor.

In example 1, we have not defined any constructor in myInteger class. Even then, the instance of myInteger class is created because the compiler implicitly defines the default constructor.

But this is not the case in Example 2, where we have defined a parameterized constructor. It will throw a no matching function call error.

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


Output

(no output)


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:
  
  	// parameterized constructor
    myInteger(int v) {
        value = v;
    }

    //...other things in class
};

int main() {
    myInteger I1;
    getchar();
    return 0;
}


Output

main.cpp: In function ‘int main()’:
main.cpp:21:15: error: no matching function for call to ‘myInteger::myInteger()’
21 | myInteger I1;
| ^~
main.cpp:13:5: note: candidate: ‘myInteger::myInteger(int)’
13 | myInteger(int v) {
| ^~~~~~~~~
main.cpp:13:5: note: candidate expects 1 argument, 0 provided
main.cpp:6:7: note: candidate: ‘constexpr myInteger::myInteger(const myInteger&)’
6 | class myInteger {
| ^~~~~~~~~
main.cpp:6:7: note: candidate expects 1 argument, 0 provided
main.cpp:6:7: note: candidate: ‘constexpr myInteger::myInteger(myInteger&&)’
main.cpp:6:7: note: candidate expects 1 argument, 0 provided

Next Article
Practice Tags :

Similar Reads