2 lesson 2 object oriented programming in c++

Post on 14-May-2015

232 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Object Oriented Object Oriented Programming Programming

in in

c++c++

DefinitionDefinition:: Object oriented Object oriented programming is an approach that programming is an approach that provides a way of modularizing provides a way of modularizing programs by creating partitioned programs by creating partitioned memory area for both data and memory area for both data and functions that can be used as functions that can be used as templates for creating copies of templates for creating copies of such modules on demand.such modules on demand.

An object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data.

Basic concepts of Object Basic concepts of Object Oriented ProgrammingOriented Programming

ObjectsObjects

Objects are basic runtime entities in an object oriented system. They may represent a person, a place, a table, of data or any item that the program must handle.

Objects contain data and code to manipulate the data..

ClassClass

Class is a way to bind the data and its associated functions together.

A class allows its data to be hidden from its external use.

A new abstract data type is created during definition of a class

Data EncapsulationData Encapsulation

Data Encapsulation is the wrapping up of data and functions into a single unit.

The data is not accessible to the outside world, only those functions which are wrapped in the class can access it.

The insulation of the data from direct access by the program is called data hiding or information hiding

InheritanceInheritance

Inheritance is the process by which objects of one class acquire properties of objects of another class.

PolymorphismPolymorphism

Polymorphism means the ability to take more than one form

One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added.

A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

Why create new typesWhy create new types::

A class is a user-defined data type that has data members and member functions..

variable types include i.e. integers, characters.

The type of variable you declare tells a lot about it self.

If you declare height and width as integers, trying to hold anything else in these variables causes an error, example tying to hold your name in this variables causes an error..

By declaring a variable type it tells you:– their size in memory– information that they can hold– and what actions that can be performed on

them.

In real world applications a type is a category. Example of types can be – car, house person, fruit, and shape.

New types are created to solve real world problems, i.e. keeping track of an employee records or simulating the working of an heating system.

It’s possible to solve complex problems by using integers and characters, but it’s easier to solve complex problems if you create representations of the object that you are talking about.

A class is a user-defined data type that has data members and member functions

Revisiting C++ Structures

Structures provide a method of packaging together, data of different types. Once a structure has been defined we can create variables of that type using declarations similar to the built-in type declarations.

Structures enables us to access a collection of dissimilar, or varying data types, such as string name, an integer part number, and a real price.

Structures give the ability of grouping data together and working with the data as a whole unit.

Example a book has a collection of different things, i.e. title, author, call number, publisher, number of pages, date of publication.

Title stringAuthor string

Call number integerPublisher stringPrice float

Revisiting Revisiting C++ C++

StructuresStructures

A data structure that stores different A data structure that stores different types of data under a single variable types of data under a single variable name is called a record.name is called a record.

A structure contains a number of data A structure contains a number of data types grouped together. These data types grouped together. These data types may or may not be of same type.types may or may not be of same type.

Revisiting Revisiting C++ C++

StructuresStructures

Declaring of a structureDeclaring of a structure

Two events needs to be carried out in Two events needs to be carried out in declaring of structures same as declaring of structures same as variables. variables. A.A. Declaring of the structureDeclaring of the structureB.B. Assigning of specific values to individual Assigning of specific values to individual

record elementsrecord elements A structure must be declared first in the A structure must be declared first in the

program. program. Declaring a structure requires listing the Declaring a structure requires listing the

data type, data names, and data type, data names, and arrangement of data items.arrangement of data items.

Syntax:Syntax:

1.1. Struct <structure name>Struct <structure name>

2.2. {{

3.3. structure element 1;structure element 1;

4.4. structure element 2;structure element 2;

5.5. structure element 3;structure element 3;

6.6. }; [one or more structure }; [one or more structure variables];variables];

Example:Example:1.1. Struct bookStruct book2.2. {{3.3. char name;char name;4.4. float price;float price;5.5. int pages;int pages;6.6. };};

A new data type called A new data type called struct bookstruct book is defined. is defined.

Each variable of this data type will consist of a character Each variable of this data type will consist of a character variable called name, a float variable called price and an variable called name, a float variable called price and an integer variable called pages.integer variable called pages.

Once the structure has been declared one or more Once the structure has been declared one or more variables can be declared to be of that typevariables can be declared to be of that type

