Saturday, 4 July 2009

A simple example of pointer-to-const

What is "const correctness"?

"const correctness" means using the keyword const to prevent const objects from getting mutated.

In this example we show passing by pointer-to-const. In case of pass by pointer-to-const, any attempts to change to the caller's variable within the function would be flagged by the compiler as an error at compile-time. This check is done entirely at compile-time: there is no run-time space or speed cost for the const. Also passing by pointer-to-const is more efficient as it avoids temporary objects.

So here is the example:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple program to show const pointers
#include<iostream>

using namespace
std;

class
A
{

public
:
int
*var;
};


void
someFunc(const A* a)
{

//int b=200;
//a = &b; - Not Possible to convert int* to const int*
// We can use a const_cast but thats not the purpose here
*(a->var) = 200; //Possible to change value of const pointer
}

void
anotherFunc(const A* a)
{

if
(a)
{

if
(a->var)
delete
a->var;
delete
a;
}
}


int
main()
{

A *a = new A;
a->var = new int(1024);
cout<<"1: a->var = "<<*(a->var)<<endl;
someFunc(a);
cout<<"2: a->var = "<<*(a->var)<<endl;
anotherFunc(a);
//cout<<"3: a->var = "<<*(a->var)<<endl; - Not Valid
return 0;
}
 


The output is as follows:

No comments:

Post a Comment