object oriented slides

41
Object Oriented Object Oriented Programming Programming (CSC-205(3)) (CSC-205(3)) Instructor: Arjumand Yar Instructor: Arjumand Yar Khan Khan

Upload: ahad-nadeem

Post on 09-Jan-2017

12 views

Category:

Data & Analytics


0 download

TRANSCRIPT

Page 1: Object oriented slides

Object Oriented Object Oriented ProgrammingProgramming

(CSC-205(3))(CSC-205(3))

Instructor: Arjumand Yar Instructor: Arjumand Yar KhanKhan

Page 2: Object oriented slides

Internal EvaluationInternal Evaluation

Mid- Term Exam 15 MarksAssignment 6 //Quizzes/Tests 9 //Presentation 10 //Major Assignment 10 //Total internal Marks 50 //Final Term ExaminationFinal Term Exam 50 //Total Marks 100 //

Page 3: Object oriented slides

Text Books: Text Books:

Any book on Object Oriented Any book on Object Oriented Programming Programming

Herbert Schildt, C++ form the Ground Up, 4TH Edition.(Harvey & Paul) Deitel & Deitel C++ How to Program, 6/E

Reference Books:

Page 4: Object oriented slides

Brief History of C++Brief History of C++

In 1967, BCPL (Basic Combined Programming Language) language was developed by Martin Richards.

The BCPL language was used to write operating systems and compilers.

After two years, Ken Thomsan developed “B” programming language.

B programming language had advance features as compared with BCPL. Both BCPL and B were “type less” languages.

Page 5: Object oriented slides

Brief History of C++Brief History of C++

What does “type less” languages mean ?

It means you do not have to declare the data type explicitly. 

For example: declaring integers . . . if it's TYPED then you declare as an integer your variable. 

If “TYPELESS”, you can do 

$var=39 

and it will be interpreted as an integer (it will be treated as string if double-quoted, however). 

Page 6: Object oriented slides

Brief History of C++Brief History of C++

In the early 1970s, Dennis Ritchie of Bell Laboratories was engaged in a project to develop a new operating system. 

Ritchie discovered that in order to accomplish his task he needed the use of a programming language that was concise and that produced compact and speedy programs.

This need led Ritchie to develop the programming language called C.

Page 7: Object oriented slides

Brief History of C++Brief History of C++  In the early 1980's, a newprogramming language was created which was based upon the C language. 

This new language was developed by  Bjarne Stroustrup and was called C++. 

Stroustrup states that the purpose of C++ is to make writing good programs easier and more pleasant for the individual programmer. 

When he designed C++, he added OOP (Object Oriented Programming) features to C without significantly changing the C component. 

Page 8: Object oriented slides

Brief History of C++Brief History of C++

  There are several versions of the C++ language, of which Visual C++ is one of them.  Other dialects include Borland C++, Turbo C++, and Code Warrior (Mac). 

All of these software packages enable you to create computer programs with C++, but they all implement the C++ language in a slightly different manner. 

In an attempt to maintain portability of both the C and C++ languages, the American National Standards Institute (ANSI) developed a standard of consistency for C and C++ programming. 

Thus C++ is a "relative" (called a superset) of C, meaning that any valid C program is also a valid C++ program.

Page 9: Object oriented slides

SIMULA 1 (1962) and Simula 67 (1967) [SIMULA 1 (1962) and Simula 67 (1967) [Ole-John Dahl and Kristen Ole-John Dahl and Kristen Nygaard] were the first languages with object-oriented features Nygaard] were the first languages with object-oriented features BUTBUT less object-oriented features when compared to C++ less object-oriented features when compared to C++ after it was enriched in 1990‘s after it was enriched in 1990‘s

Brief History of OOPBrief History of OOP

“Believed that”

C++ was the first Object-Oriented Language

However !

Page 10: Object oriented slides

C++ was powerful enough as compared to C languageC++ was powerful enough as compared to C language Major limitation was its complexity. Major limitation was its complexity.