Example:Example: Struct book b1,b2,b3;Struct book b1,b2,b3; The variables b1, b2, b3 are declared to be of the type struct The variables b1, b2, b3 are declared to be of the type struct

bookbook The declaration of the structure type and the structure variable The declaration of the structure type and the structure variable

can be combinedcan be combinedExample One:Example One:

Struct bookStruct book {{ char name[10];char name[10]; float price;float price; int pages;int pages; }b1,b2,b3;}b1,b2,b3;

Example Two:Example Two: StructStruct {{ int month;int month; int day;int day; int year;int year; } birth;} birth;

Assigning actual data values to the data Assigning actual data values to the data items of a structure is referred to as items of a structure is referred to as populating the structure.populating the structure.

Accessing the Structure ElementsAccessing the Structure Elements

To access a member of the structure, To access a member of the structure, specify the name of the structure specify the name of the structure variable then a dot and the structure variable then a dot and the structure element.element.

As per the example above:- birth.month As per the example above:- birth.month refers to the first member of the birth refers to the first member of the birth structure, birth.day refers to the second structure, birth.day refers to the second member of the structure, and birth.year member of the structure, and birth.year refers to the third member.refers to the third member.

The period in each of these variable The period in each of these variable names is called the member access names is called the member access operator or the dot operatoroperator or the dot operator

Example:Example:

B1.pagesB1.pages Before a dot there must be a structure Before a dot there must be a structure

variable and after the dot a structure variable and after the dot a structure element.element.

Nested StructuresNested Structures

ExampleExample Consider the following Consider the following

two structures:two structures:1.1. Struct employeeStruct employee2.2. {{3.3. charchar emp_name[25];emp_name[25];4.4. char char address[30];address[30];5.5. char char city[10];city[10];6.6. charchar state[2];state[2];7.7. int int zip;zip;8.8. intint salary;salary;9.9. }}

1.1. struct customersstruct customers2.2. {{

3.3. charcharcust_name[25];cust_name[25];

4.4. charchar address[30];address[30];

5.5. charchar city[10];city[10];

6.6. charchar state[2];state[2];

7.7. intint zip;zip;

8.8. intint balance;balance;

9.9. }}

Even thought the two structures have different data Even thought the two structures have different data one structure can be created to consolidate the two one structure can be created to consolidate the two together. together.

1.1. Struct address_infoStruct address_info

2.2. {{

3.3. charchar address[30];address[30];

4.4. charchar city[10];city[10];

5.5. char char state[2];state[2];

6.6. intint zip;zip;

7.7. }}

This structure can be used as a member in the other structures.This structure can be used as a member in the other structures.

1.1. Struct employeeStruct employee2.2. {{3.3. charchar emp_name[25];emp_name[25];4.4. struct address_info struct address_info e_address; e_address;5.5. int int salary;salary;6.6. };};7.7. struct customerstruct customer8.8. {{9.9. char char cust_name[25];cust_name[25];10.10. struct address_infostruct address_info c_address;c_address;11.11. intint balance;balance;12.12. }; };

Array Of StructuresArray Of Structures

Example:Example:

1.1. Struct storesStruct stores

2.2. {{

3.3. intint employees;employees;

4.4. intint registers;registers;

5.5. int int sales;sales;

6.6. } store[1000];} store[1000];

The code creates 1000 store structures, each The code creates 1000 store structures, each containing three members.containing three members.

Example:Example:

1.1. Struct storesStruct stores

2.2. {{

3.3. intint employees;employees;

4.4. intint registers;registers;

5.5. int int sales;sales;

6.6. } store[1000];} store[1000];

The code creates 1000 store structures, each The code creates 1000 store structures, each containing three members.containing three members.

Limitations of C StructuresLimitations of C Structures

C does not allow the struct data types to be treated as built in types. The struct data types can not be added nor subtracted from each other.

Example:1. Struct sum2. {3. Float x;4. Float y;5. };6. Struct sum s1,s2,s3;

The variables s1,s2 and s3 can be assigned values using the dot operator but can not be added nor subtracted from each other.

Example: s3 = s1 +s2 s3 = s2 – s1

is illegal in C++.

Classes and MembersClasses and Members

Def:A class is a user-defined data type that has data members and member functions..

A class is similar to the c++ structure except that the definition of the class and all the functions that operate on the class are grouped together in one place, and further it allows its data to be hidden from its external use.

By declaring a class we create a new abstract data type and also we bind the data and its associated functions together.

