classes in c++ - users.encs.concordia.caamer/teach/coen244/...in a functional program you write down...

116
Classes in C++ Aishy Amer Electrical & Computer Engineering Concordia University Lecture Outline: C++ classes Creating objects Review: call/return by value/reference Assignment operator Default & general constructor Destructor Pointers to objects Objects and call-by-value Copy constructor Hidden func. calls in OOP struct or class? Constant members Constant objects Static members Friend functions inline functions Function overloading Operator overloading this pointer Data type Casting c A. Amer C++ classes 1

Upload: others

Post on 22-Apr-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Classes in C++Aishy Amer

Electrical & Computer Engineering Concordia University

Lecture Outline:C++ classesCreating objectsReview: call/return by value/reference

Assignment operatorDefault & general constructorDestructorPointers to objectsObjects and call-by-valueCopy constructor

Hidden func. calls in OOPstruct or class?Constant membersConstant objectsStatic membersFriend functionsinline functionsFunction overloadingOperator overloadingthis pointerData type Casting

c© A. Amer C++ classes 1

C++ Classes

Classes allow programmers to develop data types (objects)with physical attributes (data) and

with behavior (member functions or methods)

Always separate class declaration from class implementation

C++ class declaration:

class <name> {

public:

<behavior = member functions = operations>

private:

<physical attributes = member data>

};

c© A. Amer C++ classes 2

C++ Classes: Example

Time class: Class declaration (prototype, header, ...)class Time {

public:

void setTime(int, int , int);

void printTime() ;

private:

int hour ;

int minute ;

int second ;

} ;

c© A. Amer C++ classes 3

C++ Classes: Example

Time class: Class implementation (definition)void Time::setTime(int h, int m, int s) {

hour = h ; minute = m ; second = s ;

}

void Time::printTime() {

cout << hour << ":" << minute << ":" << second ;

}

c© A. Amer C++ classes 4

C++ Classes: binding data & functions

// Listing 9.1: Using access function on behalf of the client code

struct Cylinder { // data structure to access

double radius, height;

};

void setCylinder(Cylinder& c, double r, double h)

{ c.radius = r; c.height = h; }

double getVolume(const Cylinder& c) // compute volume

{ return c.height * c.radius * c.radius * 3.141593; }

void scaleCylinder(Cylinder &c, double factor)

{ c.radius * = factor; c.height * = factor; } // scale dimensions

void printCylinder(const Cylinder &c) // print struct stat e

{ cout << "radius: " <<c.radius << " height: " <<c.height <<en dl; }

c© A. Amer C++ classes 5

C++ Classes: binding data and functions

// --> CLIENT // pushing responsibility to server functions

Cylinder c1, c2; // program data

setCylinder(c1,10,30); setCylinder(c2,20,30); // set cy linders

cout << "\nInitial size of first cylinder\n";

printCylinder(c1);

if (getVolume(c1) < getVolume(c2)) // compare volumes

{ scaleCylinder(c1,1.2); // scale it up and

cout << "\nFirst cylinder changed size\n"; // print new size

printCylinder(c1); }

else // otherwise do nothing

cout << "\nNo change in first cylinder size" << endl;

c© A. Amer C++ classes 6

C++ Classes: binding data and functions

// Listing 9.2: Binding data and functions in a class with its own scope.

class Cylinder { // start of the class scope

private:

double radius, height; // data fields to access

public:

void setCylinder(double r, double h) // set cylinder data

{ radius = r; height = h; }

double getVolume() // compute volume

{ return height * radius * radius * 3.141593; }

void scaleCylinder(double factor) // scale dimensions

{ radius * = factor; height * = factor; }

void printCylinder() // print object state

{ cout << "radius: " <<radius << " height: " <<height <<endl; }

} ; // end of class scope

// USE

Cylinder c; c.getVolume();

c© A. Amer C++ classes 7

C++ Classes: private & public specifiers

A private data member or a member function can only beaccessed from within the class

Private is the default – if no specifiers are used

Private data members can be accessed or modified only whileinside a member function of the class

Private member functions can be called only while insideanother member function of the class

Public data member or member function can be accessedfrom anywhere in a program

The public specifier is less restrictive than private

Why bother with private/public specifiers?

c© A. Amer C++ classes 8

C++ Classes: private & public specifiers

Specifiers allow a class to be very complex:with many (private) member functions and data memberswhile having a simple (public) interface to be used by others

Think of a class with many members:It is complex to writeBut with only few public functions it can be used easilyYou need only to understand how to use its public functionsWhat do you need to view: its implementation ordeclaration?

You are not allowed to access the data directly

In a small program, using these specifiers may seem unnecessary

They are, however, necessary in large programs and projectsc© A. Amer C++ classes 9

Creating class objects

int main() {

int x ; // creating a variable x of type int

Time q ; // creating an object q of type Time

Time noon, t; // Create two more objects

int h,m,s; // create 3 int

noon.setTime(12, 0, 0) ; // use the object: DOT operator

noon.printTime() ;

cout<< ‘‘enter time H-M-S’’;

cin>>h>>m>>s; // use the int variables

t.setTime(h,m,s);

return 0 ;

}

c© A. Amer C++ classes 10

Creating class objects: Example

// --> CLIENT // pushing responsibility to server functions

Cylinder c1, c2; // define program data

c1.setCylinder(10,30); c2.setCylinder(20,30); // set cy linders

cout << "\nInitial size of first cylinder\n";

c1.printCylinder();

if (c1.getVolume() < c2.getVolume()) // compare volumes

{ c1.scaleCylinder(1.2); // scale it up and

cout << "\nFirst cylinder changed size\n"; // print new size

c1.printCylinder();

}

else // otherwise do nothing

