Transcription

Object Oriented Programming UsingC

LECTURE NOTESONObject Oriented Programming Using C Prepared byDr. Subasish MohapatraDepartment of Computer Science and ApplicationCollege of Engineering and Technology, BhubaneswarBiju Patnaik University of Technology, Odisha2P.T.O

SYLLABUSPCCS2207Object Oriented ProgrammingModule IIntroduction to object oriented programming, user defined types, structures, unions,polymorphism, encapsulation. Getting started with C syntax, data-type, variables,strings, functions, default values in functions, recursion, namespaces, operators, flowcontrol, arrays and pointers.Module IIAbstraction mechanism: Classes, private, public, constructors, destructors, member data,member functions, inline function, friend functions, static members, and references.Inheritance: Class hierarchy, derived classes, single inheritance, multiple, multilevel,hybrid inheritance, role of virtual base class, constructor and destructor execution, baseinitialization using derived class constructors.Polymorphism: Binding, Static binding, Dynamic binding, Static polymorphism: FunctionOverloading, Ambiguity in function overloading, Dynamic polymorphism: Base classpointer, object slicing, late binding, method overriding with virtual functions, pure virtualfunctions, abstract classes.Operator Overloading: This pointer, applications of this pointer, Operator function,member and non member operator function, operator overloading, I/O operators.Exception handling: Try, throw, and catch, exceptions and derived classes, functionexception declaration, unexpected exceptions, exception when handling exceptions,resource capture and release.Module IIIDynamic memory management, new and delete operators, object copying, copyconstructor, assignment operator, virtual destructor.Template: template classes, template functions.Standard Template Library: Fundamental idea about string, iterators, hashes, iostreamsand other types.Namespaces: user defined namespaces, namespaces provided by library.Object Oriented Design, design and programming, role of classes.Text Books:1. Object Oriented Programming with C by E. Balagurusamy, McGraw-HillEducation (India)2. ANSI and Turbo C by Ashoke N. Kamthane, Pearson EducationReference Books:1. Big C - Wiley India2. C : The Complete Reference- Schildt, McGraw-Hill Education (India)3. C and Object Oriented Programming – Jana, PHI Learning.4. Object Oriented Programming with C - Rajiv Sahay, Oxford5. Mastering C - Venugopal, McGraw-Hill Education (India)3P.T.O

CONTENTSLecture 01:Lecture 02:Lecture 03:Lecture 04:Lecture 05:Lecture 06:Lecture 07:Lecture 08:Lecture 09:Lecture 10:Lecture 11:Lecture 12:Lecture 13:Lecture 14:Lecture 15:Lecture 16:Lecture 17:Lecture 18:Lecture 19:Lecture 20:Lecture 21:Lecture 22 & 23:Lecture 24:Lecture 25:Lecture 26:Lecture 27:Lecture 28:Lecture 29:Lecture 30:Lecture 31:Lecture 32:Lecture 33:Lecture 34:Lecture 35:Lecture 36:Lecture 37:Lecture 38:Lecture 39:Lecture 40:Lecture 41:Lecture 42:IntroductionObject Oriented ProgrammingBASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMINGBENEFITS OF OOPBasics of C TokensBasic Data types in C Symbolic ConstantOperatorsControl StructuresFunctions in C Function OverloadingClassMember FunctionNesting of Member functionArray with ClassStatic Data MemberFriendly functionsReturning ObjectsConstructorsDestructorsOperator OverloadingType ConversionClass to Basic typeInheritanceMultilevel InheritanceHierarchical InheritanceVirtual Base ClassPolymorphismVirtual functionsPure Virtual FunctionsC function overridingException HandlingArray reference out of boundContainership in C TemplateClass TemplateVirtual destructorsManaging Console I/ONamespacesNew & Delete Operators4P.T.O

Module-1:LECTURE-1Introduction:Programmers write instructions in various programming languages to perform their computationtasks such as:(i) Machine level Language(ii) Assembly level Language(iii) High level LanguageMachine level Language :Machine code or machine language is a set of instructions executed directly by a computer's centralprocessing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or anALU operation on a unit of data in a CPU register or memory. Every program directly executed by aCPU is made up of a series of such instructions.Assembly level Language :An assembly language (or assembler language) is a low-level programming language for a computer,or other programmable device, in which there is a very strong (generally one-to-one) correspondencebetween the language and the architecture's machine code instructions. Assembly language isconverted into executable machine code by a utility program referred to as an assembler; theconversion process is referred to as assembly, or assembling the code.High level Language :High-level language is any programming language that enables development of a program in muchsimpler programming context and is generally independent of the computer's hardware architecture.High-level language has a higher level of abstraction from the computer, and focuses more on theprogramming logic rather than the underlying hardware components such as memory addressing andregister utilization.The first high-level programming languages were designed in the 1950s. Now there are dozens ofdifferent languages, including Ada , Algol, BASIC, COBOL, C, C , JAVA, FORTRAN, LISP,Pascal, and Prolog. Such languages are considered high-level because they are closer to humanlanguages and farther from machine languages. In contrast, assembly languages are considered lowlevel because they are very close to machine languages.The high-level programming languages are broadly categorized in to two categories:(iv) Procedure oriented programming(POP) language.(v) Object oriented programming(OOP) language.5P.T.O

Procedure Oriented Programming LanguageIn the procedure oriented approach, the problem is viewed as sequence of things to be done such asreading , calculation and printing.Procedure oriented programming basically consist of writing a list of instruction or actions for thecomputer to follow and organizing these instruction into groups known as functions.Main programFunction-1Function-2Function-3The disadvantage of the procedure oriented programming languages is:1. Global data access2. It does not model real word problem very well3. No data hidingGlobal dataGlobal dataFunction-1Function-2Function-3Local dataLocal dataLocal dataCharacteristics of procedure oriented programming:1.2.3.4.5.6.Emphasis is on doing things(algorithm)Large programs are divided into smaller programs known as functions.Most of the functions share global dataData move openly around the system from function to functionFunction transforms data from one form to another.Employs top-down approach in program design6P.T.O

LECTURE-2Object Oriented Programing“Object oriented programming as an approach that provides a way of modularizing programs bycreating partitioned memory area for both data and functions that can be used as templates forcreating copies of such modules on demand”.Object AObject BDataDataCommunicationFunctionsFunctionsObject CFunctionsDataFeatures of the Object Oriented programming1.2.3.4.5.6.7.8.Emphasis is on doing rather than procedure.programs are divided into what are known as objects.Data structures are designed such that they characterize the objects.Functions that operate on the data of an object are tied together in the datastructure.Data is hidden and can’t be accessed by external functions.Objects may communicate with each other through functions.New data and functions can be easily added.Follows bottom-up approach in program design.7P.T.O

LECTURE-3BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING1.2.3.4.5.6.7.ObjectsClassesData abstraction and encapsulationInheritancePolymorphismDynamic bindingMessage passingOBJECTSObjects are the basic run-time entities in an object-oriented system. They may represent a person, aplace, a bank account, a table of data or any item that the program must handle.The fundamental idea behind object oriented approach is to combine both data and functioninto a single unit and these units are called objects.The term objects means a combination of data and program that represent some real wordentity. For example: consider an example named Amit; Amit is 25 years old and his salary is 2500.The Amit may be represented in a computer program as an object. The data part of the object wouldbe (name: Amit, age: 25, salary: 2500)The program part of the object may be collection of programs (retrive of data, change age,change of salary). In general even any user –defined type-such as employee may be used. In theAmit object the name, age and salary are called attributes of the object.Object: rageDisplaySTUDENTTotalAverageDisplayCLASS:A group of objects that share common properties for data part and some program part arecollectively called as class.In C a class is a new data type that contains member variables and member functions thatoperate on the variables.8P.T.O

