Lecture09

Post on 09-Jul-2015

69 views 0 download

Tags:

Transcript of Lecture09

1/27

Learn about:

i) More info on member access specifiers

ii) Constant Objects and Functions

iii) Array of Objects

iv) Objects as Function Arguments

v) Returning Objects from Functions

Lecture 09

Classes and Objects

2/27

Access Specifiers• What is access specifier?

– It is the one which specifies which member can be accessed at which place.

– Types of access specifiers :

• There are three namely,

– Private

– Public » A class's public members can be accessed by any

function in a program. Used as an interface of the class - Other objects can use it .

– Protected.

ob1 ob2

Friend Ob

Data Hiding

3/27

Member access specifiers (page164-176)

public

private

Kitty

public

private

friend of Kitty

public

private

Snoopy

4/27

How to access the members ?

• If the data members of the class is – Private :

• Cannot access directly outside the class• How to access ?

– We should use member functions to access it.

– EG : data member ----> int a;

» int main( )

» { object name.member function( argument ) }

– Public :• can access outside the class

• EG : object name . Datamembername = value;» ob1.a = 9; Example - Next slide

5/27

A Simple Class

#include <iostream.h> class Student // class declaration { private: int idNum; //class data members double gpa;

public: void setData(int id, double result) { idNum = id;

gpa = result; }

