What default functions provided by compiler in C++?

Below are default functions provided by compiler  in C++ language if not implemented  in a class by a software developer.

  • Default constructor
  • Copy constructor
  • Assignment operator
  • Destructor

NOTES

Default constructor example:

If we don’t write any constructor in a class including c++ copy constructor then default constructor provided by compiler will be called when we create an object of the class E.g. in below class A, constructor is not written, hence default constructor will be called in the program.

C++ code example :

class A{
public:	
	void function(){
	}
};

int main() {
	A ob; // default constructor will be called, generated by compiler
	return 0;
}

But, if you write any constructor , whether it is empty or with arguments or copy constructor , it will never call default constructor but user defined constructor E.g.

class A{
	
public:
	A(int a){//constructor with argument. No default constructor will be called
	}
	void function(){
	}
};
int main() {
	A ob(5); //calls parameterized constructor
	return 0;
}

Now question is, what will happen, if we create object like “ A ob” in above example? Answer is, it will not call c++ default constructor and compiler will flash an error i.e.

“error : ‘A’ : no appropriate default constructor available“

To resolve this error, we need to place an empty constructor like A(){} too in the class.

class A{
	
public:	
	A(){} // empty constructor
	A(int a){//constructor with argument. No default constructor will be called
	}
	void function(){
	}
};

int main() {
	A ob(5); //calls parameterized constructor
	A ob1;// now works fine
	return 0;
}

Default destructor:

Default destructor is also called implicitly if we have not written in the class.

Related Posts