Constructors and Other Tools - PowerPoint PPT Presentation

1 / 66
About This Presentation
Title:

Constructors and Other Tools

Description:

Validate the data! Ensure only appropriate data is assigned ... How many objects exist at given time. Place keyword static before type. 43. static data member ... – PowerPoint PPT presentation

Number of Views:51
Avg rating:3.0/5.0
Slides: 67
Provided by: Baol
Category:

less

Transcript and Presenter's Notes

Title: Constructors and Other Tools


1
Chapter 7
  • Constructors and Other Tools

2
Learning Objectives
  • Constructors
  • Definitions
  • Calling
  • More Tools
  • const parameter modifier
  • Inline functions
  • Static member data
  • Vectors
  • Introduction to vector class

3
Constructors
  • 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

4
Constructor Definitions
  • Constructors defined like any member function
  • Except
  • Must have same name as class
  • Cannot return a value not even void!

5
Constructor 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

6
Constructor 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!

7
Calling 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

8
Constructor 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!

9
Constructor 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

10
Alternative 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

11
Constructor 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!
13
Overloaded 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"

14
Class with Constructors Example Display 7.1
Class with Constructors (1 of 3)
15
Class with Constructors Example Display 7.1
Class with Constructors (2 of 3)

16
Class with Constructors Example Display 7.1
Class with Constructors (3 of 3)
17
Constructor 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!


18
Explicit 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

19
Explicit 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!
20
Default 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

21
Example
  • BankAccount Class
  • Display 7.2
  • Page 283-287
  • Self-study

22
Class 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

23
Class Member Variable Example Display 7.3 A
Class Member Variable (1 of 5)
24
Class Member Variable Example Display 7.3 A
Class Member Variable (2 of 5)
25
Class Member Variable Example Display 7.3 A
Class Member Variable (3 of 5)
26
Class Member Variable Example Display 7.3 A
Class Member Variable (4 of 5)
27
Class Member Variable Example Display 7.3 A
Class Member Variable (5 of 5)
28
More 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

29
Parameter 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

34
Call-by-reference
  • ??/?? reference variable ??????????????,
    ?????????????????????? (alias).
  • ??????? C ???????????. (????????)
  • ? C ?, ??????????,??? "... ???"
    ????????????,??? "... ??? reference variable".
  • ????? ???????
  • int x int x
  • int p x int y x

35
The 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
37
Use of const
  • All-or-nothing
  • If no need for function modifications
  • Protect parameter with const
  • Protect ALL such parameters
  • This includes class member functionparameters

38
Const with member function
  • class BankAccount
  • public
  • void output( ) const
  • void BankAccountoutput( ) const

39
Example
  • Display 7.4
  • Page 295297

40
Inline 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!

41
Inline 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!

42
Static 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

43
static data member
  • class ??? static data member ????????? (global
    variable),?????? class ? data member?
  • ?? private static data member ????? class
    ???????,?? public static data member ??? C ???
    ????????
  • ???????? ?? data member ?? ?? static ???

44
static 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
47
Static 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!

48
static 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 ???

50
Static Members Example Display 7.6 Static
Members (1 of 4)
51
Static Members Example Display 7.6 Static
Members (2 of 4)
52
Static Members Example Display 7.6 Static
Members (3 of 4)
53
Static Members Example Display 7.6 Static
Members (4 of 4)
54
Vectors
  • 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

55
Vectors
  • 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

56
Vector 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

57
Vector 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

58
Vector 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)
59
Vector 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
60
Vector Example Display 7.7 Using a Vector (1
of 2)
61
Vector Example Display 7.7 Using a Vector (2
of 2)
62
Vector Use
  • //default constructor producing an empty vector.
  • //vector constructor uses the default constructor
    for AClass to initialize 20 elements.

vectorltintgt v
vectorltAClassgt record(20)
63
Vector 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

64
Size 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().

65
Summary 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

66
Summary 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"
Write a Comment
User Comments (0)
About PowerShow.com