Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object programming essentials

Similar presentations


Presentation on theme: "Object programming essentials"— Presentation transcript:

1 Object programming essentials
Chapter 5 (Part 1) Object programming essentials

2 Chapter 5 Objectives After completing this module, the student will be able to: Understand the concept of C++ class and object syntax Create objects Access object members Create setter/getter access methods Limit the range of accepted values in access methods Understand and implement different strategies for obtaining derived data Define a C++ class from scratch Model real-world entities with classes and objects Limit acceptable input range Manage multiple objects Provide meaningful and helpful representation of objects Understand the interactions between objects of the same type

3 Chapter 5 Objectives Create objects based on objects of other objects of custom classes  Understand the concept of inheritance syntax and operation Share functionality between objects using inheritance Implement data structures in C++ Understand the concept of dynamic allocation of C++ objects Prevent memory leaks and deallocate acquired resources Provide derived data about the implemented data structure Keep the data structure consistent at all times Traverse data structures Access data stored in data structures Create copies of data structures Implement and use copy constructors

4 5.1 Basic concepts of object programming

5 5.1.1 Classes and objects in real life
All of our programs and all the techniques we’ve used up till now fall into the so-called procedural style of programming.

6 5.1.1 Classes and objects in real life
Procedural programming works very well for simple projects and not large ones. Large and complex projects carried out by large teams consisting of many developers use Object approach . C++ language was created as a universal tool for object programming.

7 5.1.2 Classes and objects in real life
In the procedural approach, we can distinguish two different and separate worlds: data: populated by variables of different types code: inhabited by code grouped into functions. The object approach suggests a completely different way of thinking. The data and the code are enclosed together in the same world, divided into classes

8 5.1.2 Classes and objects in real life
Every class is like a recipe that can be used when you want to create a useful object You may produce as many objects as you need to solve your problem. Every object has a set of properties and is able to perform a set of activities (operations, methods).

9 5.1.2 Classes and objects in real life
The recipes may be modified if they’re inadequate for specific purposes and, in effect, new classes may be created. The new classes inherit properties and methods from the originals and usually add some new ones, creating new and more specific tools. Objects are materializations of ideas expressed in classes much like a piece of cheesecake on your plate is an incarnation of an idea expressed in the recipe printed in an old cookbook.

10 Example: Compute rectangle area.
class rectangle { private: int length; int width; public: void set_len(int a) { length=a; } void set_wid(int a) { width=a; } int get_len() { return length; } int get_wid() { return width; } int area() { return width*length;} }; int main() { int L, W; rectangle aobject; cout<<"Enter the length and width of rectangle(L,W)"; cin>>L>>W; aobject.set_len(L); // illegal aobject.length=L; //because, length is private aobject.set_wid(W); // illegal aobject.width=W; //because width is private cout<<"Length:"<<aobject.get_len()<<endl; cout<<"Width:"<<aobject.get_wid()<<endl; cout<<"Area: "<<aobject.area()<<endl; return 0; }

11 5.1.3 Class – what is it? Example of Classes (vehicles). All vehicles existing (and not yet existing) in the world are related to each other by a single, important feature: the ability to move. We suggest the following definition for any member of the class vehicles: vehicles are artificially created entities used for transportation, moved by forces of nature and directed (driven) by humans.

12 5.1.3 Class – what is it? The “vehicles” class is very broad. Too broad. We need to define some more specialized classes. The specialized classes are (will be) called “sub-classes”. The “vehicles” class will be a “super-class” for them all. The most general and the widest class is always at the top (a super) while its descendants are below (subs).

13 5.1.3 Class – what is it? Sub classes Sub classes Super class

14 5.1.5 Object – what is it? Object is an instance of class, which holds the data variables declared in class and the member operations (functions) work on these class objects. You can create as many objects as you want from the same class.

15 5.1.5 Object – what is it? For example:
any personal car is an object that belongs to the “wheeled vehicles” class. It also means that the same car belongs to all the superclasses of its home class; therefore, it’s a member of the “vehicles” class, too. Each subclass is more specialized (or more specific) than its superclass. Each superclass is more general (more abstract) than all its subclasses.

16 5.1.7 What does any object have?
The object programming convention assumes that every existing object may be equipped with three groups of attributes: A name that uniquely identifies it A set of individual properties ( attributes) A set of abilities to perform specific activities that can change the object itself (operations)

17 5.1.7 What does any object have?
There’s a hint that can help you identify any of these three spheres. Whenever you describe an object and you use: a noun, you probably define the object’s name adjective, you probably define the object’s property a verb, you probably define the object’s activity

18 5.1.7 What does any object have?
Example 1: “Max is a large cat who sleeps all day” Object name = Max Home class = Cat Property = Size (large) Activity = Sleep (all day) Example 2: “A pink Cadillac went quickly” Object name = Cadillac Home class = Wheeled vehicles Property = Colour (pink) Activity = Drive (quickly)

19 5.1.8 Why all this? class OurClass{ };
The class you define has nothing to do with object creation The class itself isn’t able to create an object – you have to create it yourself. It’s now time to show you how to define the simplest class and how to create an object. class OurClass{ }; The definition begins with the keyword class. The keyword is followed by an identifier that names the class Next, you add a pair of curly brackets. The content inside these define all the class properties and activities. Our curly brackets are empty, so the class is empty too.

20 5.1.9 The very first object OurClass ourObject;
The newly defined class becomes an equivalent of a data type, and we can use it as a type name. Imagine that we want to create one object of the OurClass class. We declare a variable that can store objects of that class and create an object at the same time. OurClass ourObject;

21 5.1 Practice Lab 5.1.9 (1) Classes and Objects in C++ [A]
Lab (2) Restricting access to object data [A] Lab (3) Obtaining derived data from an object [B] Lab (4) Classes and objects: ShopItemOrder [B]

22 5.3 Anatomy of the class

23 5.3.1 Class components A class is an aggregate consisting of variables (also called fields or properties) and functions (sometimes called operations/methods). Both variables and functions are class components /members.

24 Any member (variable or function) can be public, private or protected
5.3.2 Access specifier Three categories of class members private (default) Member cannot be accessed outside the class Public Member is accessible outside the class Protected Used with inheritance (next chapter) Any member (variable or function) can be public, private or protected

25 5.3.2 Access specifiers The following class has three components:
one variable of type int called value  two functions called setVal and getVal respectively. class is named Class.  class Class { int value; void setVal(int value); int getVal(void); }; Since all the components are declared without the use of an access specifier, all three components are private

26 5.3.2  Access specifiers The setVal and getVal components are public – they’re accessible to all users of the class. The value component is private – it’s accessible only within the class. class Class { public: void setVal(int value); int getVal(void); private: int value; };

27 5.3.3 Creating an object the_object.setVal(0);
Any object of the class is equipped with all the components defined in the class. Class the_object(); The public components are available for use. You can do this:  the_object.setVal(0); The private components are hidden and unavailable. You mustn’t do this:  the_object.value = 0; //Syntax Error

28 Example: We can define the function member inside the class
We can define the function member outside the class using :: operator x y void fun(); void print(); myObj

29 Unified Modeling Language (UML) Class Diagrams
To describe the class graphically. This is usually what will be given in the lab. +: member is public -: member is private #: member is protected

30 C++ Programming: From Problem Analysis to Program Design, Fourth Edition
Example These functions cannot modify the member variables of a variable of type clockType const: formal parameter can’t modify the value of the actual parameter private members, can’t be accessed from outside the class

31 C++ Programming: From Problem Analysis to Program Design, Fourth Edition
Class Functions Getter function: member function that only accesses the value(s) of member variable(s) Setter function: member function that modifies the value(s) of member variable(s) Constant function: Member function that cannot modify member variables Use const in function heading

32 Example:

33 5.3.4 Overriding component names
A function that is a class component has full access to other class components, including private ones. If any function introduces an entity of the name identical to any of the class components, the name of the class component is overridden. It can be accessed only by the qualification with the home class name.

34 Example Rubbish value 10

35 5.3.4 Overriding component names
The setX function uses a parameter called x. The parameter overrides the class component called x. This means that the assignment   x = x;  applies to the value parameter and has nothing to do with the component of the same name. One of the proper forms of the assignment looks like this: A::x = x; The qualification unveils the overridden name of the component.  

36 5.3.6 Qualifying component names (1)
If any class function body is given outside the class body, its name must be qualified with the home class name and the “::” operator. A function defined in this way has the same full access to all class components as any function defined inside the class. All rules for overriding names are valid too.

37 5.3.6 Qualifying component names (1)
class Class { public: void setVal(int value) { this -> value = value; } int getVal(void); private: int value; }; int Class::getVal(void) { return value;

38 5.3.7 Qualifying component names (2)
Class function names may be overloaded just like ordinary function names. The default parameter values may be used too. All the other restrictions on the construction of the overloaded class functions apply, too.

39 Example class Class { public: void setVal(int value) { this -> value = value; } void setVal(void) { value = -2; } int getVal(void) { return value; } private: int value; }; int main() { Class obj; obj.setVal(20); // call the first version of the function obj.setVal(); // call the second version of the function }

40 5.3.8 Constructors A function with a name identical to its home class name is called a constructor. The constructor is intended to construct the object during its creation i.e. to initialize field values, allocate memory, create other objects, etc. The constructor may access all object components like any other class member function but should not be invoked directly. A constructor has no type

41 Example class Class { public: Class(void) { this -> value = -1; } void setVal(int value) { this -> value = value; } int getVal(void) { return value; } private: int value; };

42 5.3.8 Constructors Class object;
Declaring the object of the class, e.g. by doing it in the following way: Class object; implicitly invokes the constructor. Note you’re not allowed to do either this: object.Class() or this Class::Class();

43

44 5.3.9 Overloading constructor names (1)
Constructors may be overloaded too, depending on specific needs and requirements. The following class has two different constructors that differ in their number of parameters. The actual constructor is chosen during the object’s creation. class Class { public: Class(void) { this -> value = -1; } Class(int val) { this -> value = val; } void setVal(int value) { this -> value = value; } int getVal(void) { return value; } private: int value; }; 

45 5.3.9 Overloading constructor names (1)
Look at the following snippet, please: Class object1, object2(100); cout << object1.getVal() << endl; cout << object2.getVal() << endl; The object1 object will be created using a parameter-less constructor, while the object2 will be created with a one-parameter constructor. The snippet will output the following values: -1 100

46 5.3.9 Overloading constructor names (1)
Note that you mustn’t demand the use of a non-existent constructor – this means that the following snippet is wrong:   Class objectx(2,100);

47

48 5.3.10 Overloading constructor names (2)
If a class has a constructor (or more precisely, at least one constructor), one of them must be chosen during object creation i.e. you’re not allowed to write a declaration which doesn’t specify a target constructor. class Class { public: Class(int val) { this -> value = val; } void setVal(int value) { this -> value = value; } int getVal(void) { return value; } private: int value; }; Int main() { Class obj1(5); //legal statement Class obj2; // Syntax Error (no default constructor) }

49 Constructors and Default Parameters
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Constructors and Default Parameters Using clockType constructor, you can declare clockType objects with zero, one, two, or three arguments as follows: clockType clock1; //Line 2 clockType clock2(5); //Line 3 clockType clock3(12, 30); //Line 4 clockType clock4(7, 34, 18); //Line 5 Note: if you have a constructor with all default parameters you cannot declare a constructor without parameters, they both called default constructor. clockType clockType(int = 0, int = 0, int = 0); clockType clockType (); //illegal in the same class

50 5.3.13 Destructors Destructors are functions without any type
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Destructors Destructors are functions without any type The name of a destructor is the character '~' followed by class name For example: ~clockType(); A class can have only one destructor The destructor has no parameters The destructor is automatically executed when the class object goes out of scope

51 Example

52 Example

53 Arrays of Class Objects (Variables) and Constructors
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Arrays of Class Objects (Variables) and Constructors If a class has constructors and you declare an array of that class’s objects, the class should have the default constructor

54 Arrays of Class Objects (Variables) and Constructors (continued)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Arrays of Class Objects (Variables) and Constructors (continued)

55 Example class Employee{ string name; int id; double salary; public:
Employee(string="",int=0,double=0); void setAll(string,int,double); double getSalary()const; void setSalary(double s); void print()const; ~Employee(); };

56 Example Employee::Employee(string n,int i,double s) { setAll(n,i,s); }
void Employee::setAll(string n,int i,double s) name = n; id = i; setSalary(s); double Employee::getSalary()const { return salary; }

57 Example void Employee::setSalary(double s) {
if( s >= 100 && s <= 1000) salary = s; else if( s < 100) salary = 100; else salary = 1000; } void Employee::print()const cout<<"Employee name: "<<name<<" Id = "<<id<<" Salary = "<<salary<<endl; Employee::~Employee() cout<<"goodbye "<<name<<endl;}

58 Example /*Write a NON-MEMBER function that receives an object of type employee and the increasing percentage. This function should update the salary for the employee by the parameter percentage.*/ void updateSalary(Employee &e,double p) { double s = e.getSalary(); s = s + s*p; e.setSalary(s); //e.setSalary(e.getSalary()+e.getSalary()*p); }

59 Example /*write a non-member function that receives an array of employee and print all information its elements. */ void print(Employee e[],int size) { for(int i = 0; i < size; i++) e[i].print(); }

60 void main() { //create an object of type employee with the following info: Ali,123,700 Employee admin("Ali",123,700); //create an array of type employee of size 3 Employee emp[3]; //prompt the user to enter the information of all employees in the array string n; int id; double s; for(int i = 0; i < 3; i++) cin>>n>>id>>s; emp[i].setAll(n,id,s); }

61 //print all employee in this program
admin.print(); for(int i = 0; i < 3; i++) emp[i].print(); //Increase the salary for the employee admin by 30% updateSalary(admin,.3); //Increase the salary for the third employees in the array by 5% updateSalary(emp[2],.05); //print the information of the emp array print(emp,3); }

62 5.3 Practice Lab 5.3.10 (1) Flight booking system: part 1 [B]
Lab (3) Flight booking system: part 3 [C] Lab (4) Gym membership management system [C] Lab (5) Modelling fractions: part 1 [C] Lab (6) Modelling fractions: part 2 [B] Lab (7) Modelling fractions: part 3 [B] Lab (8) Points in 2D: part 1 [A] Lab (9) Points in 2D: part 2 [B] Lab (10) Points in 2D: part 3 [B] Lab (11) Inheritance basics: part 1 [B] Lab (12) Inheritance basics: part 2 [B] Lab (1) Singly linked list: part 1 [B] Lab (2) Singly linked list: part 2 [B] Lab (3) Singly linked list: part 3 [A] Lab (4) Singly linked list: part 4 [B] Lab (5) Singly linked list: part 5 [B] Lab (6) Singly linked list: part 6 [B] Lab (7) Singly linked list: part 7 [B] Lab (8) Doubly linked list [C]

63 5.2 A stack: a view from two different perspectives

64 5.2.1 Stack aka LIFO (1) A stack is a structure developed to store data in a very specific way. Example: A stack of coins would be best here. You can’t put or get a coin anywhere else but on the top of the stack. To get the coin on the bottom, you have to remove all the coins that are sitting on top of it. The alternative name for a stack is LIFO: Last In – First Out. The coin that goes onto the stack last comes off first.

65 5.2.1 Stack aka LIFO (1) A stack is an object to two elementary operations conventionally named “push” (when a new element is placed on the top) “pop” (when an existing element is taken away from the top). Let’s try to implement a stack in “C++”. It’ll be a very simple stack and store int values only. We’ll show you how to do it in two independent approaches: procedural and objective. Let’s start with procedural. 

66 int stack[100]; 5.2.2 Stack aka LIFO (2) procedural implementation
First, we have to decide how to store the int values that’ll arrive onto our stack. We suggest using the simplest method and use a vector (array) with no more than 100 values for this job. We also assume that the element at index 0 is at the bottom of the stack. The stack itself is already declared as: int stack[100];

67 5.2.3 Stack pointer But the array isn’t enough to implement a stack. We need a few additional details. number of elements currently stored on the stack. This variable is generally called a “stack pointer”, or SP for short. Initially, the stack is empty, so the stack pointer should be assigned the value of 0. int sp=0;

68 5.2.4 Push void push(int value) { stack[SP++] = value; }
We’re now ready to define a function that places a value onto the stack. Here is what we’ve supposed: the name for the function is “push” the function gets one parameter of type int (this is the value to be placed onto the stack) the function returns nothing (self-explanatory, right?) the function places the parameter value into the first free element in the arrayand increments the SP void push(int value) { stack[SP++] = value; } The function doesn’t check if there’s room for the new value.  

69 5.2.5 Pop int pop(void) { return stack[--SP]; }
Now it’s time for the function to take a value off the stack. This is how we imagine it: the name of the function is “pop” (we don’t want to discover America again) the function doesn’t have any parameters the function returns the value taken from the stack the function reads the value from the stack’s top and decrements SP int pop(void) { return stack[--SP]; The function doesn’t check if there’s any element on the stack.

70 5.2.6 The stack in action #include <iostream>
using namespace std; int stack[100]; int SP = 0; void push(int value) { stack[SP++] = value; } int pop(void) { return stack[--SP]; } int main(void) { push(3); push(2); push(1); cout << pop() << endl; return 0; } What is the output of this program?!

71 5.2.7 Pros and cons Disadvantages
two essential variables (stack and SP) are completely vulnerable; anyone can modify them in an uncontrollable way it may happen that one day you need more than one stack; be prepared to work hard you’ll have to create another vector for the stack’s storage, another stack pointer for a new vector, probably more push and pop functions too; it may also happen that you need not only push and pop functions, but also some other things; you can implement them but try to imagine what’ll happen when you have dozens of separately implemented stacks we’ve used the int stack so far, but you may want to use the stacks defined for other types: floats, strings or even arrays and structures; what’ll happen then?

72 5.2.7 Pros and cons The objective approach provides solutions for each of these problems. Encapsulation (chapter 6): the ability to hide (protect) selected values against unauthorized access when you have a class implementing all the needed stack behaviors, you can produce as many stacks as you want; the ability to enrich the stack with new functions comes from the inheritance (Chapter 6); you can create a new class (or more precisely a subclass) which inherits all the existing traits from the superclass and adds some new ones you can create a template (chapter 8) which is a generalized, parameterized class, ready to materialize itself in many different incarnations; its code can adapt to varying requirements and, for example, create stacks ready to work with other types of data 

73 5.2.8 Stack from scratch (1) Let’s write a brand new stack implementation from scratch using objective approach. Stack is a list that contain: A vector (array) as the stack’s storage An int variable as the stack pointer. We wanted to encapsulate both variables and make them inaccessible from the outside world. class Stack { int stackstore[100]; int SP; };

74 5.2.12 Stack from scratch (5) The class is complete now. class Stack {
private: int stackstore[100]; int SP; public: Stack(void) { SP = 0; } void push(int value); int pop(void) { return stackstore[--SP]; } };  void Stack::push(int value) { stackstore[SP++] = value; }

75 5.2.13 Stack from scratch (6) Testing our class:
We want to create three objects of the class “Stack”. Next, we want use them in a juggling sort of way. Try to predict the value outputted to the screen. #include <iostream> using namespace std; int main(void) { Stack little_stack, another_stack, funny_stack; little_stack.push(1); another_stack.push(little_stack.pop() + 1); funny_stack.push(another_stack.pop() + 2); cout << funny_stack.pop() << endl; return 0; }


Download ppt "Object programming essentials"

Similar presentations


Ads by Google