cout << "\nNo change in first cylinder size" << endl;

c© A. Amer C++ classes 11

Creating class objects

When a class object is instantiated (i.e., created):only the data members are associated with that object

Member functions of a class are only created once:i.e., one copy per class not per object

Hence, sizeof() returns the size of the data members

Big classes do not necessarily imply big objects:all objects of a class share member functions

c© A. Amer C++ classes 12

Class objects: Public & Private Members

Any public members (data or function):accessed by objects of that class

All private members (data and functions):accessed only by other member functions of the same classobject

c© A. Amer C++ classes 13

Interacting objects

OO program:

a pool of objects that are created, destroyed and interacting

Interaction:based on messages or data which are sent from one object toanotherEx.: noon.setTime(12, 0, 0) ; // setTime of yourself

c© A. Amer C++ classes 14

Interacting objects

A message is a request to an object to invokeone of its methods

A message therefore contains1) the name of the method and 2) the arguments of the method

Objects may deny interaction (execution of a method)Ex: If the object is not allowed to execute the requestedmethod

c© A. Amer C++ classes 15

Interacting objects

When the compiler processes a messageExample: noon.setTime(12, 0, 0)

Identifies the name of the object

Searches for the declaration of object to identify its class

Searches for the declaration of this class

Searches whether the member function in the message isdefined

Member function found: checks its interface ...

Match? generate object code

No match? error message

c© A. Amer C++ classes 16

Interacting objects: example

Consider your computer:

How a character appears on the screen when you type a key

In a functional programyou write down the steps to bring a character on the screen:1. wait, until a key is pressed2. get key value3. write key value at current cursor position4. advance cursor position

→ You do not distinguish entities withwell-defined properties and well-known behavior!

c© A. Amer C++ classes 17

Interacting objects: example

In an OO program:

You would distinguish the interacting objects key and screen

A key receives a message to change its state to be pressed

Its corresponding object sends a message to the screen object

This message requests the screen object to display theassociated key value

c© A. Amer C++ classes 18

References: review

A reference is an alternative name or alias for an object

A reference to an object b of type T isT& r=b; // r is declared to be an alias to b;Any operation carried out on r is then an operation on b

int i=5;

int &r =i; // r alias to i

int x=r; // x=5 since r is alias of i

r=2; //equivalent to i=2 since r is an alias of i

A reference must be initialized and cannot be changedto refer to another object

The main use of references is in specifying arguments andreturn values for functions and for overloaded operators

c© A. Amer C++ classes 19

References

Example:void swap(int& i, int& j) // i and j are aliases for main’s x and y

{ // i is x - not a pointer to x, nor a copy of x, but x itself

// Anything you do to i gets done to x, and vice versa

int tmp = i;

i = j;

j = tmp;

}

int main() {

int x, y;

// ...

swap(x,y);

}

c© A. Amer C++ classes 20

References

Remember: you can’t separate the reference from the referent:the reference is its referent

Unlike a pointer, once a reference is bound to an object, it cannot be "reseated" to another object

The reference itself isn’t an object, i.e., it has no identity

taking the address of a reference gives you the address of thereferent

Thus, A reference is similar to a const pointer such asint* const p (this is not const int* p)

Do not confuse references with pointers

This usually means that references are most useful in a classpublic interface

c© A. Amer C++ classes 21

Pointers: review

A pointer is a type of variable that has it own address

A pointer value is a memory address

Common logical error: dereferencing an uninitialized pointer

// Make sure you understand the following:

int x=10,

//int * pi; * pi = 5; // Not OK; You have to initialize pi first

int x(2); // initialize x to 2

int * pi;

pi=&x; // pi points to x, i.e., assign the address of x to pi

* pi=4; // the same as x=4;

int &a; // &a is an address, a reference; I have to initialize i t here

int y(10);

int &b=y; //initialize the address; &b is the address of y

b +=10; // y =+10

c© A. Amer C++ classes 22

Pointers: review

//www.xs4all.nl/˜carlo17/c++/const.qualifier.html fo r const pointers

int x1; // TYPE is "int"

const int x2 = 3; // x2 is a constant

int * p1; // TYPE is "int * "

const int * p2; // p2 is NOT a constant

//No initialization needed? No, because the variable p2 is n ot a constant:

//It only points to constant data!

//If you want to make p2 itself constant then you’ll have to wr ite:

int * const p2 = ...;

//This is the reason that it is better to put

//qualifiers always to the right of the TYPE, to avoid confus ion:

int x1;

int const x2 = 3;

c© A. Amer C++ classes 23

Pointers: review

int * p1;

int * const p2 = &x1; //Note that now we have to initialize p2.

//--------- But how to declare a pointer constant that is

//initialized with &x2 (a pointer to an int const)?

int const * p3; // pointer to ‘the type of x2’

int const * const p4 = &x2; // pointer constant to ‘the type of x2’

//---------- very logical when you realize that the qualifi ers

// work on everything on the left of them, as do * and & in types

//------- Important: When you look at a type that contains a * (or a &)

//always realize that the * (&) works on everything on the left

//---------- Dynamic & fixed memory...

int A[2000]; // not dynamic memory allocation

int * pp = new int[2000]; //dynamic

// do some work with pp ...

delete pp;

pp = new int[15]; // dynamic

c© A. Amer C++ classes 24

Pointers and functions

int add(int x, int y); int* add(int x, int y);

A return type of a function can be of any built-in (except arrays)or programmer-defined type

Parameters are defined (allocated & initialized) when thefunction is invoked

The space for parameters is allocated in the program stack

They are initialized with the values of actual arguments

Function parameters are a copy of the actual argument values

They are destroyed when the function terminates

c=add(a,b); // a,b do not change in the function

c© A. Amer C++ classes 25

Call by-value

int mean(int a, int b);

int main() {

int x=5,y=10;

int z;

z = mean(x,y); // a copy of x and a copy of y are made

// and passed to the function mean()

...

}

c© A. Amer C++ classes 26

Return by-value

int mean(int a, int b) {

int ave=(a+b)/2;

return ave;

//1st copy: ave is copied into temporary location

// which main() can access

// 2nd copy: main() copies the content of this location into z

}

c© A. Amer C++ classes 27

Call by-reference

void swap(int& a, int& b);

int main() {

int x=5,y=10;

swap(x,y); // the names a and b in swap’s body refer directly t o

// the storage in main()’s x and y

//swap works not with copies of x and y but directly with x and y

...

}

void swap(int& a, int& b) {

int t;

t=a;

a=b; b=t; // a is x and b is y

}

c© A. Amer C++ classes 28

Return-by-reference – Not Safe

int& SQR(int a) {

int notSafe=(a * a); // notSafe is stored somewhere in the memory

return notSafe; // The actual location of notSafe is made

// available to main()

// But notSafe goas out of scope: It does not exist

// outside the function?!!

}

int main() {

int x=5,y;

y=SQR(x); //ONE copy: the value of s is copied into y

cout<<y; // Output could be garbage

...

}

c© A. Amer C++ classes 29

Return-by-reference – Safe

int& AddOne( int& in ) {

in = in + 1; //in is not local

//AddOne adds 1 to the variable Start

return in;

}

int main() {

int Start = 3;

int Result;

Result = AddOne(Start) + 2; //the function call is replaced w ith

// the new result of Start

//The value of Start is not copied

//After the function call, the value of Start is 4

return 0;

}

c© A. Amer C++ classes 30

Return-by-reference – Safe; Not Safe

int& SafeNotSafe( const int fGrade ) {

int local = 5;

int * localPointer = new int(8);

if ( fGrade < 1 )

return local; // bad news

else

return * localPointer; // ok

}

c© A. Amer C++ classes 31

Class design in C++

Lecture Outline:C++ classes

Creating objects

Review: call/return by value/reference

Assignment operator

Default & general constructor

Destructor

Pointers to objects

Objects and cal-by-value

Copy constructor

Hidden function calls in OOP

struct or class ?

Constant members

Constant objects

Static members

Friend functions

inline functions

Function overloading

Operator overloading

this pointer

Data type Casting

c© A. Amer C++ classes 32

Object assignment: = operator

C++ goal:treat programmer-defined types in the same way as built-in types

The = operator is a method related to a class

If an object is assigned to another objecta member-wise assignment is performed

Time t1(12, 1, 30), t2 ;

t2 = t1 ; // assignment method =

//t2 gets the values 12, 1, 30

Time& Time::operator=(const Time& p) { ... }; //a = in class t ime

Be careful with member-wise assignmentIf member data is a pointer, the pointer address is copiedthis could be disastrous

c© A. Amer C++ classes 33

Constructors

A constructor is a member function that is calledautomatically when an object of that class is created

The constructor function name is the name of the class

It has no return type

Primarily used to initialize class objects

A constructor mayallocate memory for member pointers,initialize data, or/andread data from a file

c© A. Amer C++ classes 34

Constructors

class Time {

public:

Time() ; // Constructor

void setTime( int h, int m, int s ) ;

void printTime() ;

˜Time() ; // Destructor

Time& operator=(const Time& p) // declare a =

Private:

int hour, minute, second ;

} ;

c© A. Amer C++ classes 35

Constructors

Why would you need a Time constructor?

What happens if someone creates a Time object, then tries toprint it right away?

Time t ;

t.printTime() ;

If a constructor does not initialize the object data→ garbage would be printed out

c© A. Amer C++ classes 36

Types of constructors

Constructor provided by the compiler

Default constructor – no arguments

General constructor – with arguments

Conversion constructor – with one argumentof a different type than the class

Copy constructor – with one argument of the same class

c© A. Amer C++ classes 37

Compiler’s constructor

If the programmer does not provide a constructorthe compiler will automatically create onebut it probably does not do what you wantExample:

class Student {... private: int ID; char * name; };

//what about the pointer? Undefined?

Generally the compiler constructor initializes all member datato default values (e.g., int to 0, string to "")

c© A. Amer C++ classes 38

Default constructor

A constructor with no arguments

It sets the data of an object to predefined initial values

Example

Time::Time()

{

hour = minute = second = 0 ;

}

But what if the user wants to set their own default values?

c© A. Amer C++ classes 39

When is a default constructor a must?

Are there situations where I must supply a constructor?Yes; Reference members and const members must beinitialized

class XXX {... private: const int a; int &r; };

XXX x; // error if no default constructor

c© A. Amer C++ classes 40

General constructor

A constructor may take parameters

It overloads the default constructor to providedifferent initializations from the default constructor

class Time {

public:

Time();

Time(int, int, int) ;

void setTime( int h, int m, int s ) ;

void printTime() ;

˜Time() ;

Private:

int hour, minute, second ;

} ;

Time::Time(int h, int m, int s) {

hour = h ; minute = m ; second = s ; }

c© A. Amer C++ classes 41

Constructor: summary

Always provide a default constructorto initialize all member data to default values(int to 0, strings to "", pointers to NULL, etc.)

Do not rely on the constructor provided by the compiler

class Point { ... private: int x; int y; Point * next; };

...

Point NewPoint; →The next field of NewPoint is undefined

c© A. Amer C++ classes 42

Conversion constructor

A conversion constructor is a constructor that accepts oneargumentthat is of different type than the class

Often it is the type of the data members of the class

It is not supplied by the compiler

Useful whenyou want to specify only one value to create an objectuse the same default value for other fields of each object

