hecate
hecate

Reputation: 632

Passing 'const' pointer which points to another pointer in c++

The following code fails to compile with two errors on the line 'func(&pobj);' stating "Cannot convert 'X * *' to 'const X * *' in function main()" and "Type mismatch in parameter 1 (wanted 'const X * *', got 'X * *') in function main()" even though its the correct way to pass pointer parameters. And also on commenting this particular line i.e 'func(&pobj);' and uncommenting the two lines above it which declares a new 'const' pointer 'pp' of required type (in parameter of func) but still throws an error on the line which declares and assigns 'pp' saying "Cannot convert 'X * *' to 'const X * *' in function main()".

using X = int;

void func(const X **);

int main() {
    X *pobj = new X(58);

    // const X **pp = &pobj;  // ERROR
    // func(pp);

    func(&pobj); // ERROR
}

I believe that this is the correct way to pass constant pointers as parameters and I just don't understand why the program fails to compile. Can anyone point out the fault in the code above and suggest me the correct logic/syntax if I am wrong? Thanks in advance.

UPDATE: This question was marked as duplicate but it doesn't have the answer that solves the problem at hand. Thus I would love it if the Stack Overflow community would help me to solve my problem here. Thanks.

Upvotes: 1

Views: 174

Answers (3)

Roland
Roland

Reputation: 336

If the answer of Ajay is not appropriate, because You cannot change the interface of func(),

and if the answer of Kerrek does not work, because func() changes the pointer, which must be assigned back, that does not happen:

X * p = new X(58);
const X * q = p;
func(&q);
p = q;   // errror

then simply use a cast:

func(const_cast<const X**>(&p))

Upvotes: 0

Ajay
Ajay

Reputation: 18411

You will need to apply const to pointer-to-pointer:

void func(X *const *);

...
     X * const *pp=&pobj; // ERROR    
     func(&pobj); // ERROR
...

void func(X * const * obj) { // module code goes here
}

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 476990

Do this:

const X * pobj = new X(58);
// ^^^^^^

func(&pobj);

Now pobj is a pointer-to-const-X, and its address is of type const X ** as required.

If you want to retain the original (mutable) pointer, you need to make a new const pointer first:

X * p = new X(58);
const X * q = p;

func(&q);

Upvotes: 2

Related Questions