5

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?

Ken White
  • 123,280
  • 14
  • 225
  • 444
Hugo
  • 53
  • 4
  • Sorry for not being clear, i edited my post. Its the string itself that shall not be modified. – Hugo Jun 08 '11 at 19:33
  • 2
    Thinking of them as "double pointers" may be the root of your problem. The term "double pointer" is one I never encountered until I came across SO, and I'd be kind of interested to know which nitwit (not necessarily on SO) originated it. –  Jun 08 '11 at 19:45
  • Also, with regards to your last sentence, it's rarely good style to do an explicit cast. Casting may be necessary but is never stylish. – David Thornley Jun 08 '11 at 19:50
  • A "double pointer" is not a thing in C++. What you're playing with here is a "pointer to pointer". – mlp Jul 15 '19 at 16:19

3 Answers3

3

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.

James Johnston
  • 9,264
  • 9
  • 48
  • 76
2

If you want to be really picky :

class C {

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

private:
    std::string **myPrivate;
};
user703016
  • 37,307
  • 8
  • 87
  • 112
2

There are very rare cases in c++ when a raw pointer (even less for a double pointer) is really needed, and your case doesn't seams to be one of them. A proper way would be to return a value or a reference, like this :

class C{

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

private:
    std::string myPrivate;
};
BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • This would have been my preferred way as well - especially with a string, but I didn't know if the poster had some other type that might have actually required this... – James Johnston Jun 08 '11 at 20:03
  • Perhaps i should have written my Motivation: I want to have access to an array with two indices x[0][1], so i created an array of pointers. But although it might have been possible to change my code in another position i wanted to know how to handle "double-pointers" or hower a pro calls pointers-to-pointers. – Hugo Jun 13 '11 at 07:53