Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSE 2341 Object Oriented Programming with C++ Note Set #5.

Similar presentations


Presentation on theme: "1 CSE 2341 Object Oriented Programming with C++ Note Set #5."— Presentation transcript:

1 1 CSE 2341 Object Oriented Programming with C++ Note Set #5

2 2 Quick Look Introduction to the C++ class –constructors/destructors –interface/implementation –attributes/member functions –using the class in a main driver

3 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 4 Example Class class Rectangle { private: int length, width, area; public: void setData(int, int); void calcArea(); int getLength(); int getWidth(); void setWidth(int); int getArea(); }; access specifiers

5 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 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 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 instance of Rectangle

8 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 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 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 11 Rectangle.h //Declaration of class Rectangle #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { public: void setWidth(float); void setLength(float); float getWidth(); float getLength(); float getArea(); private: float width; float length }; #endif Rectangle.h

12 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 13 Rectangle.cpp #include “Rectangle.h” //Definitions of member functions //Copies the parameter to length data member void Rectangle::setLenght(float l) { length = l; } //Copies the parameter to width data member void Rectangle::setWidth(float w) { width = w; } Rectangle.cpp

14 14 Rectangle.cpp (continued) //return value stored in width data member float Rectangle::getWidth() { return width; } //return value stored in length data member float Rectangle::getLength() { return length; } //return calculated area of the rectangle float Rectangle::getArea() { return length * width; } Rectangle.cpp

15 15 Using the Class in Driver //Demonstrates use of Rectangle class #include “Rectangle.h” #include 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); Driver.cpp Use “” when including a user-defined class

16 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; } Driver.cpp

17 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 18 A More Robust Rectangle Problems with the rectangle class? Should width or length ever be negative? Have the functions which modify a data member return a bool indicating success or not

19 19 Rectangle.h //Declaration of class Rectangle #ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { public: bool setWidth(float); bool setLength(float); float getWidth(); float getLength(); float getArea(); private: float width; float length }; #endif Rectangle2.h

20 20 More Robust Rectangle Implementation #include “Rectangle.h” //Definitions of member functions //Copies the parameter to length data member bool Rectangle::setLength(float l) { if (l >= 0.0) { length = l; return true; } else { length = 0.0; return false; } Rectanglew2.cpp

21 21 More Robust Rectangle Implementation (continued) //Copies the parameter to width data member void Rectangle::setWidth(float w) { if (w >= 0.0) {width = w; return true; } else {width = 0.0; return false; } } //return value stored in width data member float Rectangle::getWidth() { return width; } Rectanglew2.cpp

22 22 Rectangle.cpp (continued) //return value stored in length data member float Rectangle::getLength() { return length; } //return calculated area of the rectangle float Rectangle::getArea() { return length * width; } Rectangle2.cpp

23 23 Using the Class in Driver //Demonstrates use of Rectangle class #include “Rectangle.h” #include 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; Driver2.cpp

24 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; } Driver2.cpp

25 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; } Driver2.cpp

26 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 27 Review of Different Files Rectangle.hClass Interface Rectangle.cppMember Function Definitions Driver.cppMain driver

28 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 29 Rectangle.h //Declaration of class Rectangle #ifndef RECTANGLE_H #define RECTANGLE_H class 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 Rectangle3.h Inlined member function definitions will not also appear in Rectangle.cpp

30 30 Special Member Functions The Constructor & The Destructor

31 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 32 Constructor Demo Class #include 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; } Demo.h

33 33 Constructor Demo Class #include “Demo.h” #include using namespace std; int main() { cout << “Before Object Creation” << endl; Demo demoObj; cout << “After Object Creation” << endl; return 0; } demoDriver.cpp Before Object Creation Welcome to the Constructor! After Object Creation Output:

34 34 More on Constructors Default Constructor –constructor which accepts no arguments Constructors may –accept argument –have default arguments –be declared inline –be overloaded

35 35 Inventory Item Class InventoryItem.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 36 Inventory Item Class InventoryItemDriver.cpp 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: Wrench Units on Hand: 20

37 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 38 Destructor Demo Class #include using namespace std; class Demo { public: Demo(); ~Demo(); }; Demo::Demo() { cout << “Welcome to the Constructor!” << endl; } Demo::~Demo() { cout << “Goodbye from the Destructor!” << endl; } Demo2.h

39 39 Destructor Demo Class #include “Demo2.h” #include using namespace std; int main() { cout << “Before Object Creation.” << endl; Demo demoObj; cout << “After Object Creation” << endl; return 0; } demoDriver.cpp Before Object Creation Welcome to the Constructor! After Object Creation Goodbye From the Destructor! Output:

40 40 Inventory Item Class InventoryItem2.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 41 Inventory Item Class InventoryItemDriver.cpp 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: Wrench Units on Hand: 20 Output:

42 42 Argument Accepting Constructor #ifndef SALE_H #deifne SALE_H class 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 43 Argument Accepting Constructor #include 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; } SaleDriver.cpp

44 44 Argument Accepting Constructor #ifndef SALE_H #deifne SALE_H class 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 Sale2.h Default Argument

45 45 Argument Accepting Constructor #include 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); SaleDriver2.cpp

46 46 Argument Accepting Constructor cout << “Total at 5% is: $” << cashier.getTotal() << endl; cout << “Total at 6% is: $” << cashier2.getTotal() << endl; return 0; } SaleDriver2.cpp Enter Sale amount: 125.00 Total at 5% is: 131.25 Total at 6% is: 132.50 output:

47 47 Fini ?


Download ppt "1 CSE 2341 Object Oriented Programming with C++ Note Set #5."

Similar presentations


Ads by Google