Title: Constructors and Other Tools
1Chapter 7
- Constructors and Other Tools
2Learning Objectives
- Constructors
- Definitions
- Calling
- More Tools
- const parameter modifier
- Inline functions
- Static member data
- Vectors
- Introduction to vector class
3Constructors
- Initialization of objects
- Initialize some or all member variables
- Other actions possible as well
- A special kind of member function
- Automatically called when object declared
- Very useful tool
- Key principle of OOP
4Constructor Definitions
- Constructors defined like any member function
- Except
- Must have same name as class
- Cannot return a value not even void!
5Constructor Definition Example
- Class definition with constructor
- class DayOfYearpublic DayOfYear(int
monthValue, int dayValue) //Constructor
initializes month day to arguments. - void input() void output()
private int month int day
6Constructor Notes
- Notice name of constructor DayOfYear
- Same name as class itself!
- Constructor declaration has no return-type
- Not even void!
- Constructor in public section
- Its called when objects are declared
- If private, could never declare objects!
7Calling Constructors
- Declare objects DayOfYear date1(7,
4), date2(5, 5) - Objects are created here
- Constructor is called
- Values in parentheses passed as arguments to
constructor - Member variables month, day initializeddate1.mon
th ? 7 date2.month ? 5date1.dat ? 4 date2.day ? 5
8Constructor Equivalency
- Consider
- DayOfYear date1, date2 // problems
date1.DayOfYear(7, 4) // ILLEGAL!date2.DayOfYear
(5, 5) // ILLEGAL! - Seemingly OK
- CANNOT call constructors like other member
functions!
9Constructor Code
- Constructor definition is like all other member
functionsDayOfYearDayOfYear(int monthValue,
int dayValue) month monthValue day
dayValue - Note same name around
- Clearly identifies a constructor
- Note no return type
- Just as in class definition
10Alternative Definition
- Previous definition equivalent toDayOfYearDay
OfYear( int monthValue, int dayValue)
month(monthValue), day(dayValue) ? - Third line called "Initialization Section"
- Body left empty //need not be empty
- Preferable definition version
11Constructor Additional Purpose
- Not just initialize data
- Body doesnt have to be empty
- In initializer version
- Validate the data!
- Ensure only appropriate data is assigned toclass
private member variables - Powerful OOP principle
12- DayOfYearDayOfYear(int monthValue,int
dayValue) month(monthValue), day(dayValue) -
- if ((month lt1) (month gt12))
-
- cout ltlt Illegal month value! \n
- exit(1)
-
- if ((day lt1) (day gt31))
-
- cout ltlt Illegal month value! \n
- exit(1)
-
-
Validate the data!
13Overloaded Constructors
- Can overload constructors just like other
functions - Recall a signature consists of
- Name of function
- Parameter list
- Provide constructors for all possibleargument-lis
ts - Particularly "how many"
14Class with Constructors Example Display 7.1
Class with Constructors (1 of 3)
15Class with Constructors Example Display 7.1
Class with Constructors (2 of 3)
16Class with Constructors Example Display 7.1
Class with Constructors (3 of 3)
17Constructor with No Arguments
- Can be confusing
- Standard functions with no arguments
- Called with syntax callMyFunction()
- Including empty parentheses
- Object declarations with no "initializers"
- DayOfYear date1 // This way!
- DayOfYear date() // NO!
- What is this really?
- Compiler sees a function declaration/prototype!
- Yes! Look closely!
18Explicit Constructor Calls
- Can also call constructor AGAIN
- After object declared
- Recall constructor was automatically called then
- Can call via objects name standard
memberfunction call - Convenient method of setting member variables
- Method quite different from standard member
function call
19Explicit Constructor Call Example
- Such a call returns "anonymous object"
- Which can then be assigned
- In ActionDayOfYear holiday(7, 4)
- Constructor called at objects declaration
- Now to "re-initialize"holiday DayOfYear(5,
5) - Explicit constructor call
- Returns new "anonymous object"
- Assigned back to current object
An anonymous object is an object that is not
named (as yet) by any variable!
20Default Constructor
- Defined as constructor with no arguments
- One should always be defined
- Auto-Generated?
- Yes No ?
- If no constructors AT ALL are defined ? Yes!!
- If any constructors are defined ? No!!
- If no default constructor
- Cannot declare MyClass myObject
- With no initializers
21Example
- BankAccount Class
- Display 7.2
- Page 283-287
- Self-study
22Class Type Member Variables
- Class member variables can be any type
- Including objects of other classes!
- Type of class relationship
- Powerful OOP principle
- Need special notation for constructors
- So they can call "back" to member objects
constructor
23Class Member Variable Example Display 7.3 A
Class Member Variable (1 of 5)
24Class Member Variable Example Display 7.3 A
Class Member Variable (2 of 5)
25Class Member Variable Example Display 7.3 A
Class Member Variable (3 of 5)
26Class Member Variable Example Display 7.3 A
Class Member Variable (4 of 5)
27Class Member Variable Example Display 7.3 A
Class Member Variable (5 of 5)
28More tools
- Intelligence is the facility of making
artificial objects, especially tools to make
tools - Three topics
- Const parameters for classes
- Inline functions
- Static class members
29Parameter Passing Methods
- Efficiency of parameter passing
- Call-by-value
- Requires copy be made ? Overhead
- Call-by-reference
- Placeholder for actual argument
- Most efficient method
- Negligible difference for simple types
- For class types ? clear advantage
- Call-by-reference desirable
- Especially for "large" data, like class types
30????(reference type)
- ?????,C??call by reference,C ???? call by
value?????,C ?? Pascal?????????????????? C
?????,??? class ? object, ?? ???,?????,????? ?
??,?????????????C??call by reference?const???,?
????????????,?? call by value ???,??????? (actual
parameter) ?????
31???????--????? (alias)
- ?????????????,? C ?? ?????????????,????????,????
,????? C ? C ???????????????,??? ??? - ???????????????
-
- int pi
- pi new int(10)
- pi 2
-
- ??
- pi ????, ?????? int ????,? ???????????
- ??????????????, ? ???? pi?
32- ???????? ?????????,?????? ??????,????
?????????? ????????,?????? ??? - ? ? ???????????????
-
- int i
- int referToi i // ?? referToi ? ?? i ???? i
10 - cout ltlt "referToi " ltlt referToi ltlt endl
- referToi 20
- cout ltlt "i " ltlt i ltlt endl
-
- ??
- ?? referToi ??? i ??????????????,? referToi ??? i
???? - ?? referToi ? i ????????,???????????
- referToi ????????? i ???,?????? i ???,????
referToi ?,?????? i? - ?????????
- referToi 10
- i 20
33??????? -- call by reference
- void swap(int x, int y) // call by reference
-
- int temp
- temp x
- x y
- y temp
-
- main()
-
- int i, j
- cout ltlt "Input 2 numbers" ltlt endl
- cin gtgt i gtgtj
- if( i gt j ) swap(i, j)
- cout ltlt "The smaller number is " ltlt i ltlt endl
- cout ltlt "The larger is " ltlt j ltlt endl
-
- ??
- ???? swap(i, j) ?, ??? ?? ??int xi int yj?
- ?? x ? ?? i ? ??, y ? ?? j ? ???
- ??? swap ?, ?? ?? x ? y ??, ?? i ? j ??? ???
- ??? ?? ? ?? ?
- Input 2 numbers
- 100 50
- The smaller number is 50
- The larger is 100
34Call-by-reference
- ??/?? reference variable ??????????????,
?????????????????????? (alias). - ??????? C ???????????. (????????)
- ? C ?, ??????????,??? "... ???"
????????????,??? "... ??? reference variable". - ????? ???????
- int x int x
- int p x int y x
35The const Parameter Modifier
- Large data types (typically classes)
- Desirable to use pass-by-reference
- Even if function will not make modifications
- Protect argument
- Use constant parameter
- Also called constant call-by-reference parameter
- Place keyword const before type
- Makes parameter "read-only"
- Attempts to modify result in compiler error
36- bool isLarger(BankAccount account1, BankAccount
account2) - //Returns true if the balance in account1 is
greater than that in account2. - //Otherwise return false
-
- return(account1.getBalance() gt
account2.getBalance()) -
- bool isLarger(const BankAccount account1, const
BankAccount account2) - //Returns true if the balance in account1 is
greater than that in account2. - //Otherwise return false
-
- return(account1.getBalance() gt
account2.getBalance())
Pass by value
Pass by const reference
37Use of const
- All-or-nothing
- If no need for function modifications
- Protect parameter with const
- Protect ALL such parameters
- This includes class member functionparameters
38Const with member function
- class BankAccount
-
- public
-
- void output( ) const
-
-
- void BankAccountoutput( ) const
-
-
39Example
40Inline Functions
- For non-member functions
- Use keyword inline in function declaration and
function heading - For class member functions
- Place implementation (code) for function INclass
definition ? automatically inline - Use for very short functions only
- Code actually inserted in place of call
- Eliminates overhead
- More efficient, but only when short!
41Inline Member Functions
- Member function definitions
- Typically defined separately, in different file
- Can be defined IN class definition
- Makes function "in-line"
- Again use for very short functions only
- More efficient
- If too long ? actually less efficient!
42Static Members
- Static member variables
- All objects of class "share" one copy
- One object changes it ? all see change
- Useful for "tracking"
- How often a member function is called
- How many objects exist at given time
- Place keyword static before type
43static data member
- class ??? static data member ????????? (global
variable),?????? class ? data member? - ?? private static data member ????? class
???????,?? public static data member ??? C ???
???????? - ???????? ?? data member ?? ?? static ???
44static data member???
- ??
- constructNum ??? C ??? ????????
- destructNum ???? class CTest ????????
- class CTest
-
- public
- CTest()
- CTest()
- static int constructNum
- int value
- private
- static int destructNum
45- ?? static data member ?????????class ??????
implementation ??,???? - ?? static data member ??? ???
- class CTest
-
- public
- CTest()constructNum
- CTest()destructNum
- static int constructNum
- int value
- int getDestructorNum() return destructNum
- private
- static int destructNum
-
- int CTestconstructNum0 // static data member
??? ??? - int CTestdestructNum0 // static data member
??? ??? - main()
46- ??
- ? class CB ????????? CTestconstructNum,
??????????????? - ? main() ????????? CTestconstructNum?
- ???????
- number of constructed class CTest 2
- number of destructed class CTest 0
- b.x 2
- number of constructed class CTest 3
- number of destructed class CTest 0
- b.x 3
- number of constructed class CTest 3
- number of destructed class CTest 1
- class CB
- public
- CB()
- CB()
- void set() // public static data member ???
- x CTestconstructNum
- int get() return x
- private
- int x
- main()
-
- CTest t1, t2, pt
- CB b
- b.set()
- coutltlt "number of constructed class CTest "
- coutltlt CTestconstructNumltlt endl // public
static data member ??? - coutltlt "number of destructed class CTest "
- coutltlt t1.getDestructorNum() ltlt endl
- coutltlt "b.x "ltlt b.get()ltlt endl
? 3
47Static Functions
- Member functions can be static
- If no access to object data needed
- And still "must" be member of the class
- Make it a static function
- Can then be called outside class
- From non-class objects
- E.g., ServergetTurn()
- As well as via class objects
- Standard method myObject.getTurn()
- Can only use static data, functions!
48static member function
- ??? 3 ? class CTest ? member function
getDestructorNum() ???? static data member
destructNum,????? destructNum ??,???????????
CTest ? object???,???? member function
getDestructorNum() ?? static ????? static member
function? - ?? static member function ????????? static data
member ?????? - ?????? 3 ? ? main() ??? t1.getDestructorNum() ??
CTestgetDestructorNum()?
49? 3
- main()
-
- CTest t1, t2, pt
- CB b
- b.set()
- coutltlt "number of constructed class CTest "
- coutltlt CTestconstructNumltlt endl // public
static data member ??? - coutltlt "number of destructed class CTest "
- coutltlt CTestgetDestructorNum() ltlt endl
- coutltlt "b.x "ltlt b.get()ltlt endl
- pt new CTest
- b.set()
- coutltlt number of constructed class CTest
// public static data member ??? - coutltlt CTestconstructNumltlt endl
- coutltlt "number of destructed class CTest "
- coutltlt CTestgetDestructorNum() ltlt endl
- coutltlt "b.x "ltlt b.get()ltlt endl
- delete pt
- coutltlt number of constructed class CTest
// public static data member ???
50Static Members Example Display 7.6 Static
Members (1 of 4)
51Static Members Example Display 7.6 Static
Members (2 of 4)
52Static Members Example Display 7.6 Static
Members (3 of 4)
53Static Members Example Display 7.6 Static
Members (4 of 4)
54Vectors
- Well, Ill eat it said Alice, and if it makes
me grow larger, I can reach the key and if it
makes me grow smaller, I can creep under the dor
so either way Ill get into the garden. - Lewis Carroll, Alices Adventures in Wonderland
55Vectors
- Vector Introduction
- Recall arrays are fixed size
- Vectors "arrays that grow and shrink"
- During program execution
- Formed from Standard Template Library(STL)
- Using template class
- Template in chap 16 STL in chap 19
56Vector Basics
- Similar to array
- Has base type
- Stores collection of base type values
- Declared differently
- Syntax vectorltBase_Typegt
- Indicates template class
- Any type can be "plugged in" to Base_Type
- Produces "new" class for vectors with that type
- Example declarationvectorltintgt v
57Vector Use
- vectorltintgt v
- "v is vector of type int"
- Calls class default constructor
- Empty vector object created
- Indexed like arrays for access
- But to add elements
- Must call member function push_back
- Member function size()
- Returns current number of elements
58Vector Use
- Cannot initialize the ith element using vi
- Add an element to a vector for the first time
- Use the member function push_back
- First at position, then position 1, then 2, and
so forth
vectorltdoublegt sample sample.push_back(0.0) samp
le.push_back(1.1) sample.push_back(2.2)
59Vector Use
- size can be used to determine how many elements
are in a vector - Return a value of type unsigned int.
- Safe form
- Vector definition
- In library vector
- In std namespace
for (int i0 iltsample.size() i) cout ltlt
samplei ltlt endl
for (unsigned int int i0 iltsample.size()
i) cout ltlt samplei ltlt endl
include ltvectorgt using namespace std
60Vector Example Display 7.7 Using a Vector (1
of 2)
61Vector Example Display 7.7 Using a Vector (2
of 2)
62Vector Use
- //default constructor producing an empty vector.
- //vector constructor uses the default constructor
for AClass to initialize 20 elements.
vectorltintgt v
vectorltAClassgt record(20)
63Vector Efficiency
- Member function capacity()
- Returns memory currently allocated
- Not same as size()
- Capacity typically gt size
- Automatically increased as needed
- If efficiency critical
- Can set behaviors manually
- v.reserve(32) //sets capacity to 32
- v.reserve(v.size()10) //sets capacity to 10
morethan size
64Size and Capacity
- Size
- The number of elements in the vector
- Capacity
- The number of elements for which it currently has
memory allocated - For a vector v, the size and capacity can be
recovered with the member functions v.size() and
v.capacity().
65Summary 1
- Constructors automatic initialization of class
data - Called when objects are declared
- Constructor has same name as class
- Default constructor has no parameters
- Should always be defined
- Class member variables
- Can be objects of other classes
- Require initialization-section
66Summary 2
- Constant call-by-reference parameters
- More efficient than call-by-value
- Can inline very short function definitions
- Can improve efficiency
- Static member variables
- Shared by all objects of a class
- Vector classes
- Like "arrays that grow and shrink"