1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University...

20
1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University [email protected] ECE230 Lectures Series

Transcript of 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University...

Page 1: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

1

C++ Classes: Access (II)

Ying Wu Electrical Engineering & Computer

ScienceNorthwestern [email protected]

ECE230 Lectures Series

Page 2: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

2

Thinking in C

Buy_Materials()

Hire_Workers()

Build_Floor()

Build_Bedrooms()

Build_Kitchen()

Build_Roof()

Assembly()

$$$

Page 3: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

3

Thinking in C++

$$$

HomeDepot

Material

Worker

Floor

Bedroom

Kitchen

Roof

House

Page 4: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

4

CVariableclass CVariable

{

double m_dValue;

char* m_sName;

public:

// constructors and destructors

CVariable();

CVariable(const char*name, const double& v = 0.0);

~CVariable();

CVariable(const CVariable& var); // copy constructor

const CVariable& operator=(const CVariable& var); // overload =

// getting and setting

double Value() { return m_dValue; };

char* Name() const { return m_sName; };

void SetValue(const double& v) { m_dValue = v; };

bool SetName(const char* name);

};

Page 5: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

5

A good point of C++: “package”

Data encapsulation– Class = Data + Functions

Data

Functions

Classaccess

Is it good to access all the members from outside?

Page 6: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

6

What to learn today?

Access to data members Access to member functions Header files

Page 7: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

7

Syntax for accessing

Rules of thumb– (I) we do not differentiate data

members and member functions. (since both are members!)

– (II) if the client is an object, use “.”– (III) if the client is a pointer of a

object, use “”

Page 8: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

8

void main()

{

CVariable a;

a.SetName(“var_1”);

a.SetValue(1.5);

CVariable *b;

b = &a;

b->SetValue(3.3);

(*b).SetName(“vvv”);

CVariable &c;

c = a;

c.SetValue(0.0);

cout << a.Name() << a.Value() << endl;

cout << b->Name() << b->Value() << endl;

}

Page 9: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

9

Question?

(1)Is it good?

(2)Why do I need to manipulate the data directly?

• No, I don’t want my class to be too transparent to other users!

• I don’t want to give users too much rights to manipulate the data in my package!

void main(){

CVariable a;

a.m_dValue = 1.0;

char name[] = “var_1”;a.m_sName = name;

}

Page 10: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

10

Another good point of C++

Information Hiding– Clients can only access some specific

members in a class

Data

Functions

access

Data

Functions

Class

Page 11: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

11

Controlling Access to Members

public – Presents clients with a view of the services

the class provides (interface)– Data and member functions are accessible

private– Default access mode– Data only accessible to member functions

and friends– private members only accessible through

the public class interface using public member functions

Page 12: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

12

Access Functions and Utility Functions

Utility functions– private functions that support the operation

of public functions– Not intended to be used directly by clients

Access functions– public functions that read/display data or

check conditions – Allow public functions to check private

data– “set” functions– “get” functions– Predicate functions

Page 13: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

13

// salesp.h

// SalesPerson class definition

// Member functions defined in salesp.cpp

#ifndef SALESP_H

#define SALESP_H

class SalesPerson {

public:

SalesPerson(); // constructor

void getSalesFromUser(); // get sales figures from keyboard

void setSales( int, double ); // User supplies one month's

// sales figures.

void printAnnualSales();

private:

double totalAnnualSales(); // utility function

double sales[ 12 ]; // 12 monthly sales figures

};

#endif

Page 14: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

14

// salesp.cpp// Member functions for class SalesPerson#include <iostream>#include <iomanip>

using namespace std;

#include "salesp.h"

// Constructor function initializes arraySalesPerson::SalesPerson(){ for ( int i = 0; i < 12; i++ ) sales[ i ] = 0.0;}

// Function to get 12 sales figures from the user // at the keyboardvoid SalesPerson::getSalesFromUser(){ double salesFigure;

for ( int i = 1; i <= 12; i++ ) { cout << "Enter sales amount for month " << i << ": "; cin >> salesFigure; setSales( i, salesFigure ); }}