Java Programming [James Gosling, Bill Joy etc 1991].Java Programming [James Gosling, Bill Joy etc 1991].

Java quickly grew in popularity with the growth of WWW.Java quickly grew in popularity with the growth of WWW.

Java was replaced by C# by Microsoft in 2000.Java was replaced by C# by Microsoft in 2000.

Brief History Brief History

Page 11: Object oriented slides

PROCEDURAL PROGRAMMINGPROCEDURAL PROGRAMMING Procedural programming is a classic Procedural programming is a classic

programming where the program language is programming where the program language is used to tell the computer EXACTLY what to do - used to tell the computer EXACTLY what to do - step by step. step by step.

A program in a procedural language is a list of A program in a procedural language is a list of instruction. That is, each statement in the instruction. That is, each statement in the language tell the computer to do something.language tell the computer to do something.

The focus of procedural programming is to The focus of procedural programming is to break down a programming task into a break down a programming task into a collection of variables, data structures, collection of variables, data structures, and subroutines.and subroutines.

Page 12: Object oriented slides

PROCEDURAL PROGRAMMINGPROCEDURAL PROGRAMMING Examples of procedural languages include Examples of procedural languages include

Fortran, COBOL and C, which have been Fortran, COBOL and C, which have been around since the 1960s and 70s. around since the 1960s and 70s. 

Page 13: Object oriented slides

Limitations ofLimitations ofProcedural ProgrammingProcedural Programming The lack of encapsulation in structured The lack of encapsulation in structured

programming results in longer programs due programming results in longer programs due to the repetition of code in several places to the repetition of code in several places within a single program.within a single program.

This long code in turn makes it difficult to This long code in turn makes it difficult to effectively locate and fix errors in the program.effectively locate and fix errors in the program.

Structured programming lacks information Structured programming lacks information hiding and sometimes there is a clash of hiding and sometimes there is a clash of variables when different parts of the program variables when different parts of the program overwrite the same variableoverwrite the same variable

Page 14: Object oriented slides

Limitations ofLimitations ofProcedural ProgrammingProcedural Programming Data EncapsulationData Encapsulation Data encapsulation, sometimes referred to Data encapsulation, sometimes referred to

as data hiding, is the mechanism whereby as data hiding, is the mechanism whereby the implementation details of a class are kept the implementation details of a class are kept hidden from the user. The user can only hidden from the user. The user can only perform a restricted set of operations on the perform a restricted set of operations on the hidden members of the class by executing hidden members of the class by executing special functions commonly called special functions commonly called methodsmethods. . The actions performed by the methods are The actions performed by the methods are determined by the designer of the class. determined by the designer of the class. 

Page 15: Object oriented slides

Limitations ofLimitations ofProcedural ProgrammingProcedural Programming A popular example you’ll hear for encapsulation is driving a car. Do A popular example you’ll hear for encapsulation is driving a car. Do

you need to know exactly how every aspect of a car works (engine, you need to know exactly how every aspect of a car works (engine, carburettor, alternator, and so on)? No - you need to know how to carburettor, alternator, and so on)? No - you need to know how to use the steering wheel, brakes, accelerator, and so on.use the steering wheel, brakes, accelerator, and so on.

Another example is searching for a value in an array. In Java, you Another example is searching for a value in an array. In Java, you can do the following:can do the following:

The above code will return true if the value 11 is in myArray, The above code will return true if the value 11 is in myArray, otherwise it will return false. How does the contains() method work? otherwise it will return false. How does the contains() method work? Which searching technique does it use? Does it pre-sort the array Which searching technique does it use? Does it pre-sort the array before searching? The answer is before searching? The answer is it doesn't matterit doesn't matter because the exact  because the exact implementation of the method is hidden.implementation of the method is hidden.

Page 16: Object oriented slides

Limitations ofLimitations ofProcedural ProgrammingProcedural Programming Structured programming is not suitable for Structured programming is not suitable for

