Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why objects cannot be created without using class-keyword?

Tags:

c++

class

g++

The following C++ code gives an error while compiling:

#include<iostream>

using namespace std;

class time
{
        int hours;
        int minutes;
    public:
        void gettime(int h, int m)
        { hours = h; minutes = m; }

        void puttime(void)
        {
            cout << hours << " hours and ";
            cout << minutes << " minutes " << "\n";
        }

        void sum(time, time);
};

void time::sum(time t1, time t2)
{
    minutes = t1.minutes + t2.minutes;
    hours = minutes/60;
    minutes = minutes % 60;
    hours = hours + t1.hours + t2.hours;
}

int main()
{
    time T1, T2, T3; // LINE NUMBER 32.

    T1.gettime(2, 45);
    T2.gettime(3, 30);

    T3.sum(T2, T2);

    cout << "T1 = "; T1.puttime();
    cout << "T2 = "; T2.puttime();
    cout << "T3 = "; T3.puttime();

    return 0;
}

The following error, I am getting:

habeebperwad:~/study/cpp/eb$ g++ 5.7-objects-as-arguments.cpp
5.7-objects-as-arguments.cpp: In function ‘int main()’:
5.7-objects-as-arguments.cpp:32:7: error: expected ‘;’ before ‘T1’
5.7-objects-as-arguments.cpp:34:2: error: ‘T1’ was not declared in this scope
5.7-objects-as-arguments.cpp:35:2: error: ‘T2’ was not declared in this scope
5.7-objects-as-arguments.cpp:37:2: error: ‘T3’ was not declared in this scope
habeebperwad:~/study/cpp/eb$ 

If I add class before the statement 'time T1, T2, T3;', it is works fine.

Why it is not working without the class?

like image 555
Mohammed H Avatar asked Mar 25 '12 14:03

Mohammed H


1 Answers

Your compiler defines std::time, thus it is expecting either time(...); or time;. The class name time is ambiguous, so the keyword class is needed. To prevent this don't use using namespace std; or rename your class.

Don't forget to add the namespace qualifier std:: to cout if you drop using namespace std;.

I recommend to enable all compiler warnings (-Wall -Wextra in g++) to prevent such errors in the future, as GCC hints that there's something wrong:

temp.cc:33:20: Warning: Expression is a reference, not a call, of function »time« [-Waddress] temp.cc:33:20: Warning: Expression has no effect [-Wunused-value]

like image 119
Zeta Avatar answered Oct 22 '22 16:10

Zeta