1 cse 2341 object oriented programming with c++ note set #5
TRANSCRIPT
1
CSE 2341Object Oriented Programming
with C++
Note Set #5
2
Quick Look
• Introduction to the C++ class– constructors/destructors– interface/implementation– attributes/member functions– using the class in a main driver
3
The Class in C++
• Objects are implemented with a class in C++.
Basic syntactical features of a class:
class className
{
//declaration statements here
};
4
Example Class
class Rectangle{private:
int length, width, area;public:
void setData(int, int);void calcArea();int getLength();int getWidth();void setWidth(int);void setWidth(int);int getArea();
};
access specifiers
5
Access Specifiers
• 3 different access specifiers – public, private, protected – prevent members of the class from being used
in ways in which they were not intended• Private:
– only accessible by member functions of the class
• Public:– accessible by any function
• Protected:– accessible by a derived class (to come later)
• NOTE: Default access is private but should be explicitly indicated.
6
Defining a member function of a class
• Can be defined inside the class interface or externally in a separate file
void Rectangle::setData(int w, int l){ width = w; length = l;
area = width * length;}
7
Defining an Instance of a Class
• class objects may only be defined after the class is declared
• Instantiation– defining a class object of a particular
type
Rectangle box; box is an instanceof Rectangle
8
Accessing a public member
• given an instance of an object of type T, public members of the function are accessed using the . (dot) operator
Generally: T.publicMember();
Example: box.setData(2,3);
9
Pointers to Objects
• pointers to object types are acceptable
• use the -> operator to access public members from a pointer
Rectangle box;Rectangle* boxPtr;boxPtr = &box;boxPtr -> setData(4, 5);
10
Interface vs. Implementation
• Interface – the declaration of the class• Implementation – the definition of the
member functions• interface and implementation are typically
separated into different files (also separate from main driver file)
• For Rectangle Class– Interface – Rectangle.h– Implementation – Rectangle.cpp
11
Rectangle.h//Declaration of class Rectangle#ifndef RECTANGLE_H#define RECTANGLE_Hclass Rectangle{public:
void setWidth(float);void setLength(float);float getWidth();float getLength();float getArea();
private:float width;float length
};#endif
Rect
an
gle
.h
12
#ifndef
#ifndef RECTANGLE_H#define RECTANGLE_H // Other code here#endif
• This code ensures that the class is only defined once.• If multiple source files include Rectangle, no need to compile it multiple times.
13
Rectangle.cpp
#include “Rectangle.h”//Definitions of member functions
//Copies the parameter to length data membervoid Rectangle::setLenght(float l){
length = l;}
//Copies the parameter to width data membervoid Rectangle::setWidth(float w){
width = w;}
Rect
an
gle
.cp
p
14
Rectangle.cpp (continued)
//return value stored in width data memberfloat Rectangle::getWidth(){
return width;}
//return value stored in length data memberfloat Rectangle::getLength(){
return length;}
//return calculated area of the rectanglefloat Rectangle::getArea(){
return length * width;}
Rect
an
gle
.cp
p
15
Using the Class in Driver
//Demonstrates use of Rectangle class#include “Rectangle.h”#include <iostream>using namespace std;int main(){
Rectangle box;float temp;cout << “This program will calculate “
<< “the area of a rectangle.” << endl;cout << “What is the width? “;cin >> temp;box.setWidth(temp);
Dri
ver.
cpp
Use “” when includinga user-defined class
16
Using the Class in Driver
cout << “What is the length? “; cin >> temp box.setLength(temp);
//Display all of box’s data cout<<“Length: “<<box.getLength()<<endl; cout<<“Width: “<<box.getWidth()<<endl; cout<<“Area: “<<box.getArea()<< endl;
return 0;}
Dri
ver.
cpp
17
Private Data Members – Why??
• In OOP, an object should protect its private data members so they do not get inadvertently corrupted
• A public interface to that data is provided so it does not get corrupted
18
A More Robust Rectangle
• Problems with the rectangle class?
• Should width or length ever be negative?
Have the functions which modifya data member return a bool
indicating success or not
19
Rectangle.h//Declaration of class Rectangle#ifndef RECTANGLE_H#define RECTANGLE_Hclass Rectangle{public:
bool setWidth(float);bool setLength(float);float getWidth();float getLength();float getArea();
private:float width;float length
};#endif
Rect
an
gle
2.h
20
More Robust Rectangle Implementation
#include “Rectangle.h”//Definitions of member functions
//Copies the parameter to length data memberbool Rectangle::setLength(float l){
if (l >= 0.0){ length = l;
return true;}else{
length = 0.0;return false;
}}
Rect
an
gle
w2
.cp
p
21
More Robust Rectangle Implementation (continued)
//Copies the parameter to width data membervoid Rectangle::setWidth(float w){
if (w >= 0.0){ width = w;
return true; }else{ width = 0.0;
return false; }}
//return value stored in width data memberfloat Rectangle::getWidth(){
return width;}
Rect
an
gle
w2
.cp
p
22
Rectangle.cpp (continued)
//return value stored in length data memberfloat Rectangle::getLength(){
return length;}
//return calculated area of the rectanglefloat Rectangle::getArea(){
return length * width;}
Rect
an
gle
2.c
pp
23
Using the Class in Driver
//Demonstrates use of Rectangle class#include “Rectangle.h”#include <iostream>using namespace std;int main(){
Rectangle box;float temp;cout << “This program will calculate “
<< “the area of a rectangle.” << endl;cout << “What is the width? “;cin >> temp;
Dri
ver2
.cp
p
24
Using the Class in Driver
if(!box.setWidth(temp)){
cout << “Invalid Width – width set “ << “to 0.0!” << endl;
}cout << “What is the length? “;cin >> temp;if(!box.setLength(temp)){
cout << “Invalid Length – length set ” << “ to 0.0!” << endl;
}
Dri
ver2
.cp
p
25
Using the Class in Driver
//Display all of box’s data cout<<“Length: “<<box.getLength()<<endl; cout<<“Width: “<<box.getWidth()<<endl; cout<<“Area: “<<box.getArea()<< endl;
return 0;}
Dri
ver2
.cp
p
26
I/O in Classes
• Notice – No cin/cout in Rectangle• Allows flexibility to use the object
– not locked into any particular error messages, prompts, etc.
• Classes should only have I/O if specifically designed for such.– Best left to the person designing the
application
27
Review of Different Files
• Rectangle.h Class Interface• Rectangle.cpp Member Function
Definitions• Driver.cpp Main driver
28
More on Classes
• Class can have– private member functions– public data members
• If member function is private, can only be called by other member functions of the class or friends
• Member functions may be defined inside class declaration – called inlining
29
Rectangle.h//Declaration of class Rectangle#ifndef RECTANGLE_H#define RECTANGLE_Hclass Rectangle{public:
bool setWidth(float);bool setLength(float);float getWidth() {return width;}float getLength() {return length;}float getArea()
{return length * width;}private:
float width;float length
};#endif
Rect
an
gle
3.h
Inlined member functiondefinitions will not also appear in Rectangle.cpp
30
Special Member Functions
The Constructor& The Destructor
31
Constructor
• A constructor– is automatically called upon object
instantiation– has the same name as the name of the
class– Must be declared as a public member
function– NO RETURN TYPE!!!
32
Constructor Demo Class
#include <iostream>using namespace std;class Demo{public:
Demo();};
//Constructor defined in the .h file//Usually defined in .cpp file. Demo::Demo(){
cout << “Welcome to the Constructor!” << endl;}
Dem
o.
h
33
Constructor Demo Class#include “Demo.h”#include <iostream>using namespace std;int main(){
cout << “Before Object Creation” << endl;Demo demoObj;cout << “After Object Creation” << endl;return 0;
}
dem
oD
river.
cpp
Before Object CreationWelcome to the Constructor!After Object Creation
Output:
34
More on Constructors
• Default Constructor – constructor which accepts no arguments
• Constructors may– accept argument– have default arguments– be declared inline– be overloaded
35
Inventory Item ClassIn
ven
tory
Item
.h class InventoryItem{private:
char* descrip;int units;
public:InventoryItem(){descrip = new char[51];}void setDescription(char* x) { strcpy(descrip, x); }void setUnits(int u) {units = u;}char* getDescription() {return descrip;}int getUnits() {return units;}
};
36
Inventory Item ClassIn
ven
tory
Item
Dri
ver.
cp
p
int main(){ InventoryItem stock; stock.setDescription(“Wrench”); stock.setUnits(20);
cout << “Item Description: “ << stock.getDescription() << endl; cout << “Units on Hand: “ << stock.getUnits() << endl;
return 0;}
Output:
Item Description: WrenchUnits on Hand: 20
37
Destructor
• A Destructor– is a member function– is automatically called when an object is
destroyed– has the same name as the class
preceded with a tilde (~)– performs shutdown procedures– never accept parameters– cannot be overloaded
38
Destructor Demo Class#include <iostream>using namespace std;class Demo{public:
Demo();~Demo();
};
Demo::Demo(){ cout << “Welcome to the Constructor!” << endl; }
Demo::~Demo(){ cout << “Goodbye from the Destructor!” << endl;}
Dem
o2
.h
39
Destructor Demo Class#include “Demo2.h”#include <iostream>using namespace std;int main(){ cout << “Before Object Creation.” << endl; Demo demoObj; cout << “After Object Creation” << endl; return 0;}
dem
oD
river.
cpp
Before Object CreationWelcome to the Constructor!After Object CreationGoodbye From the Destructor!
Output:
40
Inventory Item ClassIn
ven
tory
Item
2.
h
class InventoryItem{private:
char* descrip;int units;
public:InventoryItem(){descrip = new char[51];}~InventoryItem(){delete descrip;}void setDescription(char* x) { strcpy(descrip, x); }void setUnits(int u) {units = u;}char* getDescription() {return descrip;}int getUnits() {return units;}
};
41
Inventory Item ClassIn
ven
tory
Item
Dri
ver.
cp
p
int main(){ InventoryItem stock; stock.setDescription(“Wrench”); stock.setUnits(20);
cout << “Item Description: “ << stock.getDescription() << endl; cout << “Units on Hand: “ << stock.getUnits() << endl;
return 0;}
Item Description: WrenchUnits on Hand: 20
Output:
42
Argument Accepting Constructor
#ifndef SALE_H#deifne SALE_Hclass Sale {private: float taxRate; float total;public: Sale(float rate) { taxRate = rate; } void calcSale(float cost) { total = cost + cost * taxRate; } float getTotal() {return total;}}; #endif
Sale
.h
43
Argument Accepting Constructor
#include <iostream>using namespace std;#include “Sale.h”int main() { Sale cashier(0.06); //6% tax rate float amt; cout.setprecision(2); cout.setf(ios::fixed|ios::showpoint); cout << “Enter Sale amount: “; cin >> amt; cashier.calcSale(amt); cout << “Total is: $” << cashier.getTotal() << endl; return 0;}
Sale
Dri
ver.
cpp
44
Argument Accepting Constructor
#ifndef SALE_H#deifne SALE_Hclass Sale {private: float taxRate; float total;public: Sale( float rate=0.05) { taxRate = rate; } void calcSale(float cost) { total = cost + cost * taxRate; } float getTotal() {return total;}}; #endif
Sale
2.h
Default Argument
45
Argument Accepting Constructor
#include <iostream>using namespace std;#include “Sale2.h”int main() { Sale cashier(0.06); //6% tax rate Sale cashier2; //5% tax rate float amt; cout.setprecision(2); cout.setf(ios::fixed|ios::showpoint); cout << “Enter Sale amount: “; cin >> amt; cashier.calcSale(amt); cashier2.calcSale(amt);
Sale
Dri
ver2
.cp
p
46
Argument Accepting Constructor
cout << “Total at 5% is: $” << cashier.getTotal() << endl; cout << “Total at 6% is: $” << cashier2.getTotal() << endl; return 0;}
Sale
Dri
ver2
.cp
p
Enter Sale amount: 125.00Total at 5% is: 131.25Total at 6% is: 132.50
output:
47
Fini
?