Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the ambiguity between default constructor and overloaded constructor?

Tags:

c++

The line A b(3) produces ambiguity as it could invoke any of the two possible constructors. Either the single argument parametrized constructor or the two-argument parametrized constructor with default argument. How do i solve this?

#include<iostream>
using namespace std;
class A
{
    public:
    int a,b;
    A()
    {
        a=5;
        b=6;
    }
    A(int a1)
    {
        a=a1;
        b=54;
    }
    A(int a1,int b2=8)
    {
        a=a1;
        b=b2;
    }
    void show()
    {
        cout<<"a="<<a<<" b="<<b<<endl;
    }
};    
int main()
{
    A a(3); // I want A(int a1,int b2=8) to get executed
    A b(3); // I want A(int a1) to get executed
    a.show();
    b.show();
    return 0;
} 
like image 335
Ashwyn Avatar asked May 29 '12 16:05

Ashwyn


People also ask

What is the difference between default constructor and default argument constructor?

A default constructor is a 0 argument constructor which contains a no-argument call to the super class constructor. To assign default values to the newly created objects is the main responsibility of default constructor.

Can we use default arguments with constructor?

Like all functions, a constructor can have default arguments. They are used to initialize member objects. If default values are supplied, the trailing arguments can be omitted in the expression list of the constructor.

What is ambiguity in constructor in C++?

ambiguous means the compiler found multiple “valid” choices and refused to make the choice for you. You need to add clarifying information (usually about types). It may be that the compiler is able to convert a value into a type that matches a constructor and can do this twice.

Is it possible to overload a default constructor in C++?

Constructor Overloading in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments.


1 Answers

First, answer this:

When you write A a(4), do you want a.b. to be:

Option a) 54

class A
{
    public:
    int a,b;
    A()
    {
        a=5;
        b=6;
    }
    A(int a1,int b2 = 54)
    {
        a=a1;
        b=b2;
    }
};    

Option b) 8

class A
{
    public:
    int a,b;
    A()
    {
        a=5;
        b=6;
    }
    A(int a1,int b2 = 8)
    {
        a=a1;
        b=b2;
    }
};    

The error is there for a reason. If you don't know what you want from the code, how can you expect the compiler to?

EDIT: After your edit - impossible. Not with that exact code.

like image 189
Luchian Grigore Avatar answered Sep 23 '22 17:09

Luchian Grigore