Tuesday, July 28, 2009

With C++, is it possible to declare a class and have access to the private member data just using the object?

With C++, is it possible to declare a class, lets say Counter which has a private member data called itsNumber. In the body of the program "int main(){}", Can itsNumber be accessed in any way without ussing a public accessor. for eg:





#include%26lt;iostream%26gt;


int main()


{


Counter i;


std::cout%26lt;%26lt;i; // Where it displays itsNumber


return 0;


}

With C++, is it possible to declare a class and have access to the private member data just using the object?
No, you cannot access it directly. You need either an accessor or a friend function.





In your example,


class Counter {


// public functions not listed


private:


int i;


// Here we allow operator %26lt;%26lt; to access private members


friend ostream%26amp; operator %26lt;%26lt; (ostream%26amp; os, Counter%26amp; c);


};





then you can write a function that outputs the object onto a stream.





ostream%26amp; operator %26lt;%26lt; (ostream%26amp; os, Counter%26amp; c)


{


return os %26lt;%26lt; c.i;


}
Reply:I'm not sure about c++ but with c# you could overload the ToString() method to do exactly this for a class. Perhaps c++ has something of that nature.

elephant ear

No comments:

Post a Comment