AsylumOfMind AsylumOfMind - 4 days ago 4
C++ Question

Using sleep and usleep interchangeably by creating a class that decides which one to use

How would I implement sleep and usleep in a header file. This is what I've tried so far and it isn't working. I am not quite proficient in c++ yet. I know that it is possible to do something similar in HTML by commenting out and each browser uses the code specific to it.

This is the sample I'm practicing with:

help.cpp

#include <iostream>
#include "pause.h"

using namespace std;


int main() {

pause p;

cout << "Hello";

p.pause(5000)

cout << " World";

}


Someone in another thread suggested using #ifdef #else #endif to get it to work between windows and linux/unix

pause.h

#ifdef _WIN32
#include <windows.h>


class pause
{
public:
void pause(unsigned milliseconds)
{
Sleep(milliseconds);
}
};

#else
#include <unistd.h>

class pause
{
public:
void pause(unsigned milliseconds)
{
usleep(milliseconds * 1000); // takes microseconds
}
};

#endif


Somehow though, I must have written the class incorrectly because running my .cpp file it is not recognizing the class or object I tried creating.

Error

Running /home/ubuntu/workspace/help.cpp
In file included from /home/ubuntu/workspace/help.cpp:2:0:
/home/ubuntu/workspace/pause.h:20:41: error: return type specification for constructor invalid
void pause(unsigned milliseconds)
^
/home/ubuntu/workspace/help.cpp: In function ‘int main()’:
/home/ubuntu/workspace/help.cpp:9:7: error: expected ‘;’ before ‘p’
pause p;
^
/home/ubuntu/workspace/help.cpp:13:1: error: ‘p’ was not declared in this scope
p.pause(5000)
^
/home/ubuntu/workspace/help.cpp:15:1: error: expected ‘;’ before ‘cout’
cout << " World";
^


Process exited with code: 1

Answer

You cannot have a member function as the same name as the class. pause is the class name, so compiler treats your pause function (pause::pause) as a constructor.

You can rename the class to say Pause and then p.pause will call Pause::pause function which is valid.

Comments