Transitive Const in OO programming

Regan Heath regan at netmail.co.nz
Wed Aug 8 08:01:09 PDT 2007


Regan Heath wrote:
> Alex Burton wrote:
>> Regan Heath Wrote:
>>
>>> StateMachine::getResult modifies state and cannot be 'const'
>>> either.  In this case I think you need a non-const
>>> StateMachine::reset to go back to state = 0;  It makes sense,
>>> especially if you want to call getResult several times for example.
>>>
>>>
>>> Why call StateMachine::sendMessage inside
>>> stateMachineWrapper::getResult?
>>
>> Because it's a state machine and thats how it works.
>>
>>> Why does StateMachineWrapper::getResult have to be const?
>>
>> All it does is gets a value - the fact that internally perhaps
>> several layers of code down there is a state machine should not make
>> a nice get method become non const, and in turn prevent it from being
>> used from a const method.
>>
>>> It seems making StateMachineWrapper::getResult non-const solves the
>>> problem.
>>
>> Yes it would but then I can't simply call a get method (getResult)
>> using a const reference to StateMachineWrapper.
>>
>>> Regan
>>
>> Thanks for your reply Regan, but I think you misunderstand my post,
>> this is not a specific programming problem I have, it is some code I
>> have constructed in order to illustrate a conceptual problem.
> 
> Correct me if I'm wrong but you want to be able to exclude parts of your 
> class from the protection given by 'const', specifically:
> 
> "int state;" in "StateMachine"
> "StateMachine mMachine;" in "StateMachineWrapper"
> 
> thus allowing you to label methods which only modify these things as 
> "const".  Is that more or less it?

Here you are ;)

class StateMachine
{
	int state;
	this()
	{
		state = 0;
	}
	void sendMessage()
	{
		state = 1;
	}
	const int getResult()
	{
		if (state == 1)
		{
			int* p = cast(int*)&state;
			*p = 0;
			return 10;			
		}
		else
			throw new Exception("not in state to getResult");
	}
};

class StateMachineWrapper
{
	StateMachine mMachine;
	this()
	{
		mMachine = new StateMachine;
	}
	const int getResult()
	{
		StateMachine p = cast(StateMachine)mMachine;
		p.sendMessage();
		return p.getResult();
	}
};


void main()
{
	const(StateMachineWrapper) wrapper = new StateMachineWrapper;
	int x = wrapper.getResult();	
}



More information about the Digitalmars-d mailing list