Page 15: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

15

// Function to set one of the 12 monthly sales figures.// Note that the month value must be from 0 to 11.void SalesPerson::setSales( int month, double amount ){ if ( month >= 1 && month <= 12 && amount > 0 ) sales[ month - 1 ] = amount; // adjust for subscripts 0-11 else cout << "Invalid month or sales figure" << endl; }

// Print the total annual salesvoid SalesPerson::printAnnualSales(){ cout << setprecision( 2 ) << setiosflags( ios::fixed | ios::showpoint ) << "\nThe total annual sales are: $" << totalAnnualSales() << endl;}

// Private utility function to total annual salesdouble SalesPerson::totalAnnualSales(){ double total = 0.0;

for ( int i = 0; i < 12; i++ ) total += sales[ i ];

return total;}

Page 16: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

16

87 // Fig. 6.7: fig06_07.cpp

88 // Demonstrating a utility function

89 // Compile with salesp.cpp

90 #include "salesp.h"

91

92 int main()

93 {

94 SalesPerson s; // create SalesPerson object s

95

96 s.getSalesFromUser(); // note simple sequential code

97 s.printAnnualSales(); // no control structures in main

98 return 0;

99 }

 OUTPUTEnter sales amount for month 1: 5314.76Enter sales amount for month 2: 4292.38Enter sales amount for month 3: 4589.83Enter sales amount for month 4: 5534.03Enter sales amount for month 5: 4376.34Enter sales amount for month 6: 5698.45Enter sales amount for month 7: 4439.22Enter sales amount for month 8: 5893.57Enter sales amount for month 9: 4909.67Enter sales amount for month 10: 5123.45Enter sales amount for month 11: 4024.97Enter sales amount for month 12: 5923.92 The total annual sales are: $60120.59

Create object s, an instance of class SalesPerson

1. Load header file and compile with the file that

contains the function

definitions

2. Create an object

2.1 Use the object’s member functions to get and print sales

Program Output

Use access functions to gather and print data (getSalesFromUser and printAnnualSales). Utility functions actually calculate the total sales, but the user is not aware of these function calls.

Notice how simple main() is – there are no control structures, only function calls. This hides the implementation of the program.

Page 17: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

17

Separating Interface from Implementation

Separating interface from implementation– Makes it easier to modify programs– Header files

Contains class definitions and function prototypes

Using #ifndef#define…#endif

– Source-code filesContains member function definitions

Page 18: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

18

// variable.h Header file#ifndef _VARIABLE_H_#define _VARIABLE_H_

class CVariable{

double m_dValue;char* m_sName;

public:// constructors and destructorsCVariable();CVariable(const char*name, const double& v = 0.0);~CVariable();CVariable(const CVariable& var); // copy constructorconst CVariable& operator=(const CVariable& var); // overload =

// getting and settingdouble Value() { return m_dValue; }; char* Name() const { return m_sName; };void SetValue(const double& v) { m_dValue = v; };bool SetName(const char* name);

};

#endif

Page 19: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

19

// variable.cpp source file#include “variable.h”

CVariable::CVariable() : m_dValue(0.0), m_sName(NULL){

// empty}

CVariable::CVariable(const char* name, const double& v){

m_dValue = v;m_sName = new char[strlen(name)+1];strcpy(m_sName, name);

}

CVariable::CVariable(const CVariable& var){

m_dValue = var.m_dValue;m_sName = new char[strlen(var.m_sName)+1];strcpy(m_sName, var.m_sName);

}

CVariable::~CVariable(){

if(m_sName!=NULL){delete [] m_sName;

}}

Page 20: 1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu ECE230 Lectures Series.

20

const CVariable&CVariable::operator=(const CVariable& var){

if(&var != this){ // check for self-assignmentm_dValue = var.m_dValue;SetName(var.m_sName);

}return *this;

}

boolCVariable::SetName(const char* name){

bool code = true;if(m_sName!=NULL)

delete [] m_sName;m_sName = new char [strlen(name) + 1];if(m_sName){

strcpy(m_sName, name);}else

code = false;return code;

}