A class has two major parts:a) Class declarationb) Class function definitions

The class declaration describes the type and scope of its members.

The class function definitions describe how the class functions are implemented..

Class DeclarationClass DeclarationSyntax:• Class class_name• {• permission_label_1:• type member variables;• permission_label_2:• type member functions();• } object_name

The class declaration is similar to a struct declaration. The keyword class indicates that what follows is an abstract data of the type class_name.

The body of a class is enclosed within braces and terminated by a semicolon.

The body of a class contains a declaration of the data and functions, which are collectively called class members.

The variables declared inside a class are known as data members while the functions are known as member functions..

Class name is the name for the class and the optional field object_name is one or several, valid object identifiers.

The body of the declaration can contain members that can be either data or function declarations.

The permission labels can be of any the three keywords, Private:, Public:, or Protected:.

– Private members of a class are accessible only by other members of the same class, or functions of a friend class.

– Protected members are accessible from members of their same class and friend classes and also from members of their derived classes.

– Public members are accessible from anywhere the class is visible.

Example:1. Class cat2. {3. int itsAge; // member variable

4. int itsWeight;5. void Meow(); //member function or

method

6. }

By declaring the class the memory is not allocated. What the declaration does is, it tells the compiler what the cat is, what data it contains (itsAge, itsWeight) and what it can do Meow ().

It also tells the compiler how much room must be set aside for each cat that will be created. No space is set aside for the function Meow, no space is set aside for member functions/methods.

By default functions and data declared within the class are private to that class and may be accessed only by other members of the class.

Like structures a class has two kinds of members: data members and member functions.

Data Members– Variables in a class are referred to as member variables or data members.

– A car class can have member variables representing seats, radio, tires, engine etc.

Member Functions– The functions in a class manipulate member variables. They are referred to as member functions or methods of a class.

– Member functions are functions defined within a class that act on the members of a class.

Methods of a class might include start(), Brake(). Move().

A cat class might have data members that represent age and weight, its methods might be sleep(), Meow(), ChaseMise().

– Member functions or methods are part of the class, they determine what the class can do.

Naming conventions for Naming conventions for classesclasses

C++ is case sensitive, and all class names should follow the same pattern so as to distinguish data members from non data members.

Example itsAge, itsWeight, itsSpeedcCat, cPerson.Cat, PersonRectangle, rectangle, RECTANGLEChaseMise()Drawcircle()

Defining an objectDefining an object

Once a class has been declared, we can create variables of that type by using the class name.

Example:

Cat Frisky; In C++ the class variables are known as

objects. Therefore the code defines Frisky, which is an object whose class is Cat. An object of the new type is defined the same way as defining an integer variable

Accessing class Accessing class membersmembers

The private data members of a class can only be accessed through the member functions of that class. The data members of a class can only be accessed by using the dot operator.

Example: To assign 50 to Frisky’s weight member variable, write

Frisky.itsWeight = 50; To call the Meow() function write

Frisky.Meow();

Assign to objects not to classesAssign to objects not to classes

Values are assigned to variables and not to types.Example:

If you assign int = 5 // the compiler will return an

error- Wrong

Cat.itsAge = 5; // Wrong , you cant assign 5 to the

age part of the cat. It should be int x; //define x to be an int X = 5; // set x’s value to 5 Cat Frisky; // define frisky, object of a class

cat Frisky.itsAge = 5;// assign 5 to the object

frisky.

Private versus PublicPrivate versus Public All members of a class- member variables/data

and member functions/methods are private by default.

Private members of a class are hidden to all but not to the member functions of that class.

Private members can be accessed only by the methods of the class itself.

Public members can be accessed through any object of the class.

The public members are visible and accessible to everybody

Example:1. Class cat2. {3. int itsAge;4. int itsWeight;5. void Meow();6. }; In this declarations itsAge, itsWeight and

Meow() are all private since all members of a class are private by default.

If the following is written in the main function,– Cat Boots;– Boots.itsage = 5; //the compiler returns an error can’t

access private data.

In order to access the data members of the class Cat, use the keyword public

Example:1. Class cat2. {3. public:4. int itsAge;5. int itsWeight;6. void Meow();7. };

Program to demonstrate the access of private data members

1. #include <iostream.h>2. class XYCoord3. {4. int x, y;5. };

6. void main(void)7. {8. // Make an instance of the class9. XYCoord coord;10. coord.x = 2;11. coord.y = 3;12. }

The new thing in this code is the operator:: of scope included in the definition of set_values(), its used to declare a member of a class outside it.

X and y are made private and therefore the rest of the program does not have a way to directly access them.

Advantages of classesAdvantages of classes The limitation of the c++ structures They do not allow the struct data type to be treated like built in types. Example: Struct nuclear { float a; float b; }; sttuct nuclear n1,n2,cn3;

The nuclear objects can easly be assigned values using the dot operator But they can not be added together or subtracted from the other. Example: N3 = n2 +n1; //illegal Structures do not permit data hiding, structure members can be directly

accessed by the structure variables, or any function in the scope. The structure members are public members

An advantage of classes is that several different

objects can be declared from it.

Member function can be defined in two places:

1. Outside the class definition 2. Inside the class definition

Outside of the class definitionOutside of the class definition Member functions defined inside a class have to be declared separately outside a class

1. # include<iostream.h>2. class set3. {4. int a,b;5. public:6. void input(void);7. void display(void);8. int largest(void);9. };10.int set :: largest(void)11.{12. if (a >= b)13. return (a);14. else15. return(b);16.}

17. void set :: input(void)18. {19. cout << "Enter the values of a and b"<< "\n";20. cin >> a >> b;21. }22. void set :: display(void)23. {24. cout <<"Largest value is "<<largest()<<endl;25. }26. main()27. {28. set A;29. A.input();30. A.display();31. }

A member function begins with the name of the class followed by two colons, the name of a function and its parameters.

The difference between a member function and a normal function is that a member function incorporates a membership identity label in the header. The label tells the compiler which class the function belongs to.

.

Syntax:Return type class_name :: function name (argument declaration){

function body}

The label class name:: tells the compiler that the function name belongs to the class name. Meaning the scope of the function is restricted to the class name specified in the header

The symbol :: is called a scope resolution operator.

The special characteristics of member functions include:-

Several classes can use the same function name. The class name resolves their scope.

Member functions can access the private data of the class, but non member function cannot. (This rule is overcome by the friend function)

A member function can call another member function directly without using the dot operator

Inside of the class definitionInside of the class definition

In this, the function declaration is replaced by the actual function definition inside the class.

Example:1. Class book2. {3. char name;4. int number;5. float cost;6. public:7. void getdata(int a, float b);8. void putdata(void)9. {10. cout << number <<endl;11. cout << cost <<endl;12. }13. }; A function defined inside a class is treated as an inline

function.

Nesting of member functionsNesting of member functions A member function can be called by using its name inside another member function of the

same class.

1. # include<iostream.h>2. class set3. {4. int a,b;5. public:6. void input(void);7. void display(void);8. int largest(void);9. };10. int set :: largest(void)11. {12. if (a >= b)13. return (a);14. else15. return(b);16. }

17. void set :: input(void)18. {19. cout << "Enter the values of a an b"<< "\

n";20. cin >> a >> b;21. }22. void set :: display(void)23. {24. cout <<"Largest value is

"<<largest()<<endl; // nesting of member function

25. }26. main()27. {28. set A;29. A.input();30. A.display();31. }

Private member functionsPrivate member functions Even though the data members are put on the private section and the functions on the public some situations require some functions to be put in the private section.

Functions that deal with adding of bank accounts, deleting a customer account or providing accessing balance accounts of customers should be put in restricted areas.

A private member function can only be called by another member function that is a member of its class

Example:1. Class bankcustomer2. {3. int m;4. int custbalance();5. void custdelete(void);6. int addaccount();7. public:8. void update(void);9. void write(void);10. void check(void);11. }; In this case if Robert is an object of the class

backcustomer he can not directly access the balance by using the custbalance function.

Robert.custbalance(); // object can not access private member

The function custbalance can be called by the function check() to check the balance.

1. Void bankcustomer :: check(void)

2. {

3. custbalance();

4. }

Arrays within a classArrays within a class

Arrays can be used as member variables in a class.

Example:1. Const int no=20;2.

3. Class array4. {5. int emp[no];6. public:7. void setbalance(void);8. void display(void)9. };An array variable emp is declared as a private member

of the class array, and can be used is the member function like any other array variable.

1. #include<iostream.h>2. #include <stdio.h>3. const m = 50;4. class items5. {6. int itemcode[m];7. float itemprice[m];8. int count;9. public:10. void cnt(void)11. {12. count = 0;13. }14. void getitem(void);15. void

displaysum(void);16. void remove(void);17. void

displayitems(void);18. };

