Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created January 16, 2023 22:16
Show Gist options
  • Select an option

  • Save EteimZ/f293b34d5e5ce613ae150ccdb50252fa to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/f293b34d5e5ce613ae150ccdb50252fa to your computer and use it in GitHub Desktop.
Demonstrating the dangerous effect of returning a reference from a class. Gotten from the book C how to program.
#include <iostream>
using std::cout;
using std::endl;
#include "Time.h"
int main(){
Time t; // create Time object
// initialize hourRef with the reference returned by badSetHour
int &hourRef = t.badSetHour( 20 ); // 20 is a valid
cout << "Valid hour before modification: " << hourRef;
hourRef = 30;
cout << "\nInvalid hour after modification: " << t.getHour();
// Dangerous function call that returns
// a reference caan be used as a lvalue!
t.badSetHour( 12 ) = 74;
cout << "\n\n**********************************************\n"
<< "POOR PROGRAMMING PRACTICE!!!!!!!!!\n"
<< "t.badSetHour( 12 ) as lvalue, invalid hour: "
<< t.getHour()
<< "\n**********************************************" << endl;
return 0;
}
#include "Time.h"
Time::Time(int hr, int min, int sec){
setTime(hr, min, sec);
}
void Time::setTime(int h, int m, int s){
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
}
int Time::getHour(){
return hour;
}
// Poor programming practice:
// Returning a returning to a private data member
int &Time::badSetHour( int hr ){
hour = ( hr >= 0 && hr < 24 ) ? hr : 0;
return hour; // It is dangerous to return reference
}
#ifndef TIME_H
#define TIME_H
class Time{
public:
Time( int = 0, int = 0, int = 0);
void setTime(int, int, int);
int getHour();
int &badSetHour( int ); // It is dangerous to return a reference from a class
private:
int hour;
int minute;
int second;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment