Why is this not a valid friend?

1
2
3
4
5
6
7
8
9
10
11
class Clock {
  public:
    friend void regulateTime();
    //some member functions...
  private:
    /int foo, bar;
};

void regulateTime() {
//something that uses foo and bar...
}


So what am I missing here?
You need an object.

You can't access foo and bar without an object. Each Clock has its own foo and bar. Which ones are you trying to access? Which Clock's?

1
2
3
4
5
6
7
8
9
10
11
12
13
class Clock {
  public:
    friend void regulateTime(Clock& obj);
    //some member functions...
  private:
    int foo, bar;
};


void regulateTime(Clock& obj)
{
  // now you can access obj.foo and obj.bar just fine
}



ALTHOUGH!!!

Why is this a friend function? Wouldn't it make more sense to make it a member function?
Aha, so that explains it! So basically, this would be a step in the right direction?
void regulateTime(Clock& aClock)

This is my class:

1
2
3
4
5
6
7
8
9
10
11
class Clock {
public:
  Clock (int, int, int);
  Clock(const Clock& aClock) {}
  ~Clock() {}
  void getTime() const;
  void setTime(int, int, int);
  void increaseTime(int, int, int);
private:
  int myHour, myMinute, mySecond;
};


Fairly simple: after our constructors and destructors you have a function that lets you see the time for an object, one that (re)sets time for an object, one that will increase time and the three member variables.

regulateTime() looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
void regulateTime() {
  if (mySecond >= 60) {
    int s = mySecond % 60;
    myMinute += mySecond / 60;
    mySecond = s;
    
    if (myMinute >= 60) {
      int m = myMinute % 60;
      myHour +=  myMinute / 60;
      myMinute = m;
    }
  }
}


And its purpose is to be used within other member functions. I wanted to merely try to get familiar with friendship in C++ which is why I made it a friend. Initially, it's naturally a private member function.
Last edited on
Topic archived. No new replies allowed.