lecture 9

24
AU/MITM/1.6 By Mohammed A. Saleh 1

Upload: mohammed-saleh

Post on 22-Dec-2014

189 views

Category:

Education


1 download

DESCRIPTION

Classes in C++

TRANSCRIPT

Page 1: Lecture 9

AU/MITM/1.6

By Mohammed A. Saleh

1

Page 2: Lecture 9

Abstraction and Classes. One way we cope with complexity is to

frame simplifying abstractions. Abstraction is the crucial step of representing

information in terms of its interface with the user.

You abstract the essential operational features of a problem and express a solution in those terms.

From abstraction, it is a short step to the user-defined type, which in C++ is a class design that implements the abstract interface.

2

Page 3: Lecture 9

Classes in C++ A class is a C++ vehicle for translating an

abstraction to a user-defined type. It combines data representation and methods

for manipulating that data into one neat package.

Generally, a class specification has two parts:1. A class declaration, which describes the data

component, in terms of data members, and the public interface, in terms of member functions, termed methods. 3

Page 4: Lecture 9

2. The class method definitions, which describe how certain class member functions are implemented.

The class declaration provides a class overview, whereas the method definitions supply the details.

Developing a class and a program using it requires several steps.

Lets look at a tentative class declaration for a class called Stock.

4

Page 5: Lecture 9

// beginning of stocks.cpp file #include <iostream> #include <string>class Stock // class declaration{ private:

char company[30];int shares; double share_val; double total_val; void set_tot() total_val = shares * share_val; }

public:void acquire(const char * co, int n, double pr); void buy(int num, double price); void sell(int num, double price); void update(double price); void show(); }; // note semicolon at the end 5

Page 6: Lecture 9

The C++ keyword class identifies the code The syntax identifies Stock as the type name

for this new class. This declaration enables you to

declare variables, called objects, or instances, of the Stock type.

Each individual object represents a single holding. For example, the declarations,Stock sally; Stock solly;create two Stock objects called sally and solly.

6

Page 7: Lecture 9

New are the keywords private and public. These labels describe access control for class members.

Any program that uses an object of a particular class can access the public portions directly.

A program can access the private members of an object only by using the public member functions.

7

Page 8: Lecture 9

For example, the only way to alter the shares member of the Stock class is to use one of the Stock member functions.

The public member functions act as go-betweens between a program and an object’s private members; they provide the interface between object and program

This insulation of data from direct access by a program is called data hiding

A class design attempts to separate the public interface (abstraction) from the specifics of the implementation.

8

Page 9: Lecture 9

Gathering the implementation details together and separating them from the abstraction is called encapsulation.

Instances of encapsulation: Data hiding - hiding functional details of an

implementation in the private section Placing class function definitions in a

separate file from the class declaration.

9

Page 10: Lecture 9

Member Access Control: Public or Private? One of the main precepts of OOP is to hide

the data, data items normally go into the private section and member functions that constitute the class interface go into the public section.

You can also put member functions in the private section.

The keyword private is a default access control in class objects.

10

Page 11: Lecture 9

class World {

float mass; // private by default char name[20]; // private by default

public:void tellall(void); ...

};

11

Page 12: Lecture 9

Implementing Class Member Functions Member function definitions are much like

regular function definitions Each has a function header and a function

body. Member function definitions can have return types and arguments. But they also have two special characteristics:

a) When you define a member function, you use the scope-resolution operator (::) to identify the class to which the function belongs

b) Class methods can access the private components of the class.

12

Page 13: Lecture 9

For example the header for the update() would look like this:void Stock :: update(double price)

This notation means you are defining the update() function that is a member of the Stock class

The scope-resolution operator resolves the identity of the class to which a method definition applies.

The complete name of a class method includes the class name. Stock::update() is called the qualified name of the function

13

Page 14: Lecture 9

The second special characteristic of methods is that a method can access the private members of a class.

For example, the show() method can use code like this:cout << “Company: “ << company

<< “ Shares: “ << shares << endl << “ Share Price: $” << share_val << “ Total Worth: $” << total_val << endl;

Here company, shares, and so on are private data members of the Stock class

14

Page 15: Lecture 9

//more stocks.cpp -- implementing the class member functionsvoid Stock::acquire(const char * co, int n, double pr) { strncpy(company, co, 29); // truncate co to fit companycompany[29] = ‘\0’; if (n < 0) { cout << “Number of shares can’t be negative; “

<< company << “ shares set to 0.\n”; shares = 0; }

else shares = n; share_val = pr;set_tot(); }void Stock::buy(int num, double price) {if (num < 0) { cout << “Number of shares purchased can’t be negative. “

<< “Transaction is aborted.\n”; }15

Page 16: Lecture 9

else { shares += num;share_val = price; set_tot(); } }void Stock::sell(int num, double price) {if (num < 0) { cout << “Number of shares sold can’t be negative. “

<< “Transaction is aborted.\n”; }else if (num > shares) { cout << “You can’t sell more than you have! “

<< “Transaction is aborted.\n”; } else { shares -= num; share_val = price; set_tot(); } }

16

Page 17: Lecture 9

void Stock::update(double price) { share_val = price; set_tot(); }

void Stock::show() {using std::endl; cout << “Company: “ << company << “ Shares: “ << shares << endl

<< “ Share Price: $” << share_val << “ Total Worth: $” << total_val << endl; }

Member Function Notes The acquire() function manages the first acquisition

of stock for a given company, whereas buy() and sell() manage adding to or subtracting from an existing holding

17

Page 18: Lecture 9

Which Object Does a Method Use? The simplest way is to declare class

variables:Stock kate, joe;

This creates two objects of the Stock class, one named kate and one named joe.

To use a member function with one of these objects, apply the membership operator.kate.show(); // the kate object calls the member function joe.show();

// the joe object calls the member function

18

Page 19: Lecture 9

Reviewing Our Story To Date The first step in specifying a class design is

to provide a class declaration. Includes data members and function

members. The declaration has a private section, and

members declared in that section can be accessed only through the member functions

The declaration also has a public section, and members declared there can be accessed directly by a program using class objects 19

Page 20: Lecture 9

Typically, data members go into the private section and member functions go into the public section, so a typical class declaration has this form:class className { private:

data member declarations

public: member function prototypes };

20

Page 21: Lecture 9

The contents of the public section constitute the abstract part of the design, the public interface.

Encapsulating data in the private section protects the integrity of the data and is called data hiding.

Using a class is the C++ way of making it easy to implement the OOP features abstraction, data hiding, and encapsulation

21

Page 22: Lecture 9

The second step in specifying a class design is to implement the class member functions.

*Note: You can use a complete function definition instead of a function prototype in the class declaration, but the usual practice, except with very brief functions, is to provide the function definitions separately. Use the scope-resolution operator to indicate

to which class a member function belongs.

22

Page 23: Lecture 9

For example:void Bozo :: retort ();

The resort() function belongs to the Bozo class and the full or qualified function name is Bozo :: retort ();

To create an object, which is a particular example of a class, you use the class name as if it were a type name:Bozo bozzetta;This works because a class is a user-defined type. 23

Page 24: Lecture 9

You invoke a class member function, or method, by using a class object. You do so by using the dot membership operator:cout << Bozetta.Retort();

This invokes the Retort() member function, and whenever the code for that function refers to a particular data member, the function uses the value that member has in the bozetta object.

24