Objects with Functions and Arrays. Objects can be Passed Class defines type Can use as type of...

Post on 18-Jan-2018

217 views 0 download

description

Returning an Object To return object: – Make desired object – Return it Use function:

Transcript of Objects with Functions and Arrays. Objects can be Passed Class defines type Can use as type of...

Objects with Functionsand Arrays

Objects can be Passed

• Class defines type– Can use as type of function or parameter

Returning an Object

• To return object:– Make desired object– Return it

• Use function:

Passing An Object

• Passing object copies the object:

• Main:

c1

radius: 5

Passing An Object

• Passing object copies the object:

• Main:

c1

radius: 5

c

radius: 5

Copies Generally Bad

• Copies– Are inefficient– Prevent functions from modifying an object

• Main:c1

radius: 5

Copies Generally Bad

• Copies– Are inefficient– Prevent functions from modifying an object

• Main:c1

radius: 5

c

radius: 5

Copies Generally Bad

• Copies– Are inefficient– Prevent functions from modifying an object

• Main:c1

radius: 5

c

radius: 10

Copies Generally Bad

• Copies– Are inefficient– Prevent functions from modifying an object

• Main:c1

radius: 5

Pass By Reference

• Unless you need copy, pass by reference

• Main:c1

radius: 5

Pass By Reference

• Unless you need copy, pass by reference

• Main:c1

radius: 5

c

Pass By Reference

• Unless you need copy, pass by reference

• Main:c1

radius: 10

c

Pass By Reference

• Unless you need copy, pass by reference

• Main:c1

radius: 10

Const Reference

• To prevent function from modifying, use const reference:

Link back to original object

Make changing it a compile error

Arrays

• Can have an array of objectsCircleList

0 radius: 2

1 radius: 2

2 radius: 2

3 radius: 2

4 radius: 2

Arrays

• Reference individual objectsby index CircleList

0 radius: 4

1 radius: 2

2 radius: 2

3 radius: 2

4 radius: 2

Arrays

• Arrays initialized with defaultconstructor CircleList

0 radius: 2

1 radius: 2

2 radius: 2

3 radius: 2

4 radius: 2

Arrays

• This makes 10 circles:

Arrays

• This makes 10 circles:CircleList

0 radius: 2

1 radius: 2

2 radius: 2

3 radius: 2

4 radius: 2

Arrays

• This makes 10 circles:CircleList

0 radius: 1

1 radius: 2

2 radius: 3

3 radius: 4

4 radius: 5

Arrays

• Use initialization list to prevent filling with default objects:

CircleList

0 radius: 1

1 radius: 2

2 radius: 3

3 radius: 4

4 radius: 5Call 1-arg constructor to make anonymous object