Nitesh Singh
Nitesh Singh

Reputation: 37

Which constructor will be executed?

Here, a parameterised constructor is declared but the object corresponding to that constructor is not created. But the output is 10 20 which is the execution of parameterized constructor, why?

#include<iostream>
using namespace std;

class constructor
{
    int x, y; 
    public:
    constructor(int a = 10, int b = 20 )
    {
        x = a; 
        y = b;
    }
    void Display()
    {
        cout<< x << " " << y << endl;
    } 
};

int main()
{
    constructor objBix;     
    objBix.Display(); 
    return 0;
}

Upvotes: 0

Views: 150

Answers (5)

Ajay Singh Deopa
Ajay Singh Deopa

Reputation: 146

In this case, the Parameterized constructor has been defined with all the parameters having some default values. So, even if you create an object without passing any arguments, it will treat the Parameterized constructor as default constructor and it gets called. for example, if you define constructor as

constructor(int a, int b = 20 )
{
    x = a;
    y = b;
}

Then you have to create new object of the class with at least one value which will be assigned to parameter "a".

Upvotes: 0

Z E Nir
Z E Nir

Reputation: 372

as you can read in previous answers, since you gave default values for the arguments this is the default constructor for this class objects.

so it's like write:

constructor()
{
    x = a; 
    y = b;
}

this is exactly what you did!

Upvotes: -1

iBug
iBug

Reputation: 37227

Since you have defined a custom constructor with all default arguments, it will serve as the default constructor. The compiler won't generate another default one because that would cause ambiguity when deciding which function to call. So what's actually called is your custom constructor with all default arguments used. A compiler-generated "default" doesn'y exist at all.

Reference: CppReference

A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter).

Upvotes: 3

Robert
Robert

Reputation: 8571

You did define a no-arg constructor, overriding the default constructor. You gave default values for the parameters, and hence you can call it without arguments and your defaults are used.

Upvotes: 0

vitaut
vitaut

Reputation: 55544

Quoting cppreference:

A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter).

Compiler will only implicitly generate a default constructor for you if no other constructors are provided, so in your example it is not generated.

Upvotes: 1

Related Questions