1

I'm trying to overload the increment operator++ in my class But it tells me no matching function for call to person::person(int&).

The error occurs at line 22 here is my header file

#include <string>
class person
{
private:
    std::string name;
    int age;
public:
    //Setters
    void set_name(std::string name_set);
    void set_age(int age_set);
    //Getters
    std::string get_name();
    int get_age();
    //Constructors & Destructor (Overloaded Constructor)
    person();
    person(std::string ini_name,int ini_age);
    //Operator Overloading
    person operator ++(int)
    {
        age++;
        return person(age);
    }
};

here is the cpp file

#include "person.h"
//Setters Definition
void person::set_name(std::string name_set){name = name_set;}
void person::set_age(int age_set){age = age_set;}
//Getters Definition
std::string person::get_name(){return name;}
int person::get_age(){return age;}
//Constructors & Destructor (Overloaded Constructor)
person::person(){name = "Null",age = 0;}
person::person(std::string ini_name,int ini_age):
   name(ini_name),age(ini_age)
{}

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Ahmed
  • 13
  • 4
  • That's not how the postfix increment operator should be written, check your book. Anyhow, the error clearly states the problem. There's no constructor taking only an int as input. But, like I said, the whole function should be written differently. – JHBonarius Jun 01 '21 at 09:42
  • 2
    You haven't provided a `person` constructor that takes a single `int` argument. (You have one that takes a `string` and an `int`, and the default constructor, but not the required one.) – Adrian Mole Jun 01 '21 at 09:43

1 Answers1

3

The postfix increment is supposed to increment this and return the value before the increment. You get the error because there is no constructor for person taking an int. You can fix that by:

person operator++(int)
{
    person temp{name,age};
    age++;
    return temp;
}

Though better would be to provide a copy constructor and typically postfix increment can be implemented in terms of prefix increment:

// prefix
person& operator++() {
    age++;
    return *this;
}

// postfix
person operator++(int) {
    person temp = *this;  // needs copy constructor
    ++*this;
    return temp;
} 

For more details on operator overloading I refer you to What are the basic rules and idioms for operator overloading?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185