19. void items :: getitem(void)20. {21. cout << "\tEnter item

code:";22. cin >>

itemcode[count];23. cout << "\tEnter item

cost:";24. cin >>

itemprice[count];25. count ++;26. }27. void items ::

displaysum(void)28. {29. float sum = 0;30. for (int i=0; i<count;

i++)31. sum = sum +

itemprice[i];32. cout << "Total

value :" << sum <<endl;33. }

34. void items :: remove(void) // delete a specified item.

35. {36. int a;37. cout << "enter item

code:";38. cin >>a;39. for ( int i=10; i<count;

i++)40. if(itemcode[i]

==a)41.

itemprice[i]=0;42. }43. void items :: displayitems(void)44. {45. cout << "code Price";46. for(int i=0; i<count; i+

+)47. {48. cout <<"\n" <<

itemcode[i];49. cout <<" "

<<itemprice[i];50. }51. cout << "\n";52. }

52. main()53. {54. items order;55. order.cnt();56. int x;57. do58. {59. cout <<"\t

MAIN MENU \n";60. cout <<"\n\t1

: Add an item ";61. cout <<"\n\t2

: Display total value";62. cout <<"\n\t3

: Delete an item";63. cout <<"\n\t4

: Display all items";64. cout <<"\n\t5

: Quit";65. cout << "\n\

n\t What is your choice?";

66. cin >> x;

67.switch(x)68. {69. case 1 :

order.getitem();70.

break;71. case 2 :

order.displaysum();72.

break;73. case 3 :

order.remove();74.

break;75. case 4 :

order.displayitems();76.

break;77. default

: cout << "Error in input; try again\n";

78. }79. }while(x !=5);80. return 0;81.}

Program Explanation:The program has two arrays itemcode[], to hold the code number of items and itemprice[] to hold the prices. Data member count is use to keep a record of the items in the list. The statement

Cont int m=50; //defines the size of the array membersThe function CNT() sets the variable count to zero. Getitem() gets the item code and the item price and assigns them to the array members itemCode[count] and itemPrice[count]. Count is incremented after the assignment operation is over. Remove() function deletes a given item from the list, it uses the item code to locate it in the list and sets the price to zero. Lastly the function displayItems() displays all the items in the list

Arrays of objectsArrays of objects

1. Example:

2. Class employee

3. {

4. char name[30];

5. float age;

6. public:

7. void getinfo(void);

8. void putinfo(void);

9. };

Employee is a user defined data type and can be used to create objects that relate to different categories of the

employees

Example:Employee manager[3];

Employee supervisor[10]; Employee

workers[100];];

The array manager contains three objects,, namely manager[0], manager[1],manager[2], of type employee class. The foreman array contains 15 objects and the worker array contains 75 objects.

Since the array of objects behave the same way as any object, you can use the array accessing method to access individual elements and then the dot operator to access the member functions.

manager[i].putinfo();

// will display the ith element of the array manager and invoke the member function putdata().

Program Example : Array of objects. The program reads Program Example : Array of objects. The program reads in a number of employees and prints them on the screenin a number of employees and prints them on the screen

1.1. #include <iostream.h>2. class employee3. {4. char name[30];5. float age;6. public:7. void getdata(void);8. void putdata(void);9. };10. void employee :: getdata(void)11. {12. cout << "Enter the

employee name:";13. cin >> name;14. cout <<"Enter the

employee age:";15. cin >> age;16. }17. void employee :: putdata(void)18. {19. cout <<"Name :" <<

name <<"\n";20. cout <<"Age: " <<age <<

"\n";21. }

22. const int size=3;23. main()24. {25. employee manager[size];26. for(int i=0; i<size; i++)27. {28. cout <<"\nDetails of

manager"<<i+1<<"\n";29. manager[i].getdata();30. }31. cout <<"\n";32. for (i=0; i<size; i++)33. {34. cout <<"\n Manager" << i

+ 1 <<"\n";35. manager[i].putdata();36. }37. return 0;38. }

Practice: Modify the above program to

accommodate different types of employees, i.e. supervisors, workers etc.

ENDEND

top related