[Solved] c++ program that returns half of an object [closed]


There are lots of mistakes in your code. Many of them look like typos, but the serious errors are

Not using the template parameter T in your function signature. This is the reason half(tb) did not compile since your version of half always expected an int.

Not understanding that in your constructor student = student; is just assigning a variable to itself. You can ensure that the class variable gets assignied by prefixing this-> to the name of the class variable (or you can just ensure that the class variable and parameter names are different as with ammount and amt.

You might also check out the difference between assignment (what you are doing in your constructor) and initialisation (what you should be doing in your constructor).

Below is a working version of your code

#include<iostream>
#include<string>
using namespace std;

template <class T>
double half(T x)
{
    double h = x / 2;
    return h;
}

class TuitionBill
{
    friend ostream& operator<<(ostream&, const TuitionBill&);
private:
    string student;
    double amount;
public:
    TuitionBill(string, double);
    double operator/(int);
};

TuitionBill::TuitionBill(string student, double amt)
{
    this->student = student;
    amount = amt;
}

double TuitionBill::operator/(int factor)
{
    double half = amount / factor;
    return half;
}

ostream& operator<<(ostream& o, const TuitionBill& t)
{
    o << t.student << "  Tuition: $" << t.amount;
    return o;
}

int main()
{
    int a = 47;
    double b = 39.25;
    TuitionBill tb("Smith", 4000.00);
    cout << "Half of " << a << " is " << half(a) << endl;
    cout << "Half of " << b << " is " << half(b) << endl;
    cout << "Half of " << tb << " is " << half(tb) << endl;
    return 0;
}

solved c++ program that returns half of an object [closed]