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


In this tutorial, we will be discussing a program to understand if the C++ compiler creates a default constructor when we write our own.

Generally, the C++ compiler uses the default constructor when no one is defined, but always uses the one defined by the user if any.

Example

 Live Demo

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

Output

Compiles successfully

Example

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

Output

Gives error about user-defined constructor not being defined

Updated on: 23-Mar-2020

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements