18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Dynamic memory allocation 221<br />

A benifit of the approach taken above is that a client of the class only needs to rel<strong>in</strong>k with any new<br />

implementation code even though the implementor of the class has changed the data <strong>in</strong> the object.<br />

The implementation of the revised class Account is as follows:<br />

with Unchecked_Deallocation;<br />

package body Class_Account is<br />

pragma Controlled( P_Actual_Account ); -- We do deallocation<br />

type Actual_Account is record --Hidden declaration<br />

Balance_Of : Money := 0.00; --Amount <strong>in</strong> account<br />

end record;<br />

The code for Initialize allocates the storage for the object automatically when an <strong>in</strong>stance of the class is<br />

created. The body of f<strong>in</strong>alize releases the storage when the object goes out of scope.<br />

procedure Dispose is<br />

new Unchecked_Deallocation(Actual_Account, P_Actual_Account);<br />

procedure Initialize( The:<strong>in</strong> out Account ) is<br />

beg<strong>in</strong><br />

The.Acc := new Actual_Account; --Allocate storage<br />

end Initialize;<br />

procedure F<strong>in</strong>alize ( The:<strong>in</strong> out Account ) is<br />

beg<strong>in</strong><br />

if The.Acc /= null then --Release storage<br />

Dispose(The.Acc); The.Acc:= null; --Note can be called<br />

end if;<br />

-- more than once<br />

end F<strong>in</strong>alize;<br />

The code for Deposit, Withdraw and Balance are similar to the previous implementation of Account.<br />

procedure Deposit ( The:<strong>in</strong> out Account; Amount:<strong>in</strong> Pmoney ) is<br />

beg<strong>in</strong><br />

The.Acc.Balance_Of := The.Acc.Balance_Of + Amount;<br />

end Deposit;<br />

procedure Withdraw( The:<strong>in</strong> out Account; Amount:<strong>in</strong> Pmoney;<br />

Get:out Pmoney ) is<br />

beg<strong>in</strong><br />

if The.Acc.Balance_Of >= Amount then<br />

The.Acc.Balance_Of := The.Acc.Balance_Of - Amount;<br />

Get := Amount;<br />

else<br />

Get := 0.00;<br />

end if;<br />

end Withdraw;<br />

function Balance( The:<strong>in</strong> Account ) return Money is<br />

beg<strong>in</strong><br />

return The.Acc.Balance_Of;<br />

end Balance;<br />

end Class_Account;<br />

Note:<br />

The automatic de-referenc<strong>in</strong>g of The.<br />

© M A Smith - May not be reproduced without permission

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!