Default Constructor

Default Constructor
Default Constructor
CONCEPT 

Default Constructor is also called as Empty Constructor which has no arguments and It  is Automatically called when we creates the object of class  but Remember name of Constructor is same as name of class and Constructor never declared with the help of Return Type. Means we cant Declare a Constructor with the help of void Return Type. , if we never Pass or Declare any Arguments then this called as the Copy Constructors. 
EXPLANATION

A class may have many constructors, but can only have one default constructor. This is because if multiple functions have the same name, the compiler must be able to determine from their parameter lists which one is being called at any given time. It uses the number and type of arguments passed to the function to determine which of the overloaded functions to invoke. Because there can be only one function with the class name that is able to accept no arguments, there can be only one default constructor.

Normally, as in the Sale class, default constructors have no parameters. However, it is possible to have a default constructor with parameters if all of its parameters have default values, so that it can be called with no arguments. It would be an error to create one constructor that accepts no arguments and another that has arguments but allows default values for all of them. This would create two “default” constructors. The following class declaration illegally does this.
class Sale // Illegal declaration!
{
private:
double taxRate;
public:
Sale() // Default constructor with no arguments
{ taxRate = 0.05; }
Sale(double r = 0.05) // Default constructor with a default argument
{ taxRate = r; }
double calcSaleTotal(double cost)
{ double total = cost + cost * taxRate;
return total;
};
As you can see, the first constructor has no parameters. The second constructor has one parameter, but it has a default argument. If an object is defined with no argument list, the compiler will not be able to resolve which constructor to execute.


Previous
Next Post »