Example:Create Cylinder objects with different radius valuesInitially, all objects should have height zero,and then grow to model a process

c© A. Amer C++ classes 43

Conversion constructor: example

class Cylinder {

private: double radius, height;

public:

Cylinder() { radius=1.0; height=0.0;} //default construc tor

Cylinder(double r, double h) { radius=r; height=h;} //gene ral constructor

//A conversion constructor has a parameter of a different ty pe

//than the object it is constructing.

Cylinder(double r) { radius=r; height=0.0;} //conversion constructor

//A copy constructor has a parameter of the same type

// as the object it is constructing.

Cylinder(const Cylinder &c) { radius=c.radius; height=c. height;}

...

};

c© A. Amer C++ classes 44

Conversion constructor: example

//--> CLIENT

Cylinder c; // ?

Cylinder cc(10.2,3.8); // ?

//------------------------------------------------- -------------------

Cylinder c1(50.0); // Conversion constructor is called

Cylinder c2=30.0; // Conversion constructor is called

//in both cases syntax error if you do not have a conversion co nstructor

//------------------------------------------------- -------------------

Cylinder c3=c2; // what is this?

c =cc; // what is this?

c© A. Amer C++ classes 45

Combining constructors

For some classes:possible to combine general, default, and conversion constructors

class Rational {

private:

long nmr, dnm; // private data

void normalize(); // private member function

public:

Rational(long n=0, long d=1) // general, conversion, defau lt constructor

{ nmr = n; dnm = d; ...}

...

};

// Use

Rational a(1,4);

Rational b(2); // or Rational b(2,1);

Rational c; // or Rational b(0,1);

But is this code easy to understand to the maintainer?c© A. Amer C++ classes 46

Class Destructor

During the life of an object:it may allocate memory,create pointers, references, linked lists, orother constructs which take memory

When you are done with an object who should freethe allocated memory?

Without an adequate destructorthese resources will still be reserved by your programand therefore not available to other processes

This is called a memory leak: memory allocated but not freed

c© A. Amer C++ classes 47

Class Destructor

A destructor:a class member function that is called automatically when anobject of that class is destroyed

It is primarily used to clean up dynamically allocated memory

The destructor function name is the name of the classpreceded by tilde (∼)

It has no return type and no parameters

If the programmer does not write a destructor:the compiler will automatically create onebut it does very little

Almost always write a destructor

c© A. Amer C++ classes 48

Class Destructor

When is an object destroyed?When the object is out of scope (named object) orWhen it is explicitly deleted (unnamed object)

Case 1: assumingan object is defined in main();the program ends int main() Time t; ...When is it out of scope / destroyed ?

Case 2: when a pointer to an unnamed object is deleted

c© A. Amer C++ classes 49

Class time: constructor & cestructor

Class declaration

class Time {

public:

Time() ; // Constructor initializes object data

void setTime( int h, int m, int s) ;

void printTime() ;

˜Time() ; // Destructor returns resources

// acquired by the object

Private:

int hour, minute, second ;

};

c© A. Amer C++ classes 50

Class time: constructor & cestructor

Class definition

Time::Time() { hour = minute = second = 0 ; }

Time::˜Time() { }

void Time::setTime( int h, int m, int s )

{ hour = h ; minute = m ; second = s ; }

void Time::printTime()

{ cout << hour << ":" << minute << ":" << second ; }

// ==> Use such as in main();

{

Time noon, midnight; // Constructor automatically called

noon.setTime(12, 0, 0) ; // Send a message to noon

noon.printTime() ; // Send a message to noon

...

} // destructors are called

c© A. Amer C++ classes 51

Class design in C++

Lecture Outline:C++ classes

Creating objects

Review: call/return by value/reference

Assignment operator

Default & general constructor

Destructor

Pointers & objects

Objects and call-by-value

Copy constructor

Hidden function calls in OOP

struct or class ?

Constant members

Constant objects

Static members

Friend functions

inline functions

Function overloading

Operator overloading

this pointer

Data type Casting

c© A. Amer C++ classes 52

Pointers & Objects

Two cases:1 A pointer to an object: Student *p;

2 A class with pointer members class Student .. char *fname; ;

Objective: to dynamically allocated memorya constructor to allocate memory dynamicallya destructor to delete the dynamically allocated memorya copy constructor to make a copy of the dynamicallyallocated memoryan overloaded assignment operator to make a copy of thedynamically allocated memory

⇒ memory allocation and deallocation are handled correctly

c© A. Amer C++ classes 53

Pointers & Objects

C++ goal:treat programmer-defined types in the same way as built-in types

Pointers to named and unnamed objects

int * pi = new int; //Create a new integer

double * pd = new double(3.14); //Create and initialize a new double

int * par = new int[2000]; //Create a new integer array of size 2000

...

par = new int[10]; // dynamic compared to int A[2000];

Time * Pnoon = new Time(12,0,0); //Create a new object

Pnoon->setTime(24,0,0);

Time t, * pT = &t;

pT->setTime(13,15,0);

c© A. Amer C++ classes 54

Pointers & Objects

Arrow Operator

Time t, * pT = &t ;

pT->setTime(13, 15, 0) ;

pT->printTime() ;

Dot operator

Time t, * pT = &t ;

( * pT).setTime(13, 15, 0) ;

( * pT).printTime() ;

Note:

t.setTime(3,7,0); // . dot operator

pT->setTime(13, 15, 0); // -> arrow operator

void Time::setTime(int,int,int); // :: scop/resolution o perator

c© A. Amer C++ classes 55

Pointers & Objects

int main() {

Time t;

Time * pt = &t;

pt->setTime(13,15,0);

pt->printTime();

return 0;

}

..

..

.

.

0x1000

13150

Memory mapAddress

0x10000x10010x1002

0x1???

t

pt

c© A. Amer C++ classes 56

Pointers & Objects

Memory management by server object

// Listing 9.3: Using the destructor to return heap memory

// allocated to named and to unnamed objects.

class Name {

private:

string initials;

char * contents; // pointer to dynamic memory

public:

Name (string init, char * aname);

Name (char * aname); // what constructor?

void show_name();

˜Name(); // destructor eliminates memory leak

} ;

c© A. Amer C++ classes 57

Pointers & Objects

Name::Name(string init, char * aname) { // general constructor

int len = strlen(aname); // number of characters

contents = new char[len+1]; // allocate dynamic memory

if (contents == NULL) // ’new’ was not successful

{ cout << "Out of memory\n"; exit(1); } // give up

strcpy(contents, aname); // string copy

initials = init;

}

void Name::show_name() { cout << initials << " " << contents < < "\n"; }

c© A. Amer C++ classes 58

Pointers & Objects

Name::˜Name() { // destructor eliminates memory leak

delete [] contents; // it deletes heap memory, NOT pointer ’c ontents’

}

void client () { // a free function

Name n1("JB","Jones Blonde"); // n1 is a named object

n1.show_name(); // what is in n1.contents ?

Name n2("FB","Frank Bond"); // what is in n2.contents ?

Name * p = new Name("SS","Smith Smart"); // unnamed object

p->show_name(); // what is in p->contents ?

delete p; // p is deleted =>

// destructor for object pointed to by p is called

} // n1 destroyed => destructor for object n1 is called

c© A. Amer C++ classes 59

Objects and call-by-value

Always pass an object to a function by reference, not by value

Always label passed objects as constif the function does not change their state

void myfunc(cls1 &obj, ...) { obj.set(); ...} // may change o bj

void myfunc(const cls1 &obj, ...) { ...} // cannot change obj

Why? Because an object may include a pointer data member

Passing objects with pointers to functions by value invokes abitwise copy of the object

(Recall: creating a copy involves the class copy constructor)

This results in two objects pointing to the same location!

c© A. Amer C++ classes 60

Objects and call-by-value

When the scope of the function ends,the copy of the object is destroyed (destructor is called)

The destructor frees the memory referenced by the both theoriginal and the copy pointers

Attempting to access the space of the original objectin the caller will cause "mysterious things" (e.g., program crash)

c© A. Amer C++ classes 61

Objects and call-by-value

(Member) function returning objects:

Point closestPointVal(Point& ); //returns object - slow

Point * closestPointPtr(Point& ); //returns pointer to object -fa ster

Point& closestPointRef(Point& ); //returns reference

Be careful when returning a pointer to an object:you may accidently change the object, another object maychanges its status!

Balance efficiency (e.g., speed of a program) anddesign/maintainability

Better? A slower program or risk and confusion of results?

Avoid returning objects from functions: do it only if reallynecessary

c© A. Amer C++ classes 62

Copy constructor

Types of constructors:

Constructor provided by the compiler√

Default constructor – no arguments√

General constructor – with arguments√

Conversion constructor – with one argumentof a different type than the class

Copy constructor – with one argument of the same class

c© A. Amer C++ classes 63

Copy constructor

During the life of an object,its properties (e.g., member variables) may change

Can you duplicate an object?

Copy constructor: creates a duplicate of the object as it is, atinstantiation time

The copy constructor bares the same name as the constructor

A copy constructor is an overloaded version of a constructor

c© A. Amer C++ classes 64

Copy constructor

Call-by-value makes a copy of the object

Call-by-reference is significantly more efficientif the objects are large

The copy constructor has one parameter:a reference to the same class object

Thus a copy constructor must follow this format

Point::Point(const Point&)

Examples:

class Point {...};

Point N; Point Q = N; // copy constructor called

Point S(N); // copy constructor called

c© A. Amer C++ classes 65

Copy constructor: how it works?

What happens if you do not provide one?

C++ provides an implicit copy constructor with all objects

The compiler’s copy constructor copies eachdata member of the object

It does a bitwise copy

Example:

class Text {.... private: char * text; };

The compiler’s copy constructorwill copy the pointernot the string (content) itself

This may create dangling pointers

c© A. Amer C++ classes 66

Copy constructor: how it works?

Example:If you pass a Text object to a function,both the caller and the function will have pointers tothe same Text (as if it had been passed by reference)If you delete a Text object,you will probably create dangling pointers

Thus for classes with pointer members,you should write a copy constructor

c© A. Amer C++ classes 67

Copy constructor: Example

class Student {

public:

Student(char * , char * , int) ; //Constructor

Student( const Student & ) ; //Copy Constructor

˜Student() ; //Destructor

private:

char * fname ;

char * lname ;

int id ;

};

c© A. Amer C++ classes 68

Copy constructor: Example

// Constructor: Student John("John","Young",1234567);

Student::Student(char * pF, char * pL, int idnum) {

id = idnum ;

fname = new char[ strlen(pF)+1 ] ;

lname = new char[ strlen(pL)+1 ] ;

strcpy(fname, pF) ;

strcpy(lname, pL) ;

}

//Copy Constructor: Student Frank(John);

Student::Student( const Student & stud ) {

id = stud.id ;

fname = new char[ strlen(stud.fname)+1 ] ;

lname = new char[ strlen(stud.lname)+1 ] ;

strcpy(fname, stud.fname) ;

strcpy(lname, stud.lname) ;

}

c© A. Amer C++ classes 69

Copy constructor: Example

//Destructor

Student::˜Student() { // Clean up

delete [] fname ;

delete [] lname ;

}

c© A. Amer C++ classes 70

Copy constructor: When it is Called?

