-
Friend functions ?
I had written this function [ total_tax() ] which takes an array of objects of type tax and does some calculations on the private members of objects of tax.
Code:
void total_tax (const tax *Tax)
{
float Total = 0, Tax_Value;
for (int i=0;i<300;i++)
Total += *(Tax + i)->charge ;
Tax_Value = .4 * Total;
cout <<"\n The total tax to be paid is "<<Tax_Value;
}
The friend function declaration in class tax is as follows
Code:
class tax
{
public:
tax();
tax(float);
virtual ~tax();
friend void total_tax (const tax*);
private:
float charge;
The main() is as follows..
Code:
void main()
{
int i = 0;
tax *Array[];
for (i=0;i<100;i++)
Array[i] = new tax (3000);
for (i=100;i<300;i++)
Array[i] = new tax (5000);
total_tax (Array);
}
This however doesn't compile. I get errors like
syntax error : missing ',' before '*'
left of '->charge' must point to class/struct/union
Please help.....my OOP test is on Saturday ....
-
1) left of operator -> needs to be a pointer not an object hence drop the *
2) in main array has no size!
3)in total_tax you pass as pointer to const tax yet you modify taxs state hence drop the const!
4)void main() is undefined behaviour. main() should always return an int.
fix those first.
-
Thankx.......
I removed the const but I still I don't understand why that was causing problems.
The pointers were in the array, and I was accessing a data member using the pointer, just accessing, so why could const be causing a problem ????
-
i misread it. const was fine. ignore that 1 but rest valid problems. you should not make this function a friend but instead access charge through an accessor function.
float GetCharge() const { return charge;}
then change...
Total += *(Tax + i)->charge
to
Total += (Tax + i)->GetCharge()
now friendship need not be granted to the function.