Compilation Error

Hi,

I am getting compilation error in this code, i am unable to find, what's wrong. kindly help.

Compilation error is
7.cpp:36: error: expected ‘;’ before ‘t1’
7.cpp:38: error: ‘t1’ was not declared in this scope
7.cpp:39: error: ‘t2’ was not declared in this scope
7.cpp:44: error: ‘t3’ was not declared in this scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;

class time {
        int h;
        int m;
    public:
        void getdata(int a, int b)
        {
                h = a;
                m = b;
        }
        void putdata(void)
        {
                cout << h << " " << m << endl;
        }
        void sum(time,time);
};

void time :: sum(time t1, time t2)
{
        int p = t1.h + t2.h;
        int q = t1.m + t2.m;

        p += q/60;
        q %= 60;

        h = p;
        m = q;
}

int main()
{
        time t1, t2, t3;

        t1.getdata(2,45);
        t2.getdata(3,30);

        t1.putdata();
        t2.putdata();

        t3.sum(t1,t2);

        t3.putdata();

        return 0;
}
I think the problem is this line:

using namespace std;

as there's a function named time() in the standard library.
You can't give a class the same name as an existing function and a time function already exists in the standard library:
http://www.cplusplus.com/reference/clibrary/ctime/time/
Thanks a lot filipe and Athar. I replaced time by time1 and now it is running successfully.
A better solution would be to remove the line using namespace std;. It pollutes the global namespace as you just discovered.
An even better alternative would be to make another namespace for the time class, say, cstm (custom):
1
2
3
4
5
namespace cstm
{
    ...
}
using cstm::time;
closed account (z05DSL3A)
+1 Galik
Topic archived. No new replies allowed.