"cob" <cob@hotmail.co m> wrote in message
news:403c4c4d$0 $93683$45beb828 @newscene.com.. .[color=blue]
> Are there any situations where it might be better to use
>
> struct a { int i };
>
> rather than
>
> int i; ?
>
> Why would one ever do this?
>[/color]
Homework? Good question anyway.
You might to the above if you wanted a type which was 'int-like' but
distinguishable from a normal int in function overloading (for instance).
You might do it is you wanted an 'int-like' type but wanted to suppress some
of the normal behaviour of an int (automatic conversion to double for
instance).
cob wrote:[color=blue]
> Are there any situations where it might be better to use
>
> struct a { int i };
>
> rather than
>
> int i; ?
>
> Why would one ever do this?
>
>[/color]
One reason is as a foundation to test algorithms.
If the algorithm works with a single int in the structure,
then adding another member won't add much to the design
or program structure.
Another reason may be variable alignment. Some implementations
align structures on a given boundaries but not individual
variables.
"cob" <cob@hotmail.co m> wrote in message
news:403c4c4d$0 $93683$45beb828 @newscene.com.. .[color=blue]
> Are there any situations where it might be better to use
>
> struct a { int i };
>
> rather than
>
> int i; ?
>
> Why would one ever do this?[/color]
Obviously you can write a constructor for a struct. Not that it would do
you much good, but at least you could initialize it to 0 automatically.
cob wrote:
[color=blue]
> Are there any situations where it might be better to use
>
> struct a { int i };
>
> rather than
>
> int i; // ?
>
> Why would one ever do this?[/color]
Abstraction.
struct Integer {
private:
// representation
int I;
public:
// functions, operators and constructors
};
Using Integer instead of int permits you
to redefine functions and operations on type int
or even to change the representation of Integer
without consideration for the impact those changes
will have on programs that use type Integer.
Comment