Demonstrate returning a reference to a private data member with member function - C++ Class

C++ examples for Class:Member Field

Description

Demonstrate returning a reference to a private data member with member function

#include <stdexcept> 
using namespace std; 

class Time 
{ 
public: 
    Time( int = 0, int = 0, int = 0 ); 
    void setTime( int, int, int ); 
    int getHour(); 
    int &badSetHour( int ); // DANGEROUS reference return 
private: 
    int hour; 
    int minute; 
    int second; 
};


Time ::Time( int hr, int min, int sec ) 
{ 
    setTime( hr, min, sec ); 
}

void Time::setTime( int h, int m, int s ) 
{ 
    // validate hour, minute and second 
    if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) && ( s >= 0 && s < 60 ) ) 
    { 
        hour = h; 
        minute = m; 
        second = s; 
    }
    else 
        throw invalid_argument( 
            "hour, minute and/or second was out of range" ); 
}

int Time ::getHour() 
{ 
    return hour; 
}

//Returning a reference to a private data member. 
int &Time::badSetHour( int hh ) 
{ 
    if ( hh >= 0 && hh < 24 ) 
        hour = hh; 
    else 
        throw invalid_argument( "hour must be 0-23" ); 

    return hour; // DANGEROUS reference return 
}

Related Tutorials