1

I made a code to convert time into minutes and seconds using constructor. In output I'm getting time in seconds but its not displaying time in minutes and can't figured out my mistake so anyone can help me out...

#include<iostream>
using namespace std;

class Time
{
public:
    Time(int);
    Time(float);
};

Time::Time(int t)
{
    cout << "Time in seconds: " << t*60*60 << "\n";
}
Time::Time(float t)
{
    cout << "Time in Minutes: " << int(t*60) << "\n";
}

int main()
{
    int hr;
    cout << "Enter the time in Hours: ";
    cin >> hr;
    Time t1(hr);
    Time t2(float(hr));
}
David Schwartz
  • 179,497
  • 17
  • 214
  • 278

4 Answers4

3

You aren't typecasting correctly. You need to typecast by putting the desired type in parentheses, not by trying to use it as a function. For example, you'd need to do this:

Time t2((float) hr);

cout << "Time in Minutes: " << (int) t*60 << "\n";

While Time t2(float(hr)); is legal, it's a function prototype because this is a vexing parse. It is equivalent to Time t2(float hr);, which means that t2 is a function that takes a float called "hr" and returns a Time. This has no effect since such a function is never implemented or called.

If this seems absurd, here's a way to think about it that can help. Consider this code:

Time t2 (float (*hr));

Clearly this is a perfectly normal way to declare t2 as a function that takes a pointer to a float called "hr". Well, shouldn't it also be legal without the *? And the C++ grammar rule is that if something can be a prototype, it is.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
Christian
  • 19,605
  • 3
  • 54
  • 70
  • I thought int(..) was a constructor for an integer type ? why is it not correct to us it here ? – vib Apr 15 '15 at 08:16
  • for instance there no difference seems to be made before int(..) or (int) .. ? http://www.cplusplus.com/doc/tutorial/typecasting/ (as pointed out in the comment that just got removed) – vib Apr 15 '15 at 08:25
  • But we are using constructors for time. and it doesn't show that it's a constructor and the variable are also not declared like this...?? – Attiqa Tariq Apr 15 '15 at 08:31
  • 1
    You aren't typecasting correctly. You need to typecast by putting the desired type in parentheses, not by trying to use it as a function. - The functional programming cast is equivalent to the c cast – Otomo Apr 15 '15 at 12:46
1

Should works :

Time t2((float)hr);
Alex
  • 11
  • 1
0
Time::Time(int hour){
    cout << "Time in seconds: " << hour*60*60 << "\n";
    cout << "Time in minutes: " << hour*60 << "\n";
}
shA.t
  • 16,580
  • 5
  • 54
  • 111
deanone
  • 109
  • 1
  • 3
-1

try adding

Time::Time(float t)
{
    cout << "Time in Minutes: " << float(t*60) << "\n";
}

tell me if it works..

shrikul
  • 73
  • 6