Can I read the value of a private class member directly with its object name?

I can define a class like:

class SpecialInt {
int value;
public:
....
int getValue () { return value; };
SpecialInt& operator=(const int n);
};

SpecialInt& SpecialInt::operator=(const int n) {
value = n; // Do the assignment operation!
return *this; // Return a reference to myself.
}

and I can use it like:

SpecialInt si;
si=100;

but what if I want:

SpecialInt si;
int z;

si=100;
z = si.getValue(); <---- I DON'T WANT TO USE getValue()
z=si; <---- I WANT TO USE ITS OBJECT NAME

Is it possible to read value without using getValue()?

Thanks for help

You need to write operator int() const { return value; }

However, casting operators are in general evil and lead to headaches.

Why do you want to do this?
Thanks for your help and your warning.

The class is simple, it has only a public member to serialize itself to disk and so I'd like to use the object like any other predefined integer variable.

Thanks again.
If it only has a method (is that what you meant?) to serialize itself, wouldn't that be better suited as a function?
Yes, but it's only the simplest class and in the program there are different classes more sofisticated and I'd like to know how to do it. I learnt a new thing.
Casting operators are quite risky. Casts in general are risky. (Whoever came up with const_cast...) But you can write a new operator overload where the first operand is an integer and the second is your class type. That should work fine for you.
no for private members u will have to return a copy of them. u cannot use directly.. this is special feature added in c++.. why u want to use them directly if yes.. make them public
This is not a special feature added in C++; it's an inherent concept of OO. (If you mean from C, you may be right, but C was a bit lacking compared to C++ in most respects.) The point is to encapsulate the class; to hide implementation from the user.

tummychow
.... But you can write a new operator overload where the first operand is an integer and the second is your class type. ...


What you mean is what said jsmith?
operator int() const { return value; }


Sorry but I am not very good in c++, I come from delphi.
Topic archived. No new replies allowed.