Explicitly:when initializing an object with the same data attributesas an already created object// First create an object to be copied, constructor is called !

Student John("John", "Young" , 1234567) ;

Student SomeoneElse(John) ; // calls copy constructor

OR

Student SomeoneElse = John ; // calls copy constructor

// SomoneElse is destination or target object

// John is the source object

Student JohnDoe; // calls default constructor

JohnDoe = John; // assignment operator is used

c© A. Amer C++ classes 71

Copy constructor: When it is Called?

Implicitly:

when passing an object as a function parameter AND

when returning an object by-value from a function

// A copy of the argument is created on the stack.

// The copy constructor is called on entry,

// (and the destructor is called at exit from the function)

void func1(Student std);

Student a;

func1(a); // call-by-value

c© A. Amer C++ classes 72

Class design in C++

Lecture Outline:C++ classes

Creating objects

Review: call/return by value/reference

Assignment operator

Default & general constructor

Destructor

Pointers to objects

Objects and call-by-value

Copy constructor

Hidden function calls in OOP

struct or class ?

Constant members

Constant objects

Static members

Friend functions

inline functions

Function overloading

Operator overloading

this pointer

Data type Casting

c© A. Amer C++ classes 73

Hidden function calls in OO programs

Learn to see calls to default constructor,conversion constructor, copy constructor,& destructor in a C++ code

Avoid returning objects from functions (as a copy is made!)

Avoid passing objects by value (as a copy is made!)

c© A. Amer C++ classes 74

struct or class to define classes?

To declare a class: “struct” or “class” are possible

struct:Members (data and functions) public by defaultNo default constructor/destructor

classMembers (data and functions) private by defaultDefault constructor/destructor are created by compiler

→ Do not rely on defaults→ Specify rights explicitly→ Call a class “a class”

c© A. Amer C++ classes 75

const member functions

const int x =5;

void foo(const int x, int *y);

class Point

{

int x, y; // private coordinates

public:

Point ();

void setPoint (int a, int b); // modifier function

void getX() const; // selector function

void getY() const;

...

} ;

a const method cannot change data

c© A. Amer C++ classes 76

const member functions

can call const member function even when the objectof that class is const

class A {

....

int getD() const; //an accessor

};

// -->Use:

const A x(1234,3.5); // constructed with some initial value s

x.getD(); // Only ok when ‘getD()’ is marked ‘const’

Member functions should be marked const if and only if it isguaranteed that by calling them the object is not changed.

Trying to use const for class member functions forother reasons is wrong

c© A. Amer C++ classes 77

Constant Objects

const Time noon( 12, 0, 0 ) ;

noon.printTime() ;

To allow a constant Time object to be created a constructormust be provided to initialize the data members

To allow a constant Time object to call a member function,the function must be declared const

class Time {

public:

Time( int = 0, int = 0, int = 0 ) ;

void printTime() const ;

private:

int hour ; int minute ; int second ;

} ;

c© A. Amer C++ classes 78

Constant Objects

If you create a constant object, then you cannot modifyany of its member data after the object is created

Invoking a non-constant member function ona constant object is a syntax error

A constant member function may not modify member data

Member functions may be overloaded bydeclaring one of them const

Constant object would use the const function

c© A. Amer C++ classes 79

Static members

Assuming you want to count all Point objects you created

class Point {

int x, y; // each object has (x,y)

int count; // <=== But you need only one counter?

};

static int x; // in a file: x is globally visible

static int x; // in a func.: x still visible even if the func. te rminates

static class member:

class Point {

int x, y; // each object has private coordinates

static int count; // all objects has one static data

... };

static member: there is only one instance of that memberfor all objects of the class

c© A. Amer C++ classes 80

Static members

// Listing 9.5: Using a global variable to count object insta nces.

int count = 0; // does maintainer know it belongs to Point?

class Point {

private: int x, y; // private coordinates

public:

Point (int a=0, int b=0) { // general constructor

x = a; y = b; count++;

cout << " Point created: x=" << x << " y=" << y << endl; }

void set (int a, int b) // modifier function

{ x = a; y = b; }

void get (int& a, int& b) const // selector function

{ a = x; b = y; }

void move (int a, int b) // modifier function

{ x += a; y += b; }

˜Point() // destructor

{ count--;

cout << " Point destroyed: x=" << x << " y=" << y << endl; }

} ;

c© A. Amer C++ classes 81

Static members

int quantity() // access to global variable

{ return count; }

int main() {

cout << "Number of points: " << quantity() << endl;

Point * p = new Point(80,90); //dynamically allocated Point object

Point p1, p2(30), p3(50,70); //point of origin, x-axis, gen eral point

cout << "Number of points: " << quantity() << endl;

return 0; // dynamic object is not properly deleted

}

c© A. Amer C++ classes 82

Static members

// Listing 9.6: Using static data members and member functio ns.

class Point {

int x, y; // private coordinates

static int count;

public:

// default and conversion constructor are defined

Point (int a=0, int b=0) // general constructor

{ x = a; y = b; count++;

cout << " Point created: x=" << x << " y=" << y << endl; }

static int quantity() // const is not allowed

{ return count; }

//... set, get, move, ..

˜Point() // destructor

{ count--;

cout << " Point destroyed: x=" << x << " y=" << y << endl; }

} ;

c© A. Amer C++ classes 83

Static members

The declaration of a static data member in a class is not adefinition

You must define the static member outside of the classdeclaration

Once defined, it exists even though no objects exist

int Point::count = 0; // define it

int main() {

cout << " Number of points: " << Point::quantity() << endl;

Point p1, p2(30), p3(50,70); // point of origin, x-axis, gen eral point

cout << " Number of points: " << p1.quantity() << endl;

return 0;

}