void showData() { cout << ”Student Id is ” << idNum << endl;

cout << ”GPA is " << gpa << endl; } };

can only be accessed within class

accessible from outside and within class

6/27

A simple program example

#include <iostream.h>

class Student{ public: int idNum; double gpa; void setData(int, double); void showData();};

//Implementation - refer to notes page 1 (Lecture 9).

void main() { Student s1, s2, s3; s1.setData(10016666, 3.14); s2.setData(10011776, 3.55);

s3.idNum = 10011886; s3.gpa = 3.22;

::

}

Okay, because idNumand gpa are public.

7/27

A simple program example

#include <iostream.h>

class Student{ private: int idNum; double gpa; public: void setData(int, double); void showData();};

//Implementation - refer to notes page 1 (Lecture 9).

void main() { Student s1, s2, s3; s1.setData(10016666, 3.14); s2.setData(10011776, 3.55);

s3.idNum = 10011886; s3.gpa = 3.22;

::

}

Error!!! idNumand gpa are private.

8/27

class student {

private:

char sid[20]; char name[20]; int semester;

int year; float marks[4]; float average;

public:

// …

void print( ) ;

void compute_average( )

{ average = (marks[0]+ marks[1]+ marks[2]+ marks[3])/4; }

};

student (char [], char [], int sem =1 , int yr = 1);

Another program example

9/27

// class function members implementation

student :: student (char id[20], char nama[20], int sem =1 , int yr = 1 ) { strcpy (name, nama); strcpy (sid, id); year = yr; semester = sem; }

void student :: print ( ) { cout << “Student Id:”<<sid<<endl; cout << “Student Name:”<<name<<endl; cout << “Semester:”<<semester<<endl;}

default arguments

Another program example

10/27

student (char [] id, char [] nama, int sem =1 , int yr = 1)

void print()

void compute_average()

sid name

..

.

semesteryear

average

marks

Private members cannot be accessed from outside the class

That’s why, we use public methods to access themcompute_average(...)set_marks (...)

void set_marks (float [])..

.

......

student

Public members

Private members

11/27

main (){ student a_given_student (“9870025”, “Omar”, 2, 2);

// I want to change his semester to 3a_given_student. semester = 3 // ILLEGAL

// why? Because semester is a private data member and cannot //be accessed outside the class student...}

// This is instantiation.//The object a_given_student is created and the constructor is //automatically called to initialise that data members of a_given_student with

Another program example

12/27

Then, how can we access semester and change it?

2 options:

Option 1We must define a new function member (public) to access semester

class student { private:

….

int semester;…

public: …void set_semester(int sem =1)

{semester = sem;}…

};

main (){student a_given_student (“9870025”, “Omar”, 2, 2);

// I want to change his semester to 3a_given_student. set_semester( 3 ) ;…}

Another program example

13/27

no need!

class student { private:

…. public : int semester;

…public: … void set_semester(int sem =1) {semester = sem;}...};

main (){student a_given_student (“9870025”, “Omar”, 2, 2);

// I want to change his semester to 3a_given_student.semester = 3;…}

Option 2

We must change the access specifier of semester, and make it public.

Another program example

14/27

• Some objects need to be modifiable and some do not.

• The keyword const is used to specify an object is not modifiable, and any

attempt to change the object will produce a syntax error. For example

const Model m1; or Model const m1;• const objects can only invoke their const member functions.

void showInfo() const

{ ……. }

• const declaration is not required for constructors and destructors of const objects

Model () const

{ ……… }

Constant Object

15/27

Constant objects

#include <iostream.h> class Part { private: int modelnumber; int partnumber double cost; public: Part(int mn, int pn, double c);

void setpart(int mn, int pn, double c) const;

void showpart() const; };

// Implementation - refer to page 5 Lecture 9

void main() { Part part1(8678, 222, 34.55); Part const part2; part2.setpart(2345, 444, 99.90); part1.showpart(); part2.showpart()

}

16/27

Constant objects

class Student{private: int age;

int semester; int year;

public: Student (int, int , int); // constructor

void set_semester(int sem =1){semester=sem;} //to set semester with sem (1 by default)

void print( ) const;};

// print is a constant function member// meaning, it cannot modify any of // the data members

17/27

Student::Student (int sem=5, int ag=20, int yr =1){ age=ag; year = yr; semester = sem; }

void Student::print( ) const { cout <<"AGE:"<<age<<endl <<"Year:"<<year<<endl<<"semester:"<<semester<< endl; semester = 10; // illegal }

Cause print is const and therefore can just access data memberswithout altering their values

We cannot set any data member with a valuewhy?

Constant objects

18/27

int main(){ student h1; const student h2 (4,4,4); // or student const h2(4,4,4); h1.set_semester(5); // valid h2.print(); // valid h2.set_semester(5); h2.print(); h1.print();}

EXCEPTION, constructors can still be used by constant objects

Normally invalidwhy?

Cause we choose h2 as a constant objectSO, there should be no member function that can alter its data members

Constant objects

19/27

• Constructors and destructors are inherently non constant function members

• Choose your function members that just query data members to be constants

return_type function_name (type1 par1, ..) const{… }

Syntax:

• If you choose to work with constant objects, normally all (but constructor and destructor) your function members should be constants

Constant objects

20/27

Array of Objects (page87-88)

class Student { private:

char sid[20];char name[20];int sem;

public: Student (char [], char [], int); void print( ) ; void set_semester(int s ) { sem = s;}};

Student(...)

void print()

void set_semester(int)

sem

name

Student

.

.

.

...sid

...

21/27

int main (){student FIT[3]; // declares an array called FIT with three elements

// the elements are objects of type (class) student

FIT[1].set_semester(2); // access the 2nd object of the array // and invokes its method member to set // its data member

...}

22/27

FITArray Name

0 1 2index

I want to set the semester of the 2nd array element with 3

student(...)

void print()

void set_semester()

sem

name...

sid...

3

student(...)

void print()

void set_semester()

sem

name...

sid...

student(...)

void print()

void set_semester()

sem

name...

sid...

1st array element 2nd array element 3rd array element

FIT[1].set_semester(3)

23/27

Objects As Function Arguments:A Diagram (page133-144)

dist3 feet inches

add_dist(Distance, Distance);

feet inchesdist1

add_dist(Distance, Distance);

inches = dist1.inches + dist2.inches;

dist3.add_dist(dist1, dist2)

feet inchesdist2

add_dist(Distance, Distance);

24/27

#include <iostream.h> class Distance{ public: Distance(); // default constructor Distance(int, float); // two-argument constructor void getdist(); void showdist(); void add_dist(Distance, Distance); private: int feet; float inches; };

Objects As Function Arguments:A Program

25/27

Distance::Distance() { feet = 0; inches = 0; }

Distance::Distance(int ft, float in): feet(ft),inches(in) { }

void Distance::getdist(){ cout << "\nEnter feet: "; cin feet; cout << "Enter inches: "; cin inches; } void Distance::showdist(){

cout << feet << "\'-" << inches << '\"'; }

Objects As Function Arguments:A Program

26/27

void Distance::add_dist(Distance d1, Distance d2) { inches = d1.inches + d2.inches; feet = 0; if (inches = 12.0) { inches = inches - 12.0; feet++; } feet = feet + (d1.feet + d2.feet); }

Objects As Function Arguments:A Program

27/27

int main() { Distance dist1, dist3; Distance dist2(11, 6.25); dist1.getdist(); //get dist1 from user dist3.add_dist(dist1, dist2); cout << "\ndist1 = "; dist1.showdist(); cout << "\ndist2 = "; dist2.showdist(); cout << "\ndist3 = "; dist3.showdist(); cout << endl; return 0; }

feet = 0inches = 0Distance()Distance(int, float)void getdist()void showdist()void add_dist()

feet = 0inches = 0Distance()Distance(int, float)void getdist()void showdist()void add_dist()

feet = 11inches = 6.25Distance()Distance(int, float)void getdist()void showdist()void add_dist()

dist1 dist2 dist3

Objects As Function Arguments:A Program

28/27

Returning Objects From FunctionsA Diagram

dist1 feet inches

add_dist(Distance);

feet inchesdist2

add_dist(Distance);

temp.inches = inches + dist2.inches;return temp;

dist3 = dist1.add_dist(dist2)

feet inchestemp

add_dist(Distance);

29/27

Returning Objects From FunctionsExample

class Distance { . . . Distance add_dist(Distance); };

Distance Distance::add_dist(Distance d2) { Distance temp; temp.inches = inches + d2.inches; if(temp.inches = 12.0) { temp.inches -= 12.0; temp.feet = 1; } temp.feet += feet+d2.feet; return temp; }

int main() { . . . dist3=dist1.add_dist(dist2); . . . }