List of all available Websheets
Viewing cpp/cs104/classes/const_return by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
Property | Value |
---|---|
Description html markup shown to student | In this example, we use a <tt>getValue</tt> function that returns a reference to the internal data member. When returning a reference we demonstrate the need for two versions of the function. One <tt>const</tt> and the other non-<tt>const</tt> if we want to allow the client to change the data member via the reference. <p> We illustrate the need for both versions through two functions: <tt>increment_it</tt> and <tt>print_it</tt> which pass an Item via non-<tt>const</tt> and then <tt>const</tt> reference. <p> In <tt>increment_it</tt> you see the chain of <tt>set</tt>/<tt>get</tt> that is needed. But if you realize the function is returning a reference, you can simplify this code. Please attempt to do so. <p> Also compile/submit the code to see why the type of reference returned by the <tt>const</tt> version must also be <tt>const</tt> |
Remarks Comments, history, license, etc. | Copied from problem cpp/cs104/classes/const_members2 (author: redekopp@usc.edu) Copied from problem cpp/cs104/classes/const_members (author: redekopp@usc.edu) Copied from problem cpp/cs104/classes/this_scope (author: redekopp@usc.edu) |
Engine | |
Template / Reference solution |
using namespace std; class Item { public: // notice the two versions of getValue() // this is the non-const version int& getValue() { cout << "non-const" << endl; return value; } // this is the const version...what should it return \[ REDACTED \show: int &]\ getValue() const { cout << "const" << endl; return value; } void setValue(int val) { this->value = val; } private: int value; }; void increment_it(Item& i) { \[ REDACTED \show: // how could we do this using // the non-const getValue() i.setValue(i.getValue() + 1); ]\ } // experiment void print_it(const Item& i) { \[ REDACTED \show: cout << i.getValue() << endl; ]\ } int main() { Item x; x.setValue(2); increment_it(x); print_it(x); return 0; } |
C++ test suite json list of stdin/args tests e.g. [{"stdin":"hi", "args":["4", "5"]}, {"stdin":"noargs"}] to just run once with no input use [{}] | [{}] |
Is example? i.e., just a demo | |
Remove default compiler flag(s) | ["-Wno-shadow", "-Wno-self-assign"] |
Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.