Sunday, 2 August 2009

Const after a function name

Here is a classic example of putting const after a function name. What this means is that this function will not modify any private members of this class.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows what happens if const is put after a function
#include<iostream>

using namespace
std;

class
ABC
{

public
:
int
func1(int a, int b);
int
func2(int a, int b) const;
private
:
int
x,y;
};


int
ABC::func1(int a, int b)
{

x = a, y = b;
cout<<"x = "<<x<<" and y = "<<y<<endl;
return
0;
}


int
ABC::func2(int a, int b) const
{

//x = a, y = b; - NOT POSSIBLE, Compile Error
cout<<"Cant change x and y"<<endl;
return
-1;
}


int
main()
{

ABC abc;
abc.func1(3, 7);
abc.func2(20, 40);
return
0;
}


The output is as follows:


No comments:

Post a Comment