const int *

hi all and happy new year,

i have this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template<class T>
class A
{
private:
	int t;
	T typevar;
public:
	A() {t=1;};
	void set(const T a){typevar=a;};

};

void main( void )
{
A <int *> a;
const int * x=new int(1);
a.set(x);

int k;
cin>>k;
}


that produce an error
A<T>::set' : cannot convert parameter 1 from 'const int *' to 'int *const '

and if i change to this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template<class T>
class A
{
private:
	int t;
	T typevar;
public:
	A() {t=1;};
	void set(const T a){typevar=a;};

};
void main( void )
{
A <int *> a;
int * const x=new int(1);
a.set(x);

int k;
cin>>k;
}



no error exists
can anyone anwer why??
Since 'T' is a pointer, your set() method expects a constant pointer to one or more mutable integers (that is what you wrote). In your first example, you declare 'x' to be a pointer to one or more constant integers. So, when you call set() you effectively request that a pointer to a constant object is converted into a pointer to a mutable object - this is not legal without use of 'const_cast'.

My guess is that you are a bit confused about the different meanings of the following two declarations:

1) const int *i;

2) int *const i;

The former declares that the integer is constant, while the latter declares that the pointer is constant.

Hope this helps.
Last edited on
yes this helps!!
thanks a lot..
Topic archived. No new replies allowed.