Looks like I miss something, so I need your help, guys.

#include <iostream>

using namespace std;

int main() {

    int* ptr=new int(2);
    const int* constPtr=ptr;

    int** ptr2;
    //... do memory stuff for ptr2
    const int** constPtr2=ptr2; 

    typedef int** intPtr;
    const intPtr ptr3 = ptr2;

    return 0;
}

Questions:
1. Line #8 works (at least my compiler doesn't comply), but line #12 is not allowed. Why?
2. Line #15 is equal to int** const . I thought it should be rather const int** .

you need to type cast it:

const int** constPtr2=(const int**)ptr2;

>1. Line #8 works (at least my compiler doesn't comply), but line #12 is not allowed. Why?
Because the types are incompatible. It's legal to add a const qualifier as such:

int *p = 0;
const int *q;

q = p; // Okay

Note that p and q have the same type (pointer to non-const int). However, if you add a level of indirection, things get sticky:

int **p = 0;
const int **q;

q = p; // Bzzt! Type mismatch

Now const is a type qualifier, it actually changes the type of the object. As such, int* and const int* are two different types. Here's where your error comes in. When you declare a pointer to a type, the pointer is more or less required to point to an object of that type. So let's look at the code again:

// p is a pointer that points to an object of type int*
int **p = 0;
// q is a pointer that points to an object of type const int*
const int **q;

// const int* and int* are different types, thus
// q and p point to different types and are incompatible
q = p; // Bzzt! Type mismatch

>2. Line #15 is equal to int** const . I thought it should be rather const int**.
When you create a typedef, the type is set in stone. Any qualifiers applied after that apply to the typedef as a whole. For typedef int **intPtr , adding const will qualify the type as a whole, which means the top level pointer becomes const (ie. int** const ). const can't be added to the underlying object being pointed to ( const int** ), because that would have to alter the type specified by intPtr.

Thx a lot. Everything is clear, now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.