Limited Private
Limited Private: The Problem to Solve
New Types have = and :=
- New types automatically have = and :=, but
- We may not want them
- Or, we may want them to operate differently
- Deep and Shallow Copy
- Clone
Problems with = and :=
- Built in behavior might not be what we want
- Consider = with array stacks: = does not compare correctly
- What does it do?
- What can go wrong?
- Built in behavior might change as implementation changes
- Consider := and a stack implemented as an array or using pointers
- Array: copy the entire record. Pointers: copy only the pointer
- Could cause changing implementation to change client behavior (Oh no!)
- May need to restrict ability to:
- Create copies of variables: eg mySystemClock := theSystemClock;
- Create aliases
- Prevent creation of Dangling References
- Prevent corruption of data structures
Solutions
Solution 1: Redefine = and :=
- Sometimes it's enough to give a new definition
- Example: Redefine = for array stacks
- Ada allows = but not := to be redefined
- C++ allows = and == to be redefined
Solution 2: Limited Private
- Types that are declared as Limited Private:
- Do not have :=
- Only have = if user defines it
Benefits
Benefits of No :=
- Never more than one copy (eg represent something in the real world)
- Consider problems caused by := with pointer-based stacks
- Aliases (let's trace it):
push(1, s);
push(2, s);
t := s;
pop(s); -- What does this create?
Corrupt data structure:
push(1, s);
push(2, s);
t := s;
push(3, s);
Other Issues: Assignment Procedure and Constants
Copy: An Alternative to :=
- In C++, == and = can be redefined to give desired behavior
- In Ada, = but not := can be redefined to give desired behavior
- How can we get something similar to :=?
- Create a copy function: copy(a: out T; b: in T);
Creating Constants without :=
- How do you initialize a constant if there is no :=
- Special function syntax - Extended return statement:
function init(x, y: integer) return T is
begin
-- Extended return allows limited private constant assignment
return result: T := (a => x, b => y);
end init;
theT1: constant T := init(1,2);
Example: limfunction.adb and prettified
Creates value in theT1 rather than creating it in the function and making a copy
Truth in Advertising
Limited without Private
- Limited types do not have to be private
- Example:
type Person is limited record ...