c© A. Amer C++ classes 84

Static data members

Static data members are created once for the class

Can be accessedby any member function of that same class, ORby using the scope resolution operator ::

Must be initialized at file scope

c© A. Amer C++ classes 85

Static data members

//declaration

class CountExample() {

public:

CountExample() ; // Constructor

˜CountExample() ; // Destructor

private:

static int count ;

} ;

//definition

int CountExample::count = 0 ; // Initializer at file scope

CountExample::CountExample() { count++ ; }

CountExample::˜CountExample() { count-- ; }

c© A. Amer C++ classes 86

Static Member Functions

When no object of a class exist (is declared) staticmembers functions only have access to static member data

Such member functions may be called by using the scoperesolution operator ::

c© A. Amer C++ classes 87

Static Member Function Example

class CountExample {

public:

CountExample() ; // Constructor

˜CountExample() ; // Destructor

static int getCount() { return count ; }

private:

static int count ;

} ;

int CountExample::count = 0 ; // Initializer at file scope

CountExample::CountExample() { count++ ; }

CountExample::˜CountExample() { count-- ; }

c© A. Amer C++ classes 88

Static Member Function Example

int main() {

{

CountExample cnt1 ; // created inside

CountExample cnt2 ; // the block

cout << cnt1.getCount ; // prints 1

cout << cnt1.getCount ; // prints 2

} // Block is exited => cnt1 and cnt2 destroyed

cout << CountExample::getCount() ; // prints 0

return 0 ;

}

c© A. Amer C++ classes 89

Class design in C++

Lecture Outline:C++ classes

Creating objects

Review: call/return by value/reference

Assignment operator

Default & general constructor

Destructor

Pointers to objects

Objects and call-by-value

Copy constructor

Hidden function calls in OOP

struct or class ?

Constant members

Constant objects

Static members

Friend functions

inline functions

Function overloading

Operator overloading

this pointer

Data type Casting

c© A. Amer C++ classes 90

Friend functions

A friend function of a class is defined outside the class scope

But has access to all private data members and memberfunctions

By convention: put friend declarations beforepublic and private specifiers(This makes the friend default to what?)

But: a class doesn’t control the scope of friend functions& public and private don’t apply to them

Friendship is granted, not taken

c© A. Amer C++ classes 91

Friend functions

A friend function is a function that a class permits to haveaccess to an object’s private data members

Friend functions are NOT member functions of the class butfree functions which have been given access to a data member

Friend functions are implemented without the scope resolutionoperator

c© A. Amer C++ classes 92

Friend functions

// declaration

class Complex {

//class Complex "Grants" addComplex() function access to p rivate members

friend Complex addComplex( const Complex &, const Complex & ) ;

public:

Complex(float = 0, float = 0) ; // Constructor void printComp lex() ;

private:

float real ; float imag ;

} ;

// definition

Complex addComplex( const Complex & Z1, const Complex & Z2 ) {

Complex RetC ;

RetC.real = Z1.real + Z2.real ;

RetC.imag = Z1.imag + Z2.imag ;

return RetC ;

}

c© A. Amer C++ classes 93

Friend classes

A class may be declared as a friend to another class

Example 1:

class ClassOne {

friend class ClassTwo ;

public:

...

private:

...

} ;

→ ClassOne has granted ClassTwo access to all members→ This does not imply that ClassOne has accessto the private members of ClassTwo

c© A. Amer C++ classes 94

Friend classes

Example 2:Librarian class is declared as a friend of the Book classAs such, functions within the librarian class can directlyaccess Book class’ private members and functions

c© A. Amer C++ classes 95

Friend classes

class Book {

friend class librarian; // friends

public:

Book(char * , char * , char * );

void show_book(void);

private:

char title[64];

char author[64];

char catalog[64];

};

//implementation of member functions....

class Librarian {

public:

void change_catalog(Book * , char * ); //cal by pointers

char * get_catalog(Book);

};

//implementation of member functions....

c© A. Amer C++ classes 96

Friend classes

// Use

void main(void) {

Book programming("C++/OOP", "Author", "P300");

Librarian library;

programming.show_book();

library.change_catalog(&programming, "EASY C++ 101");

programming.show_book();

//programming.get_catalog(..) is wrong! WHY?

}

Question: the relationship between Book and Librarian is friendship;Why not using inheritance?

c© A. Amer C++ classes 97

Inline functions: review

Inline functions:used to reduce the overhead of a normal function callDeclaration:

inline int mean(int i, int j)

{ return (i + j)/2; }

The inline specifier signals to the compilerinstead of transferring control to and from the function codesegment, a modified copy of the function body may besubstituted directly for the function call

c© A. Amer C++ classes 98

Inline functions: review

An inline function can be declared and definedsimultaneously as ininline int mean(int i, int j); { return (i + j)/2; }Note that the definition includes both the declaration andbody of the inline function

If it is declared with the keyword inline, it can bedeclared without a definition

The inline expansion of a function may not preservethe order of evaluation of the actual arguments

c© A. Amer C++ classes 99

Inline functions and classes

Both member and non-member functions can be inlineDeclare a member function inline:

inline void Time::printTime()

{

cout << hour << ":" << minute << ":" << second ;

}

The use of the inline specifier does not changethe meaning of the function

Why?

c© A. Amer C++ classes 100

Inline functions and classes

Because the compiler integrates the function’s code into thecode for its callers

This makes execution faster by eliminating the function-calloverhead

Moreover, constant arguments, permit simplificationsat compile time

This means not all of the inline function’s code needsto be included

c© A. Amer C++ classes 101

Function name overloading

Function name overloading: defining functions with the samename that take different arguments

float mean(int a, int b)

{ return (a+b)/2; }

