Const Correctness/Private Member Variables

Good Morning,

I hope I explain this properly but if I don't please tell me...

I need to return a const pointer to a const object from a method, however the object that I am returning is not constant internally as it can be modified in the class it is declared in.

(Please ignore the fact that constructor etc.. is missing, this is just a quick example)

1
2
3
4
5
6
7
8
9
10
11
12
13

class A
{
     private:
          SomeClass *sc;  // can't be const object as needs to be modifable internally

          void SomeMethod() { if(sc == NULL) sc = new SomeClass(); }

     public:
          const SomeClass* get( return sc; ); // can't be reference as may be NULL

};


Is this possible at all and if so please could you provide an example?

Thank you in advance for any help that you give.

Phil.
That will work, but the caller will have to check the returned pointer.
Thank you for the quick response. Will the example I posted prevent the user from modifying the object as well? I need the object to be constant as well as the pointer.

Many thanks,

Phil.
You'll return a copy, so the member can't be modified. The object also can't be modified.
Topic archived. No new replies allowed.