What is the output of the following C++ program?
[gamipress_button type=”submit” label=”Run Code Online” onclick=”window.open(‘https://coderseditor.com’,’_blank’)”]
#include <iostream> using namespace std; class Fraction { private: int den; int num; public: void print() { cout << num << "/" << den; } Fraction() { num = 1; den = 1; } int &Den() { return den; } int &Num() { return num; } }; int main() { Fraction f1; f1.Num() = 7; f1.Den() = 9; f1.print(); return 0; }
Studently Changed status to publish October 10, 2022
7/9
Num() and Den() both return references to num and den, respectively. Because references are returned, the values can be used as lvalues, and the private members den and num are modified. Although the programme compiles and runs correctly, this type of class design is strongly discouraged. Returning a reference to a private variable allows class members to directly change private data, which defeats the purpose of encapsulation.
Studently Changed status to publish October 10, 2022