-1

I saw a code in sololearn platform(C++ course) and it is about defining overloading for operator +. you can see the code below:

#include <iostream>
using namespace std;

class Account {
    private:
        int balance=0;
        int interest=0;
    public:
        Account() {}
        Account(int a): balance(a) 
        {
            interest += balance/10;
        }
        int getTotal() {
            return balance+interest;
        }
        Account operator+(Account &obj){
            Account OBJ2;
            OBJ2.balance=this->balance + obj.balance;
            OBJ2.interest=this->interest +obj.interest;
            return OBJ2;
        }
        

};

int main() {
    int n1, n2;
    cin >> n1 >> n2;
    Account a(n1);
    Account b(n2);
    Account res = a+b;

    cout << res.getTotal();
}

My question is: why do we need to keep two constructors in class "Account"? I don't understand the reason of having the default constructor( the first one without any parameter). I tried to delete it but then the code does not work.

Thank you

sm75
  • 3
  • 2
  • 1
    If the default constructor did not exist, which constructor would you expect the following line in the shown code: `Account OBJ2;` -- which constructor do you expect to be used here? – Sam Varshavchik Oct 17 '22 at 02:13
  • C++ **must** be learnt using a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and not by some online *"sololearn platform(C++ course)"*. These **trivial** things are explained in any of the [beginner c++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) which are also available as PDFs for free. **Stackoverflow is not an introduction to C++**. For learning the basics one should refer to a book first. – Jason Oct 17 '22 at 03:38
  • Didn't the compiler produce an error message? That message should be in your question. Didn't the error message identify a line where the default constructor is needed? – JaMiT Oct 17 '22 at 06:37
  • Find a different source for learning C++. The code in the question is poorly written; definitely not something beginners should be using as a base for future work. – Pete Becker Oct 17 '22 at 12:33
  • Kindly introduce the source you have in mind for learning C++.Thank you. – sm75 Oct 18 '22 at 04:23

1 Answers1

2

Look at your operator+. The first line is:

Account OBJ2;

Without a default constructor, that line is illegal. You could avoid the need for the default constructor there by using the other constructor:

    Account operator+(const Account &obj) const { // Added const for correctness
        Account OBJ2(this->balance + obj.balance);  // Create with constructor taking int
        OBJ2.interest = this->interest + obj.interest;  // May be avoidable if constructor calculation known to be valid
        return OBJ2;
    }
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271