Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition of default argument on redeclaration makes this constructor a default constructor

Tags:

c++

It says the addition of default argument on redeclaration makes this constructor a default constructor.

I did some research on it but I just don't understand what I need to do to fix this issue.

struct Transaction{
    int type;
    int amount;
    int to_from_type;
    Transaction(int, int, int);
};

Transaction :: Transaction(int type=0, int amount=0, int etc=0)
{
    this->type=type;
    this->amount=amount;
    this->to_from_type=etc;
}




 Transaction :: Transaction(int type=0, int amount=0, int etc=0) //I am getting an error at this code and I cannot fix it.

    {
        this->type=type;
        this->amount=amount;
        this->to_from_type=etc;
    }

I am not an expert in C++ and would love to get some help with my code.

like image 973
Toni Avatar asked Apr 29 '19 02:04

Toni


People also ask

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 the default type of argument used in constructor?

The default constructor with argument has a default parameter x, which has been assigned a value of 0.

What's the difference between default constructor and constructor with default arguments?

A Default constructor is defined to have no arguments at all as opposed to a constructor in general which can have as many arguments as you wish.

What is the benefit of giving a constructor with default arguments?

Supplying default constructor parameters has at least two benefits: You provide preferred, default values for your parameters. You let consumers of your class override those values for their own needs.


1 Answers

XCode is using a combination of CLang and Apple LLVM to compile your C++ code. Clang enforces a few additional checks which includes your case. What happened here is you defined a constructor to accept 3 params but your implementation can be called without any, meaning, your implemented one is actually carrying the same method signature (method name and param list) as the implicit default constructor and the one with 3 params (the one defined inside the struct) is getting left out in the eyes of your compiler. The fix is easy:

struct Transaction{
    int type;
    int amount;
    int to_from_type;
    Transaction(int=0, int=0, int=0);
};

Transaction :: Transaction(int type, int amount, int etc)
{
    this->type=type;
    this->amount=amount;
    this->to_from_type=etc;
}
like image 181
Faisal Rahman Avash Avatar answered Sep 19 '22 23:09

Faisal Rahman Avash