DATA ABSTRACTION :Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as size, widthand cost and functions to operate on the attributes.DATA ENCAPSALATION :The wrapping up of data and function into a single unit (called class) is known asencapsulation. The data is not accessible to the outside world and only those functions which arewrapped in the class can access it. These functions provide the interface between the objects data andthe program.INHERITENCE :Inheritance is the process by which objects of one class acquire the properties of anotherclass. In the concept of inheritance provides the idea of reusablity. This mean that we can addadditional features to an existing class with out modifying it. This is possible by desining a new classwill have the combined features of both the classes.POLYMORPHISIM:Polymorphism means the ability to take more than one form. An operation may exhibit differentinstance. The behaviour depends upon the type of data used in the operation.A language feature that allows a function or operator to be given more than one definition. The typesof the arguments with which the function or operator is called determines which definition will beused.Overloading may be operator overloading or function overloading.It is able to express the operation of addition by a single operater say ‘ ’. When this is possible youuse the expression x y to denote the sum of x and y, for many different types of x and y; integers ,float and complex no. You can even define the operation for two strings to mean the concatenationof the strings.DYNAMIC BINDING :Binding refers to the linking of a procedure call to the code to the executed inresponse to the call. Dynamic binding means the code associated with a given procedure call is notknown untill the time of the call at run-time. It is associated with a polymorphic reference dependsupon the dynamic type of that reference.9P.T.O

MESSAGE PASSING :An object oriented program consists of a set of objects that communicate with eachother.A message for an object is a request for execution of a procedure and therefore willinvoke a function (procedure) in the receiving object that generates the desired result. Messagepassing involves specifying the name of the object, the name of the function (message) andinformation to be sent.Employee .Salary (name)ObjectInformationMessage10P.T.O

LECTURE- 4BENEFITS OF OOP:Oop offers several benefits to both the program designer and the user. Object-oriented contributes tothe solution of many problems associated with the development and quality of software products.The principal advantages are :1.2.3.4.5.6.7.8.Through inheritance we can eliminate redundant code and extend the use of existingclasses.We can build programs from the standard working modules that communicate with oneanother, rather than having to start writing the code from scratch. This leads to saving ofdevelopment time and higher productivity.This principle of data hiding helps the programmer to build secure programs that can’t beinvaded by code in other parts of the program.It is possible to have multiple instances of an object to co-exist with out any interference.It is easy to partition the work in a project based on objects.Object-oriented systems can be easily upgraded from small to large systems.Message passing techniques for communication between objects makes the interfacedescription with external systems much simpler.Software complexity can be easily managed.APPLICATION OF OOP:The most popular application of oops up to now, has been in the area of user interfacedesign such as windows. There are hundreds of windowing systems developed using ooptechniques.Real business systems are often much more complex and contain many more objectswith complicated attributes and methods. Oop is useful in this type of applications because itcan simplify a complex problem. The promising areas for application of oop includes.1.2.3.4.5.6.7.8.Real – Time systems.Simulation and modelingObject oriented databases.Hypertext,hypermedia and expertext.Al and expert systems.Neural networks and parallel programming.Dicision support and office automation systems.CIM / CAM / CAD system.11P.T.O

