IAE IAE - 1 year ago 105
C++ Question

How to Access a Private Variable?

This question isn't meant to sound as blatantly insulting as it probably is right now.

This is a homework assignment, and the spec sheet is scarce and poorly designed to say the least. We have a function:

double refuel( int liter, GasStation *gs )
{
// TODO: Access private variable MaxFuel of gs and decrement.
}


Sound simple enough? It should be, but the class GasStation comes with no function that accesses the private variable MaxFuel. So how can I access it anyway using the function refuel?

I'm not considering creating a function
setFuel( int liter )
because the teacher always complains rather energetically if I change his specification. So... I guess I have to do some sort of hack around it, but I'm not sure how to go about this without explicitely changing the only function in GasStation and giving it a parameter so that I can call it here.

Any hints perhaps?

sbi sbi
Answer Source

Now that sounds like a real lousy homework assignment.

Anyway, I can think of three ways to access private data:

  1. through public member functions
  2. by a friend of the class
  3. cheating:

    #define private public 
    #include "the_class.h"
    #undef private
    

The first two are legal, but require you to change the class. The last is "non-intrusive" (for some definition of "non-intrusive", anyway), but is definitely illegal (although I have yet to see a compiler were it wouldn't work).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download