the development of large programs and does the development of large programs and does not allow reusability of any set of codes.not allow reusability of any set of codes.

Page 17: Object oriented slides

Object-Oriented Programming vs. Object-Oriented Programming vs. Procedural Programming cont…Procedural Programming cont…

  One alternative to procedural programming is One alternative to procedural programming is object oriented programming. object oriented programming.

Object oriented programming is meant to address Object oriented programming is meant to address the difficulties with procedural programming.  the difficulties with procedural programming.  

In object oriented programming, the main modules In object oriented programming, the main modules in a program are classes, rather than in a program are classes, rather than procedures.  The object-oriented approach lets you procedures.  The object-oriented approach lets you create classes and objects that model real world create classes and objects that model real world objects.objects.

Page 18: Object oriented slides

ClassesClasses ClassesClasses Classes declaration & definitionClasses declaration & definition Members of a classMembers of a class Access SpecifiersAccess Specifiers ObjectsObjects Declaring objects of a classDeclaring objects of a class Calling members of a Class Calling members of a Class Defining member functions outside the classDefining member functions outside the class Storage of objects in memory.Storage of objects in memory.

Page 19: Object oriented slides

ClassClass The most powerful feature of C++ programming language is that it The most powerful feature of C++ programming language is that it

support OOP.support OOP. In OOP , the computer program is divided into object.In OOP , the computer program is divided into object. OOP language is an easy and flexible approach for designing and OOP language is an easy and flexible approach for designing and

organizing the program. organizing the program. The program is designed by using Class.The program is designed by using Class.

Page 20: Object oriented slides

ClassClass A class A class hashas– data data – functionsfunctions

Page 21: Object oriented slides

Classes vs StructureClasses vs Structure Classes and Structure are similar. Classes and Structure are similar. Both have same syntax.Both have same syntax.

ButBut “ “structures are exclusively used to hold data, whereasstructures are exclusively used to hold data, whereas Class is used to hold both Data and Functions”.Class is used to hold both Data and Functions”.

Page 22: Object oriented slides

ClassClass A Class is a user defined data type.A Class is a user defined data type.

It is therefore used to declare its variables or instancesIt is therefore used to declare its variables or instances

Page 23: Object oriented slides

ObjectObjectThe variable or instances of the class are calledThe variable or instances of the class are calledObjects.Objects.

Page 24: Object oriented slides

Declaration of a Declaration of a classclass

class name_of_classclass name_of_class{{

// definition of a class// definition of a class

}}

Page 25: Object oriented slides

class Dateclass Date{{Private:Private: int day ;int day ;

int month ;int month ;int year ;int year ;

Public:Public:Void print(void) { // body of functionVoid print(void) { // body of function}}} ;} ;

Example Example

Page 26: Object oriented slides

main ( )main ( ){{

Date mydate ;Date mydate ;}}

Declaration of ObjectDeclaration of Object

Page 27: Object oriented slides

main ( )main ( ){{

Date mydate ;Date mydate ;// manipulate the data members // manipulate the data members mydate.day ;mydate.day ;mydate.month ;mydate.month ;mydate.year ;mydate.year ;

mydate.print();mydate.print();}}

Calling Members through Calling Members through ObjectObject

Page 28: Object oriented slides

Normally two types of accessNormally two types of accessspecifiers:specifiers:

PrivatePrivate PublicPublic

Member Access SpecifiersMember Access Specifiers

Page 29: Object oriented slides

The member of the class that The member of the class that cancan

be accessed only from within be accessed only from within thethe

class are called Private class are called Private membersmembers

PrivatePrivate

Page 30: Object oriented slides

Default visibility ofDefault visibility ofall data and functionall data and functioninside a class isinside a class isprivateprivate

Page 31: Object oriented slides

The member of the class that The member of the class that cancan

be accessed both from inside be accessed both from inside thethe

class as well as outside the class as well as outside the classclass

are called Public membersare called Public members

PublicPublic

Page 32: Object oriented slides

class Dateclass Date{{

private :private :

// private data and functions // private data and functions

public :public :

// public data and functions // public data and functions };};

Page 33: Object oriented slides

class Dateclass Date{{

private : private : int day , month , year ;int day , month , year ;

public :public :setMonth ( ) ;setMonth ( ) ;print ( ) ;print ( ) ;

};};

Date Class Date Class

Page 34: Object oriented slides

main ( )main ( ){{Date mydate ;Date mydate ;mydate.setMonth ( 10 ) ;mydate.setMonth ( 10 ) ;mydate.print ( ) ;mydate.print ( ) ;

}}

Page 35: Object oriented slides

Programming Example Programming Example 11 Write a program to input and print Write a program to input and print

date on the screen by using class.date on the screen by using class.#include<iostream>#include<iostream>using namespace std;using namespace std;class edate{class edate{

private:private:int y,m,d;int y,m,d;public:public:void gdate (void){void gdate (void){cout<<"Enter year:";cout<<"Enter year:";cin>>y;cin>>y;cout<<"Enter months:";cout<<"Enter months:";

cin>>m;cin>>m;cout<<"Enter days:";cout<<"Enter days:";cin>>d;}cin>>d;}void printdate(void){void printdate(void){cout<<"Date is:"<<endl;cout<<"Date is:"<<endl;cout<<y<<"/"<<m<<"/"<<d<<endl;cout<<y<<"/"<<m<<"/"<<d<<endl;

}}};};

main(){main(){edate c;edate c;c.gdate();c.gdate();c.printdate();c.printdate();}}

Page 36: Object oriented slides

Programming Example Programming Example 22/*Write a program to input the name of student and /*Write a program to input the name of student and

marks of three subjects. Calculate the total marks marks of three subjects. Calculate the total marks and average marks. Each subject has a maximum and average marks. Each subject has a maximum of 100 marks.*/of 100 marks.*/

#include<iostream>#include<iostream>using namespace std;using namespace std;class student {class student {

private: private: char name[15];char name[15];float s1,s2,s3,total,avg;float s1,s2,s3,total,avg;public:public:void getrec (void){void getrec (void){cout<<"Enter name of a student :";cin>>name;cout<<"Enter name of a student :";cin>>name;cout<<"Enter marks of ist subject:";cin>>s1;cout<<"Enter marks of ist subject:";cin>>s1;cout<<"Enter marks of second subject:";cin>>s2;cout<<"Enter marks of second subject:";cin>>s2;cout<<"Enter marks of third subject:";cin>>s3;cout<<"Enter marks of third subject:";cin>>s3;total=s1+s2+s3;avg=total/3.0;}total=s1+s2+s3;avg=total/3.0;}

void show(void){void show(void){cout<<"Name of student is"<<name<<endl;cout<<"Name of student is"<<name<<endl;cout<<"Marks in subject 1= "<<s1<<endl;cout<<"Marks in subject 1= "<<s1<<endl;cout<<"Marks in subject 2 ="<<s2<<endl;cout<<"Marks in subject 2 ="<<s2<<endl;cout<<"Marks in subject 3 ="<<s3<<endl;cout<<"Marks in subject 3 ="<<s3<<endl;cout<<"Total Marks are "<<total<<endl;cout<<"Total Marks are "<<total<<endl;cout<<"Average is equal = "<<avg<<endl;cout<<"Average is equal = "<<avg<<endl;

}};main(){}};main(){student s;student s;s.getrec();s.getrec();s.show();s.show();

}}

Page 37: Object oriented slides

Programming Example Programming Example 33/*Write a program by using a class to input two values /*Write a program by using a class to input two values

using a member function of a class. using a member function of a class. Display the sum of the two values by using another Display the sum of the two values by using another

member function of the class.member function of the class.*/*/#include<iostream>#include<iostream>using namespace std;using namespace std;class sum {class sum {

private:private:int n,m;int n,m;public: public: void get (int a ,int b){void get (int a ,int b){n=a;m=b;n=a;m=b;}}void display (void){void display (void){cout<<"sum="<<n+m;cout<<"sum="<<n+m;}}

};};