LECTURE-5Basics of C C is an object oriented programming language, C was developed by JarneyStroustrup at AT & T Bell lab, USA in early eighties. C was developed from c and simula 67language. C was early called ‘C with classes’.C Comments:C introduces a new comment symbol //(double slash). Comments start with adouble slash symbol and terminate at the end of line. A comment may start any where in the line andwhat ever follows till the end of line is ignored. Note that there is no closing symbol.The double slash comment is basically a single line comment. Multi line comments can bewritten as follows:// this is an example of// c program// thank youThe c comment symbols /* .*/ are still valid and more suitable for multi line comments./* this is an example of c program */Output Operator:The statement cout ”Hello, world” displayed the string with in quotes on the screen. The identifiercout can be used to display individual characters, strings and even numbers. It is a predefined objectthat corresponds to the standard output stream. Stream just refers to a flow of data and the standardOutput stream normally flows to the screen display. The cout object, whose properties are defined iniostream.h represents that stream. The insertion operator also called the ‘put to’ operator directsthe information on its right to the object on its left.Return Statement:In C main ( ) returns an integer type value to the operating system. Therefore every main () in C should end with a return (0) statement, otherwise a warning or an error might occur.Input Operator:The statementcin number 1;is an input statement and causes. The program to wait for the user to type in a number. The numberkeyed in is placed in the variable number1. The identifier cin is a predefined object in C thatcorresponds to the standard input stream. Here this stream represents the key board.The operator is known as get from operator. It extracts value from the keyboardand assigns it to the variable on its right.12P.T.O

Cascading Of I/O Operator:cout ”sum ” sum ”\n”;cout ”sum ” sum ”\n” ”average ” average ”\n”;cin number1 number2;Structure Of A Program :Probably the best way to start learning a programming language is by writing a program. Therefore,here is our first program:// my first program in C #include iostream using namespace std;int main (){cout "Hello World!";return 0;}Output:-Hello World!The first panel shows the source code for our first program. The second one shows the result of theprogram once compiled and executed. The way to edit and compile a program depends on thecompiler you are using. Depending on whether it has a Development Interface or not and on itsversion. Consult the compilers section and the manual or help included with your compiler if youhave doubts on how to compile a C console program.The previous program is the typical program that programmer apprentices write for the first time,and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplestprograms that can be written in C , but it already contains the fundamental components that everyC program has. We are going to look line by line at the code we have just written:// my first program in C This is a comment line. All lines beginning with two slash signs (//) are considered comments and donot have any effect on the behavior of the program. The programmer can use them to include shortexplanations or observations within the source code itself. In this case, the line is a brief descriptionof what our program is.#include iostream Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular codelines with expressions but indications for the compiler's preprocessor. In this case the directive#include iostream tells the preprocessor to include the iostream standard file. This specific file(iostream) includes the declarations of the basic standard input-output library in C , and it isincluded because its functionality is going to be used later in the program.using namespace std;All the elements of the standard C library are declared within what is called a namespace, thenamespace with the name std. So in order to access its functionality we declare with this expressionthat we will be using these entities. This line is very frequent in C programs that use the standardlibrary, and in fact it will be included in most of the source codes included in these tutorials.int main ()This line corresponds to the beginning of the definition of the main function. The main function isthe point by where all C programs start their execution, independently of its location within thesource code. It does not matter whether there are other functions with other names defined before orafter it – the instructions contained within this function's definition will always be the first ones to be13P.T.O

executed in any C program. For that same reason, it is essential that all C programs have a mainfunction.The word main is followed in the code by a pair of parentheses (()). That is because it is a functiondeclaration: In C , what differentiates a function declaration from other types of expressions arethese parentheses that follow its name. Optionally, these parentheses may enclose a list of parameterswithin them.Right after these parentheses we can find the body of the main function enclosed in braces ({}).What is contained within these braces is what the function does when it is executed.cout "Hello World!";This line is a C statement. A statement is a simple or compound expression that can actuallyproduce some effect. In fact, this statement performs the only action that generates a visible effect inour first program.cout represents the standard output stream in C , and the meaning of the entire statement is toinsert a sequence of characters (in this case the Hello World sequence of characters) into the standardoutput stream (which usually is the screen).cout is declared in the iostream standard file within the std namespace, so that's why we needed toinclude that specific file and to declare that we were going to use this specific namespace earlier inour code.Notice that the statement ends with a semicolon character (;). This character is used to mark the endof the statement and in fact it must be included at the end of all expression statements in all C programs (one of the most common syntax errors is indeed to forget to include some semicolon aftera statement).return 0;Th