float mean(int a, int b, int c) // mean() is an overloaded func tion

{ return (a+b+c)/3; }

float mean(float a, float b) // Another overloading for mean ()

{ return (a+b)/2; }

If called with 2 int arguments, avg = mean(5, 10);, the firstdefinition is used

If called with 3 int arguments, avg = mean(5, 10, 15);,the second definition is used

what about avg = mean(4.0, 8.5, 7.5); ?

c© A. Amer C++ classes 102

Function name overloading

Function name overloading:defining functions with same name but with arguments ofdifferent typesadd(int a, long b); and add(long a, int b);

Overloading is resolved byfinding the “best match” among all possible matches

c© A. Amer C++ classes 103

Operator overloading

C++ operators: +, ∗, /, ++, >>, <<, etc.Binary operator z=x+y;Unary operator z++;x += y; //x is left-hand (LH) object,y is right-hand (RH) objectx is target object, y is the source object

C++ goal: treat programmer-defined data types in the same way as built-in types

Time t,t2,t3;

t3=t1+t2; cout << t3;

t3++; cout << t3;

c© A. Amer C++ classes 104

Operator overloading

Solution:Extend built-in operators so that the same expressionsyntax with operator can be applied to objects

Example:

int a=5,b=3; a +=b;

cout << x;

Complex x(20,40), y(30,50); x +=y; // => x=(20+30) + i(40+50 )

cout << x;

Note that private data can be accessed or modified only whileINSIDE *a* member function

c© A. Amer C++ classes 105

Operator overloading: Example

// Declaration

class Time

{

friend ostream& operator <<(ostream & out, const Time& t); / /overload <<

public:

// constructors, etc.

Time operator+(const Time &t); // Overload the binary + oper ator

...

private:

int hour, minute, second;

};

c© A. Amer C++ classes 106

Operator overloading: Example

Time Time::operator+ (const Time &t) // overload the binary += operator

{

hour += t.hour;

minute += t.minute;

second += t.second;

}

ostream& operator <<(ostream & out, const Time& t)

{

out << t.hour << ":" << t.minute << ":" << t.second ;

return out;

}

c© A. Amer C++ classes 107

Operator overloading: Example

// --> USE

Time t(0,50,0),p(12,0,10),q;

cout<<q; // same as cout.operator<<(q)

q = p+t; // the same as q = p.operator+ (t)

cout << q; // 12:50:10

More in coming lectures

c© A. Amer C++ classes 108

Function Overriding

Function Overriding: redefinition of a function byproviding a different function body butkeeping the exact same function name and arguments

Thus an overrided function has different behaviorwhen called for different objects

Attention: sometimes the words overloading andoverriding are mixed up

Overriding functions are used with inheritance

More in coming lectures

c© A. Amer C++ classes 109

this pointer

Every object that gets created has access toits own address = this pointer

It is like a constant private "implicit" data member

this: a constant pointer that points to the object for which amember function is invoked

Every member function (not friends nor static) has accessto the this pointer

Its main use is for defining member functions that manipulatepointers directly

c© A. Amer C++ classes 110

this pointer

const member functions receive a constant this pointer toconstant data

Non-const member functions receive a constant this pointer tonon-constant data

class pt2d

{

private: int x, y;

public:

...

void move(int r, int s); //move to (r,s)

void move(pt2d p); // move to p

};

c© A. Amer C++ classes 111

this pointer

void pt2d::move(pt2d p)

{ x=p.x; y=p.y; // move point to p}

void pt2d::move(int r, int s)

{

this->x=r; // move point to (r,s)

this->y=s;

// the keyword this refers to a constant pointer that points t o

//the object for which a member function is invoked.

}

// -->USE

pt2d a(0,0), b(5,0), c(3,-40);

a.move(23,-3);

b.move(c);

Note:

Using this when referring to members is usually unnecessary

c© A. Amer C++ classes 112

this pointer: example

Its main use: defining member functions thatmanipulate pointers directly

Point::Point closestPointVal(Point& pt) {

if( (x * x + y * y) < (pt.x * pt.x + pt.y * pt.y) )

return * this; //this is a keyword denoting a pointer

// to the target object of the message

else

return pt;

}

// -->USE

Point p1,p2;

p1.setPoint(20,40); // set points

p2.setPoint(30,50);

Point q = p1.closestPointVal(p2); //this is object p1

//fields of the closest point are copied

c© A. Amer C++ classes 113

Type casting

Casting is converting a value of one type into a valueof another type

int x = 231;

int y = x/4; // you meant float; no casting but truncation occu rs

int x; double y;

x= int(’A’); // explicit casting x=65

y = (double) x; // explicit casting (old way)

double * p =&y; // correct pointer type

int * q = (int * ) p; // int q points to double!!??

int x; double y;

x=’A’; y=x; // implicit casting

c© A. Amer C++ classes 114

Casting and objects

Conversion constructor is a casting mechanism

Example with Rational class

// general, conversion, and default constructor

Rational::Rational(long n=0, long d=1) {

nmr=n; dnm=d;

this->normalize();

}

Rational c=5; // implicit casting equivalent to ’Rational c = (Rational)

Rational b=a+5; // 5 is converted to 5/1

The conversion constructor is called each time a function thatexpects a Rational parameter is called with an actual numericargument

c© A. Amer C++ classes 115

C++ classes: Summary

Lecture Outline:C++ classes

Creating objects

Review: call/return by value/reference

Assignment operator

Default & general constructor

Destructor

Pointers to objects

Objects and call-by-value

Copy constructor

Hidden function calls in OOP

struct or class ?

Constant members

Constant objects

Static members

Friend functions

inline functions

Function overloading

Operator overloading

this pointer

Data type Casting

c© A. Amer C++ classes 116