Search code examples
c++constantsdouble-pointer

Return a read-only double pointer


I want to a member variable, which is a double pointer. The object, the double pointer points to shall not be modified from outside the class.

My following try yields an "invalid conversion from ‘std::string**’ to ‘const std::string**’"

class C{

public:
    const std::string **getPrivate(){
        return myPrivate;
    }

private:
    std::string **myPrivate;
};
  • Why is the same construct valid if i use just a simple pointer std::string *myPrivate
  • What can i do to return a read-only double pointer?

    Is it good style to do an explicit cast return (const std::string**) myPrivate?


Solution

  • Try this:

    const std::string * const *getPrivate(){
        return myPrivate;
    }
    

    The trouble with const std::string ** is that it allows the caller to modify one of the pointers, which isn't declared as const. This makes both the pointer and the string class itself const.