Wednesday, 2 December 2009

Using constants with functions

There always seems to be confusion in using const with functions. I am not referring to const functions that have const after the function name, that is straightforward. Also, the way functions behave when you have const before them is different than the built-in types. I have earlier provided a table for that.

Here is a simple program that shows different types of const with functions.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

class
A
{

public
:
int
x;
};


class
B
{

public
:
string y;
};


A* const createA()
{

return
(new A);
}


const
B* createB()
{

return
(new B);
}


int
main()
{

A* a = NULL;
a = createA();
a->x = 100;
cout<<"a.x = "<<a->x<<endl;
delete
a;

const
B* b = NULL;
b = createB();
//b->y = "Hello"; - Compilation error because b is constant
(const_cast<B*>(b))->y = "Hello";
cout<<"b.y = "<<b->y<<endl;
delete
b;

A* const a2 = NULL;
//a2 = createA(); - Compilation Error:
// you cannot assign to a variable that is const

A* const a3 = new A; //not possible to change what a3 points to now
a3->x = 23456;
cout<<"a3.x = "<<a3->x<<endl;
delete
a3;

return
0;
}






The output is as follows:

No comments:

Post a Comment