int MyInteger = 3;
int* getMyInteger()
{
return &MyInteger;
}
I'm using "int" as example... in my code I'm passing a quite complicated and huge class, so I prefer to send a pointer.
But I would like to say something like "yes, send the adreess of the variable but don't change its value" (just for security), "const" should do the job but I think it will say something like "don't change the adress of the pointer" (not the value itself).
It should be something easy to solve, but I don't find the clue. Do you know how I can do it?
Write a function returning a const reference to your class.
Then you will be able to call const methods, but you won't be able to change non const values (or call non const methods).
To get it to work correctly you have to be careful implementing the class: methods that change any values should not declared "const". Search for "const correctness" in Codeguru or www for more details.
code:
Code:
class T
{
public:
T(){};
virtual ~T(){};
void ConstMethod() const;
void Method2ChangeData();
};
class T g_t;
const class T& GetT(){return g_t;};
int main()
{
const class T& t = GetT();
t.ConstMethod(); // possible
t.Method2ChangeData(); // not possible => compiler error
}
Addition (since laserlight supposed a function returning a const <type> *):
Alternative function to get the const pointer:
Code:
const class T* GetT(){return &g_t;};
in main:
Code:
class T* t = GetT(); // not possible => compiler error
const class T* t = GetT(); // possible
t->ConstMethod(); // possible
t->Method2ChangeData(); // not possible => compiler error
With regards
Programartist
Last edited by ProgramArtist; June 19th, 2009 at 04:33 AM.
Reason: typo ...
Bookmarks