Leon Anavi
IT Tips && Tricks

C/C++

Created: 16.10.2009 23:52 Last Modified: 17.10.2009 00:13 Views: 9344
Keywords: class, const, method, mutable, OOP

OOP with mutable Variables and const Methods

Purpose of Keywords mutable and const

Keywords mutable and const are vital for professional Object-oriented programming with C++. Methods (functions inside a class) declared as const cannot change the value of any class members except those declared as mutable. Declaration of const methods is a good (even mandatory) practice for large projects and frameworks. Sometimes the circumstances require const methods which declaration cannot be changed to modify members. For example framework declares method Draw as const but a member value must be updated after drawing certain figure. Key mutable is used to solve probles like this by allowing access of const methods to members no matter what is their scope of visibility (private, protected or public).

Examples

const

A methods declared as const will try to modify a class member. As a result the compiler will exit with an error.

Source Code

#include <iostream>

class Test
{
private:
	int m_nTest;
public:
	Test() : m_nTest(0)
	{
		//constuct
	}

	~Test()
	{
		//destruct
	}

	int getTest() const
	{
		if (0 > m_nTest)
		{
			m_nTest = 0;
		}
		return m_nTest;
	}

};

int main()
{
	Test obj;
	int nMyTest = obj.getTest();
	return 0;
}

Error

[leon@localhost mutableconst]$ g++ const.cpp -o testconst
const.cpp: In member function ‘int Test::getTest() const’:
const.cpp:22: error: assignment of data-member ‘Test::m_nTest’ in read-only structure

mutable

This working example will demonstate a get method that return the value of a member and another member which stores the count of calls of the get method. In general it is a good practice to declare all get methods as const.

Source Code

#include <iostream>

class Test
{
private:
	int m_nTest;
	mutable int n_nGetCounter;
public:
	Test(): m_nTest(0), n_nGetCounter(0)
	{
		//Nothing more to init
	}

	~Test()
	{
		//destructor
	}

	int getTest() const
	{
		n_nGetCounter += 1;
		return m_nTest;
	}

	int getTestCounter() const
	{
		return n_nGetCounter;
	}
};

int main()
{
	Test obj;
	std::cout << "Counter = " << obj.getTestCounter() << std::endl;
	std::cout << "Test value = " << obj.getTest() << std::endl;
	std::cout << "Counter = " << obj.getTestCounter() << std::endl;
	return 0;
}

Output

[leon@localhost mutableconst]$ g++ mutableconst.cpp -Wall -o testmutableconst
[leon@localhost mutableconst]$ ./testmutableconst
Counter = 0
Test value = 0
Counter = 1


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.