Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
class payroll
{
    float salary;
public:
    payroll(float f)
    {
        salary=f;
    }
    void show_salary()
    {
        cout<<"salary="<<salary;
    }
    payroll operator+(payroll);
};
payroll payroll::operator +(payroll p)
{
    payroll p2;
    p2.salary=salary+p.salary;
    return p2;
}
void main()
{
    payroll anil(1200),deepak(1300),acct;
    acct=anil+deepak;
    acct.show_salary();
}

getting error : no appropriate default constructor available.
Posted
Updated 17-Nov-10 13:16pm
v2

The error message tells you. You don't have a constructor payroll() with no arguments*, yet you are trying to implicitly call one at two places in your code. If you add the lines
payroll()
{
  salary = 0.0;
}
to your class (say, before the definition of operator+), then it should all work.

* A constructor with no arguments is called a default constructor.

Peter
Vote for answers, and mark accepted if appropriate.
 
Share this answer
 
v2
Peter_in_2780 is reading my mind.
And a constructor payroll() without arguments is not necessary if you code as payroll p2(salary+p.salary);. The default constructor is for statements like payroll p2;.
 
Share this answer
 
You only have the following constructor:
payroll:payroll(float f)


This means that out of the following instantiations in your code:
payroll anil(1200),deepak(1300),acct;

only the first two are valid.

The first two are valid because of the constructor I quoted above has a float parameter.
You can either remove the last one:
payroll anil(1200), deepak(1300)

or add a default constructor:
class payroll
{
    float salary;
public:
    payroll()
    {
        salary=0.0f;
    }
    payroll(float f)
    {
        salary=f;
    }
    void show_salary()
    {
        cout<<"salary="<<salary;
    }
    payroll operator+(payroll);
};


NOTE: If you hadn't had any constructors the compiler would have added a default constructor, but since you have one it doesn't bother and you have to code it yourself.
 
 
Share this answer
 
v3
Hi,
As everybody already said, you miss a constructor without parameter.

Changing to:
public:
    payroll(float f = 0.) // can be called without param
    {
        salary = f;
    }

should be enough :)
cheers,
AR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900