Você está na página 1de 26

More on Classes

Function Overloading Default arguments Constructors-Destructors Inheritance basics

Junaed Sattar October 08, 2008 Lecture 6

Today

Object creation and destruction Function overloading Constructor details


default constructors copy constructors copy constructor and assignment operators

Overloading

Literally, to use one identifier for multiple components Function overloading is defining multiple functions with the same name

usually, the bodies are different example of compile-time polymorphism compiler differentiates using function/method signature

Overloading example
voidSort(int*array,intsize); voidSort(double*array,intsize); voidSort(string*array,intsize,intcriteria); (Thecriteriaargumentcoulddefinehowwewantto sortstrings.alphabetically,accordingtostring length,orcaseetcetc.)

Binding overloaded methods

Binding is associating a function call with a definition

in this case: which Sort() should I execute? overloaded functions MUST have different type and/or length of arguments changing just the return type is NOT sufficient

Compiler looks at function argument list


Overloading Overdose!
voidSort(int*array, intsize); intSort(double*array, intsize); boolSort(int*array, intsize);

Find the offending declaration Default arguments can also cause overloading problems

Default arguments

Assign values to function arguments during declaration Useful for frequently passed arguments

saves typing results in compact, cleaner code, focusing on task at hand


istream&getline(istream&is,string&s,char delimiter='\n');

Remember getline?

Default arguments

If omitted, the default value is used

getline(cin,buffer);

Otherwise the passed value is used

getline(cin,buffer,'?');

Similar to overloading, different in application

Syntax

return_type function_name( non-default arguments, default_arguments = default_values ) default arguments MUST come after all non-default arguments Use default argument values at declaration but not at definition

Examples
classCourseManager{ stringcourseName; longcourseID; string*studentID; unsignedclassSize; public: //constructorsdestructorsomittedfornow voidSetClassSize(intsize=30)//default { this>classSize=size; //notethethispointer } ... ... };

Issues, if any?
boolCheckUserName(stringusername,string*list, intlength=100); boolCheckUserName(char*username,string*list,int length=100); boolCheckUserName(stringusername,string*list); boolCheckUserName(char*username,char**list,int length=100); boolCheckUserName(stringusername,char**list,int length=100);

Object construction

Classes are blueprints Instantiations: definitions of objects

memory is allocated for an object of a specific class space is allocated for variables method addresses are calculated

Classes have methods and variables


Example
classDate{ public: Date(intd,intm,inty){ day=d;month=m;year=y; } private: intday,month,year; };

Instantiate a Date
//thisiswrong.Why? Dated; //thiswillwork Dated(12,11,2001);

no default constructor must create objects same way as constructors are defined.

Initializer list

Another syntax to initialize class data using a constructor.

classDate{ public: Date(intd,intm,inty):day(d),month(m),year(y){ }

same as:
Date(intd,intm,inty){ day=d;month=m;year=y; }

Default Constructor

Constructor requring no arguments Usefulness?

think about it

Initialization vs Assignment
classCourseManager{ ... }; classCourseManager{ ... };

intmain(){ CourseManagercm1; ... CourseManagercm2=cm1; //orequivalent: //CourseManagercm2(cm1); }

intmain(){ CourseManagercm1; ... CourseManagercm2; cm2=cm1; }

Copy Constructors

Called when an object is initialized with an existing similar object Compiler provides a default copy constructor

Performs an exact bitwise copy

Works okay most of the time

Copy Constructors

But not always Think classes with dynamic memory allocation Blindly copying pointers can result in memory corruption Example to follow

Copy Constructors
classCourseManager{ ... string*studentID; unsignedclassSize; public: CourseManager(intsize=100){ studentID=newstring[size]; ... }; ... ~CourseManager(){ delete[]studentID; ... } };

Consider this
voidSomeFunction(CourseManager&cm){ CourseManagercm_new(cm); ... return; }; intmain(){ CourseManagermyCM; ... SomeFunction(myCM); }

Problem?

What happens when cm_new is destroyed? Since default copy cons. makes bitwise copy, the pointer address is duplicated In effect, cm_new and cm (or, myCM) points to the same memory location! when cm_newis destroyed, memory for studentIDis deleted! This is the same studentIDpointer used by myCM.

myCM

Cartoon version

cm_new

studentID

allocated memory

studentID

Solution

Write your own copy constructor

CourseManager(constCourseManager&cm){ classSize=cm.classSize; studentID=newstring[classSize]; ... }

Destructor is the same Key point: Allocate your own memory!

myCM

Cartoon version
allocated memory myCM

cm_new

studentID allocated memory cm_new

studentID

In the future

Overloading operators Inheritance Run-time polymorphism

Você também pode gostar