tricky return trick

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • grove
    New Member
    • Oct 2007
    • 2

    #1

    tricky return trick

    Hello, I have a small puzzle I cannot solve.

    In my class mnode, I have a private data member

    float data;

    In the constructor, it is given a value, so no worries. This puzzle is this: how can I return the value of data in the public function

    float& mnode::nodeData () const

    without changing the prototype of nodeData(). I cannot add a const modifier before the float& and I have to return the value of data.

    I hear there is some trick to doing this (it does not preserve polymorphism, or so I hear), but I do not know it.

    Anyone who knows this or can figure it out, please post an answer.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    What you are asking is horrible.

    First: The member function is const. That means anything it returns has to be const. You can return a float&.

    Why is it you can return a const float& ??

    Second: It is always bad news to return a reference to a data member. You have no guarantee that:
    a) the object will still be there when you get around yo using the refeence later
    b) returning a reference allows anyone to alter the private data member witrhout using a member function. This effectively removes all protection from the variable and renders your code unsafe.

    Third: You are not using polymorphism. What you are doing is breaking a fundamental rule of encapsulation.

    Fourth: I wash my hands of this but your solution is to write another member function that is not const.
    [code=cpp]
    float& mnode::nodeData ();
    [/code]

    Comment

    • grove
      New Member
      • Oct 2007
      • 2

      #3
      Thank you for the guidance.

      If I may ask a bit more, is there a way to do this that does not invole the creation of another member function?

      The puzzle said not to create another member function.

      Though it saddens me to say it, the "nifty solution" is supposed to kill polymorphism and information hiding--if my understanding of the question was clear.

      Is there another way solve this conundrum without the creation of another member function?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by grove
        The puzzle said not to create another member function.
        Then I have no idea. Some guys are respectable citizens and put their money in the bank and use a teller for deposits and withdrawals. Then there are the other guys who show up an night with a drill and do their own withdrawal.

        Unfortunately, I don't know many safecracking methods.

        Comment

        Working...