Home > OS >  C class question: why this "get" method exists
C class question: why this "get" method exists

Time:02-05

In my textbook on the chapter introducing classes it gives this example class:

class clockType
{
public:
    void setTime(int, int, int);
    void getTime(int&, int&, int&) const;
    void printTIme() const;
    void incrementSeconds();
    void incrementMinutes();
    void incrementHours();
    bool equalTime(const clockType&) const;
private:
    int hr;
    int min;
    int sec;
};

The definition of getTime is

void clockType::getTime(int& hours, int& minutes, int& seconds) const
{
    hours = hr;
    minutes = min;
    seconds = sec;
}

What is the purpose of this getTime function? It's not returning anything to the caller, so I it doesn't seem useful to the user. Also, you pass in parameters but then the arguments are assigned to the private member variables? That also doesn't make sense to me.

CodePudding user response:

You are passing to your function getTime 3 references and these in the getTime function are filled with the private time values. Then once this function is called you will be able to access the time values ​​simply by using the variables you passed by reference. Note that unless you create a Time object that contains these three integers, there is no direct way to return three integers in C .

CodePudding user response:

The function takes reference arguments. Which means it takes the variables' memory addresses and edits them.

void example(int& b){
    b=5;
}

int main(){
    int myVar = 0;
    example(myVar);
    std::cout << myVar; // Expected output is 5
}
  •  Tags:  
  • Related