1

What is the exact difference between

typedef class abc* abcp;  
typedef const class abc* constAbcp ; 

const abcp a1 ;  ------- 1 
constAbcp  a2 ;  ------- 2

what is the difference between 1 and 2    
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Avinash Kumar
  • 739
  • 2
  • 10
  • 25

3 Answers3

2
a2 is pointer to constant.
a1 is constant pointer.

a2->nonConstFunc(); // Bad
a1 = a2; // Bad

a1->nonConstFunc(); // OK
a2 = new_a2; // OK

Example:

struct abc {
  int foo;
};

typedef abc* abcp;  
typedef const abc* constAbcp ;

abc temp[5];

const abcp a1 = temp;
constAbcp  a2 = temp;

a1->foo = 5; // OK
a2->foo = 5; // Bad(Compile error)

a1++;  // Bad
a2++; // OK

Live example here


Closely related C question: what does this 2 const mean?

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0
const abcp a1 ;   
const Abcp  a2 ; 

a1 is a pointer to a constant of type abcp

a2 is a constant pointer to a constant of type Abcp

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

As is mentioned by the other answerers, a1 is a constant pointer. Meaning that the address cannot be changed.

const abcp a1;

Simplifies to:

abc* const a1;

Which frankly is nonsense cause you now have a pointer that is uninitialized and cannot be changed. So any assignment to it is illegal. For example you can't do this: a1 = NULL;.

Also mentioned by the other answerers, a2 is a pointer to a constant. Meaning that the value addressed cannot be changed.

constAbcp a2;

Simplifies to:

const abc* a2;

This does make sense, because you can assign to a2 all you want, it's just that you can only use it to read the value it references. You cannot use it to write to the value it references.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288