main(){main(){sum s;sum s;int x, y;int x, y;cout<<"Enter first value:";cout<<"Enter first value:";cin>>x;cin>>x;cout<<"Enter Second value:";cout<<"Enter Second value:";cin>>y;cin>>y;s.get(x,y);s.get(x,y);s.display();s.display();

}}

Page 38: Object oriented slides

Members functions of a class can also be defined outside the class. In this Members functions of a class can also be defined outside the class. In this case, only the prototype of the member function is declared inside the case, only the prototype of the member function is declared inside the class.class.

The member functions are defined outside the class in the similar was as a The member functions are defined outside the class in the similar was as a user defined functions are defined. However, the scope resolution operator user defined functions are defined. However, the scope resolution operator (::) is used in the member function declarator to define the function of class (::) is used in the member function declarator to define the function of class outside the class.outside the class.

General Syntax:General Syntax:

Type class_name :: function_name(argument){Type class_name :: function_name(argument){//body//body}}

Defining Member Functions Outside Defining Member Functions Outside the Classthe Class

Page 39: Object oriented slides

void Date :: display ( )void Date :: display ( ){{

cout << day << “/ " << month << “/ " << year ;cout << day << “/ " << month << “/ " << year ;}}

Example Example

Page 40: Object oriented slides

Programming Example Programming Example 44// Write a program to find volume of a BOX using Scope // Write a program to find volume of a BOX using Scope

resolution operatorsresolution operators#include<iostream>#include<iostream>using namespace std;using namespace std;class Boxclass Box{ public:{ public: double length; // Length of a boxdouble length; // Length of a box double breadth; // Breadth of a boxdouble breadth; // Breadth of a box double height; // Height of a boxdouble height; // Height of a box // Member functions declaration// Member functions declaration double getVolume(void);double getVolume(void); void setLength( double len );void setLength( double len ); void setBreadth( double bre );void setBreadth( double bre ); void setHeight( double hei );};void setHeight( double hei );};// Member functions definitions// Member functions definitionsdouble Box::getVolume(void)double Box::getVolume(void){return length * breadth * height;{return length * breadth * height;}void Box::setLength( double len )}void Box::setLength( double len ){{ length = len;length = len;}}

void Box::setBreadth( double bre )void Box::setBreadth( double bre ){ breadth = bre;{ breadth = bre;}}void Box::setHeight( double hei )void Box::setHeight( double hei ){ height = hei;{ height = hei;}}// Main function for the program// Main function for the programint main( )int main( ){ Box Box1; // Declare Box1 of type Box{ Box Box1; // Declare Box1 of type Box double volume = 0.0; // Store the volume of a box heredouble volume = 0.0; // Store the volume of a box here // box 1 specification// box 1 specification Box1.setLength(6.0); Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setBreadth(7.0); Box1.setHeight(5.0);Box1.setHeight(5.0);// volume of box 1// volume of box 1 volume = Box1.getVolume();volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl;cout << "Volume of Box1 : " << volume <<endl;

return 0;return 0;}}

Page 41: Object oriented slides

When an object of a class is created , a space is reserved in the When an object of a class is created , a space is reserved in the computer memory to hold its data members. Similarly, separate computer memory to hold its data members. Similarly, separate memory spaces are reserved for each class object.memory spaces are reserved for each class object.

The member functions of a class are, however. stored at only one place The member functions of a class are, however. stored at only one place in the computer memory. All objects of the class use the same in the computer memory. All objects of the class use the same member functions to process data.member functions to process data.

Therefore, while each object has a separate memory space for data Therefore, while each object has a separate memory space for data members, the member functions of a class are stored in only one members, the member functions of a class are stored in only one place and are shared by all objects of the class.place and are shared by all objects of the class.

Storage of objects in memoryStorage of objects in memory