Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
20 views
Object Oriented Programming in C++
C++ book
Uploaded by
santoshpandeyfsl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Object Oriented Programming in C++ For Later
Download
Save
Save Object Oriented Programming in C++ For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
20 views
Object Oriented Programming in C++
C++ book
Uploaded by
santoshpandeyfsl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Object Oriented Programming in C++ For Later
Carousel Previous
Carousel Next
Save
Save Object Oriented Programming in C++ For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 135
Search
Fullscreen
Object Oriented Programming in CH Contents 1 Thinking Object Oriented, 1 1.1 Procedure-Oriented Programming... 1.2 Object Oriented Programming Paradigm.. 1.2.1 Why OOP is Popul 13 A way of Viewing World Agent (Object)... 1.4 Computation as Simulation... 1.5 — Copying with Complexity 1.6 Abstraction Mechanism, 2 Classes and Methods 2.1 Historical Background of G++. 2.2 A simple C++ Program 23. Review of Structure. 23.1 Defining the Structure. 232 — Creating structure variable. 23.3 Accessing member of structure is 13 2.4 Basic Concept of Object-Oriented Programming ..... 25 Specifying a €lasS.e0sen 25.1 Access Specifiers (Visibility Labels) 252 Creating Objects 253. Accessing class members 254 Member Function... 2.5.5 Private Member Functidins . 25.6 Arrays within a C1a88 sensi 2.5.7 Memory Allocation for Object. 2.6 Amay of Object. . 27 Objects as Function Arguments 26 28 — Retuming object from function 2.9 Static Member of a Class 2.9.1 Static data member 2.9.2" Stati¢'member function 30 2.10 const Member function, 2.11 Feiénd function 2.12 Friend class. 2.13 Inline function. 2.14 Reference Variabl 2.15. Default argument 2.16 State and Behavior of Object 2.17 Responsibility of Object. . . _— SSObject Oriented Programming in CH 3 Message, Instance and Initialization. 38 3.1 Message Passing... 32 Constructors 3.2.1 Multiple Constructor (Constructor Overloading), 4 33 Copy Constructor 3.4 Constructors with default Argument 35 Destructors.. AT 3.6 Dynamic Initialization of Objects. 48. 3.7 Memory Mapping, Allocation and Recovery. ee tn SO 3.7.1 Stack & Heap Memory... 3.7.2 New and Delete Operator 38 Dynamic Constructor & Destructor (Dynamic Memory allocation using constructor & Destructor) 52 4 Object Inheritance and Reusability 4.1 Introduetion to inheritance... 4.2 FORMS OF INHERITANCE (SUB CLASS/SUB TYPES). 4.3. Defining Derived Class (Specifying Derived Class)... 43.1 Public Inheritance... 432 Proweted Inheritance. 58 433° Private Inheritance... 44° Type of Inheritance. 4A. Single Inheritance... 44.2 Multiple Inheritance. 61 443° Hierarchical Inheritance. 444 Multilevel Inheritance’ 4AS Hybrid Inheritance 44.6 Multipath inheritanée . 45 Virtual Base Class 46 Abstract class» 47 Casting Basé'Class Pointer to Derived Class Pointers m 48 Construétors and Destructors in inheritance suerte . casnanansonminas IS 49 ISA &HAS-A rule, 494 ISA Rule, “ 492) MAS-A Rule (Container ClassiContainership(Composition). 4.10 Composition/Container Vs Inheritance. 4.11 Pros and Cons of inheritance... 4.12 Subclass Subtype and Principle of Substitutability 81 5) Polymorphism... 3S. Introduction... 5.2. Classification of Polymorphism 5.2.1 Compile Time PolymorphismObject Oriented Programming in CH 22 Run Time Polymorphism 83 5.3 Function Overloading In C++ 54 Operator Overloading... $5 Overloading Unary and Binary Operators 86 55.1 Unary Operator Overloading, 552 Overloading Binary Operator. 56 Operator Overloading using a Friend Function 5.7 Rules for Operator Overlooding in C++ 58 Type Conversions... 58.1 Conversion from Basic to Class type. 582 Conversion from Class io Basic ype. 583 Conversion from One class type another classtype. 5.9 Virtual Function 3 5.9.1 Rules for Virual Functions 5.10 Pure Virtual Function 101 103 104 105 106 (SUL: Objet cacisniaoeminidanniaeararnsniansirnasicairsidi 5.12. This Pointer... ‘Template and generic Programming, 108 we 108 108 6.1 Generic and Templates... 6.2 Class Templates 62.1 Class template with multiple parameter... 110 63 Function Templates. 112 63.1 Function Template with multiple parameter cnn ve evnisonnneeenees UB 6 Overloading of Template Funct: ois. 13 64 Non-type Template argument. 14 65 Standard Template Library (STE). 4 65.1 Components of SFL: 115 65.2 Features OF STL none 5 sical ES 66 Exception Handling, 116 6.6.1 Babies of Extéption Handling ...nnsnsneneonnn = . armas TIG 66.2 Exception Handling Mechanism. 116 663 Exception generated by a function 118 6.64) Multiple catch statement 119 665 Catch all exception. 120 666 — Rethrowing exception... Object Oriented DesignObject Oriented Programming in C+ | Unit-1 1 Thinking Object Oriented 1.1 Procedure-Oriented Programming > Conventional Programming, using high level languages such as COBOL (Common Business Oriented Language), FORTAN (Foomula Trinslation) and C, is commonly called as procedural oriented programming (POP). > POP basically consists of writing a list of instructions (or actions) for the computer 10 follow, and organizing these instructions into groups known as function, > Due to this POP is called Function Oriented Programming or Structured Programming. > The lis of instructions oractions is represented using flowchart oralgorithms which helps to depict the flow of control from one action to another. > The technique of hierarchical decomposition has been used to specify the task to be completed for solying a problem. > A typical program structure for procedural programming is shown in the figure below. Z ea Figure 1 ‘Typical Structure of Procediire Oriented Programs > Ina multi-function program, many important data items are placed at globally. So that they may he accessed by all the functions. Each function may have its own local data. The Figure shown below shows the relationship of data and function in a procedure-oriented program. ion ‘Coat ata we eee Figure 1-2: Relationship of data and functions in procedure programming ‘Some features of procedure-oriented programming are: © Emphasis is on doing things (Algorithms). ‘© Large programs are divided into smaller programs called as functions. © Most of the functions share global data, Data move openly around the system from function t function, Functions transform data from one form to another. ‘© Complexity in handling large programs Data is undervalued In POP the focus is on development of function and flow of control, very litle importance given to the data, The {important data items are placed as global so they can be accessed to all functions. The global data can be modified by any of the function and this may result in accidental change by any functions. ‘Also such global data can be destroyed by any function. Further in large programs itis very difficult to identify what datais used by which function. In case we need to revise any such data we need to revise all the funetions that access and this may result in problems. © POP cannot model real world entities (person, place, thing, event etc.). POP is action oriented and don’t really ‘comespond to element of problem. It cannot depict the characteristics and function or entities in combined form, © Creation of new data type is difficult. Different data type like complex number s and two dimensional coordinate ‘cannot be easily represented by POP. Compiled by: = Naresh Prasad Das PagelObject Oriented Programming in C++ | Unit 1.2. Object Oriented Programming Paradigm ‘The object oriented approach is to remove some of the flows encountered in the procedure approach ‘OOP treats data as critical element ie. it doesn't allow the data to move freely around the systems, Itties the data closely with the related function there by protecting it from any accidental modification and deletion. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions, around these objects. ‘The organization of data and functions in the object-oriented programs shown in the figure: object object B yyy v [runetions| Figure 1-3: Organization of data & functions in OOP, > The data of an object can be accessed only by the function associated with that object. However, functions of one ‘object can access the function of other abjects ‘Some features of object oriented programming a1 ‘© Emphasis is on data rather than procedure, # Programs are divided into what are called 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 data structure, Data is hidden and cannot be accessed he estetiial funetions, ® Objects may communicate with each other through functions. New data and functions can be easily added whenever necessary. Follows bottom-up appiteach in program design, > So, object oriented programming jis’an approach that provides a way of modularizing programs by creating partitioned memory area for both dats ancl function that can be used as templates for creating copies of such modules ‘on demand, > Object oriented programmiag has other features also like inheritance, polymorphism, overloading, data obstruction, and encapsulation. ‘Example 1-1: Comparing Procedural Programming & Object Oriented Programming Paradigm. Problem: Write « program which implement a company, in which there are following departments: (2) Quality (2) Production (3) Marketing >If we solve the above program with the help of structured programming, we first divide the total department into Clifferent functions. Suppose we need two funetions QL and Q2 for Quality, three functions PI, P2 and P3 for production, two functions for marketing MI and M2 then the program structure look like: ‘Main Program a 2 a ~ ay Funevon a. | | Funeienaa || Functions | runeuonr2 } Fureuon ra ]/ Function wa || Fonetin M2 Compiled by: = Naresh Prasad Das Page 2Object Oriented Programming in C+ | Unit-1 > If we salve the same problem which we solved with the help of structured programing, using object oriented programming then the programming structure look like: © Difference between C and C++ cal cject ¢ cH © is a structural or procedural programming | C++ is an object orfented programming language Jonguage. “Emphasis is on procedure or Seps to solve any | Emphasis is on objects rather than procedure. problem, ‘Functions are the fundamental building blocks ‘Objects are the fundamental building blocks. TG, the data is not secured: Data is hidden and can't be accessed by extemal functions ‘Ciollews top down approach, ‘C+ follows bottom up approach ‘Cuses scanfi) and printi() function for standardinput [ C++ uses cin>> and coul<< for standard input and and output output. Variables mustibe defined at the beginning tn the function, Variables can be defined anywhere in the Function. Tn G, namespace feature is absent Ta Cr+, namespace feature is present ‘Cis middle level language, (Co is a high level language, ‘Programs are divided into modules and functions Programs are divided into classes and Functions, C doesi"t support exception handling direclly. Can be done by using some other functions ‘C= supports exception handling. Done by using ry and catch block ‘C doesn't support exception handling directly. Can be done by using some other functions, ‘C= supports exception handling. Done by using try and catch block. Feauures Tike function overloading and operator ceverloading is not present (C++ supports function overloading and operaior overloading. ‘C prograrm file is Saved with .C extension, (C++ program file is saved with CPP extension Compiled by: = Naresh Prasad Das Page 3Object Oriented Programming in C+ | Unit-1 ** Difference between POP (Procedural Oriented Programming) and OOP (Object Oriented Programming) ‘ASPECTS POP OOP Divided Info| In POP, program is divided into small parts | In OOP, prosram is divided into parts called functions called objects. Tmportance Tn POP, Importance is not given to data but fo [in OOP, Importance is given lo the data functions as well as sequence of actions to be | rather than procedures or functions done. because it works as areal world. ‘Approach POP follows Top Down approach, (OOP follows Bottom Up approach ‘Access Specifiers | POP does not have any access specifier ‘OOP has access specifiers named Public, Private, Protected. ete Data Moving | In POP, Data can move freely from function to [In OOP. objects can move and function in the system communicate with each other through ‘member functions Expansion To add new data and function in POP is not so | OOP provides an easy way to add new cas data and function Data Access | In POP, Most function uses Global data for | In OOP, data cannot move easily from sharing that can be accessed freely from function | function to function, it can be kept public to function in the system, or private so we can control the access of data Data Hiding | POP does not have any proper way for hiding [OOP provides Data Hiding so data so itis less secure. provides more security ‘Overloading | In POP, Overloading is not posible. In OOP. overloading is possible in the form of Function Overloading and Operator Overloading. Examples Example of POP are:C, VB, FORTRAN, Pascal. | Example of OOP are: C++, JAVA, VB.NET, C#.NET. 1.2.1 Why OOP is Popular > The concept of object oriented programming can directly be mapped with real life problem, Even we can say that the idea of OOP are taken fromthe teal life. Now there are two questions. > Question: How we can say that QOP conekpts are taken from real life? ‘na real life the objects are: Pen, Peneily Car, book ete. These abjects have two main thin © Structure (or attribute) 9 Behaviour (or Nature ‘Example A: For-examiple the structure of pen consists: color of pen, Length of pen, the material by using which body of pen is nade ete: The behavior of pen means the job performed by pen that is writing. ‘Example’B: Suppose the object is teacher then the structure of teacher consists: the height of teacher, Age of teacher ‘etc. The behavior of teacher consists: Teaching. Writing, Research etc. NOW ye cat’compare the real objects with object of OOP. We know that the object of OOP consists data and functions. The structure of real life object can map with data member of object of OOP and behavior can map with function. By above analysis we can say that the object concept is taken from real life object. And in real life the objects ‘communicate with each other like in object oriented programming Compiled by: = Naresh Prasad Das Page 4Object Oriented Programming in C+ | Unit-1 Suppose a teacher is teaching to student, then following objects interact with, each other Object ‘Teacher teach students by using Board (je. Black Board). Means sometimes speak and sometimes write onto Board for explaining topic. By above analysis we can say that the interaction of object in OOP is also taken fron real lie objeet interaction. So we can say that the object oriented programming concept are taken from real life object. > Question2: IF concepts are taken from meal life then what isthe benefit of that. how this inerease the popularity of oop? ‘We know that programming concepts are used for designing the program: al we Ktow that program are designed {or solving problem. Problems are real life problems, That means program are designed for real life problems so i we have a programming concept which is based on real life concept then to design program by using that concept is So we can say that designing program by OOP concept is easy, that is why OOP is more popular than other programming, concept. Compiled by: = Naresh Prasad Das Page 5Object Oriented Programming in C++ | Unit 1.3. A way of Viewing World Agent (Object) To illustrate the major ideas in object-oriented programming, let us consider how we might go about handling a real-world situation and then ask how we could make the computer more closely model the techniques employed. Suppose I wish to send, flowers to a friend who lives in a city many miles away. Let me call my friend Sally. Because of the distance, there is no possibility of my picking the flowers and carrying them to her door myself. Nevertheless, sending her the flowers is an easy ‘enough task; I merely go down to my local florist (who happens to be named Flora). tell her the variety and quantity of flowers | wish to send and give her Sally's adress, and I can be assured the flowers will be delivered expediently and automatically. Sally. —— Delivery Person Gardeners \ \ Flower Arranger ower ME — Flora \ / | ‘Wholesaler Sally's Florist Figure 1-4: The community of agents helping me Abunts and Commits In above example I solved my problem with help of agent (Object) flora to deliyer-the flower, There will be community of agents to complete a task. In above example Flora will communicate with sally's florist, sally's florist will arange flower, the arrangement of flower is hidden from me (data hiding/information hiding). An object-oriented program is structured as a community of interacting agents, called objects. Bach object has a role o play. Each object provides a service, or performs an action, that is used by other members of the community fesse and Methods Twill cal flora for delivering flower to my friend sally, After that there will be chain of message passing and actions taken by various agents to deliver the flower as show in figure above. Action is initiated in object-oriemed programming by the transmission of a message to an agent (an object) responsible for the action. The message encodes ihe request jor-an action and is accompanied by any additional information (arguments) needed to caity owt the request. The receiver is the object w whom the message is sent. Ifthe recelver accepts the message, it accepts the responsible to carry out the Indicated action. In response to a message, the recetver will perform some method to satisfy the request. 4 Message versus Procedure Calls In message passing. there's a designated receiver, and the interpretation the selection of method to execute in response fo the message may vary with different receivers. Usually, the specific receiver for any given message will not be known until run time, so the determination of which method to invoke cannot be made until then. ‘Thus, we say there is late binding between the message (function or procedure name) and the code fragment (method) used to respond to the message. This situation is contrast to the very early (compile-time or link time) binding of name 16 code fragment in conventional procedure calls, Respo Tnabove example, my request for action indicates only the desired outcome (flowers for my friend), Flora is free to pursue any technique that achieves the desired objective ie. to deliver flower to my friend and is not hampered by interference on. my part A fundamental concept in object-oriented programming is to describe behavior in terms of responsibilities, Classes and Instances In above scenario flora is florist we can use florist wo represent the category (or class) of all florist. Which means Flora is instance (object) of class florist All objects are instance ofa class. The method invoked by an object in response toa message is detennined by the class ofthe receiver, All objects ofa given class use the same method in response to similar messages Compiled by: = Naresh Prasad Das PagesObject Oriented Programming in C+ | Unit-1 Class Hierarchies Inheritance Tnabove example, Ihave more information about Flora-not necessarily because she isa florist but because she is a shopkeeper. Since the category Florist is a more specialized form of the category Shopkeeper. any knowledge I have of Shopkeepers is also true of Florists and hence of Flora, Flora isa Florist, but Florist isa specialized form of Shopkeeper. Furthermore, a Shopkeeper is alsoa Human; so know, for example, that Flora is probably bipedal. A Human is a Mammal, and a Mammal is an Animal, and an Animal is a Material Object (therefore it has mass and weight). Figure 1-5: A class hierarchy for various material objects. Classes can be organized into a hierarchical inheritance structure. A child class (or subelass) will inherit attributes from a pareni class higher in the tree. An abstract parent class isa class (suchas Mammal) for which there are no direct insiances; it is used only to create subclasses. Summary of A way of Viewing World Agent 1 14 > Everything is an object. ‘Computation is performed by objects commititigating ‘vith each other, requesting that other objects perform actions. Objects communicate by sending and reéeiving messages. A message isa request for ation bundled with whatever arguments may be necessary to complete the task: Each object has its own memory, which gonsists of other objects. Every object isan instance of a class. A class simply represents a grouping of similar objects, such as integers or lists ‘The class is the repository for behavior associated with an object. That is, all objects that are instances of the same ‘lass can perform the same actions, Classes are organized-into a singly rooted tree structure, called the inheritance hierarchy. Memory and behavior associated with instances of a class are automatically available to any class associated with a descendant in this tree structure Computation as Simulation ‘The Traditional Model In traditional view. computer is a data manager. following some pattern of instructions, wandering through memory, palling values out of various memory transforming them in some manner and pushing the results back into other memory, ‘The behavior of computer executing a program is a process-state or pigeon-hole model. By examining the values in the slots, one can determine the state of the machine or the results produced by a ‘computation, ‘This model may be a more or less accurate picture of what takes place inside a computer. Real world problem solving is difficult inthe traditional model. ‘The Object Oriented Model Never mention memory addresses, variables, assignments, or any of the conventional programming terms, Instead, we speak of objects, messages and responsibility For some action Compiled by: = Naresh Prasad Das Page 7Object Oriented Programming in C+ | Unit-1 > This model is process of cresting a host of helpers that forms a community and assists the programmer in the solution of a problem (Like in flower example). > ‘The view of programming as creuting a universe is in many ways similar to s style af computer simulation called “diserete even-criven simulation” > Ina discrete event-driven simulation the user create computer models of the various elements of the simulation, describes how they will interact with one another, and sets them moving, > Object oriented programming is also similar to event driven simulation. jpying with Complexity > At early stages of computer programming development all programs are written in assembly language'by. single individual. > Asprogram become more and mare complex, programmer have difficulties in remembering all information needed to develop and debug allsoftware. > As program become more and more complex, even best programmer can’t perform the task by himself, > ‘There will be group of programmer working together to solve complex problem ‘The Nonlinear Behavior of Complexity. > As programming projects become larger, an interesting phenomenon was observed. > A task that would be take one programmer 2 months to perform could not be accomplished by two programmer working for one month. > In Fred Brook’s memorable phrase, “the bearing of child takes nine monahs;no matter how many women are assigned to the wsk > The reason for this nonlinear behavior was complexity in particular the:interconnection between software components ‘were complicated, and large amount of information had to be communicated among various members of programming, team. > Interconnectedness means the dependence of one partion of code'bit another section of the code. ‘Time is not directly related with number of man hours: 1.6 Abstraction Mechanism ‘The abstraction is the process of getting detail infortition according to the level of deep sight to the problem. I you want to get detail information about the topic, you should go deeper to the problem, Classes use theory of abstraction and defined list of abstract properties, ‘Through the process of abstriction, programiier hides all but the relevant data about an object in arder to reduce ‘complexily and increase efficiency. In the same way that abstraction sometimes wotks in art, the objects that remains is a representation of the original, with unwanted detail omitted > The resulting object itself can be referred to as an abstraction, meaning a named entity made up of selected attributes and behavior (method) specify to particular usage of originating entity. > Abstraction is related to both encapsulation and data hiding. > Example: of adding complex number, considering three objects ¢1,c2, c3. C1 and 2 object is used to call input function, c3 is use for adding datain e1 and c2 and c3 is also used for displaying output, > Consider Laptop computer, we view laptop as single unit but really laptop consists of input units (keyboard, touchpad) ‘output unit (seréen), processor unit (processor, motherboard) storage unit (RAM, HDD) etc. v vy v et Compiled by: ~ Naresh Prasad Das PageObject Oriented Programming in C++ | Unit 2 Classes and Methods 2.1. Historical Background of C++ C++ is object oriented programming language. It was developed by Bjame Stroustrup at Bell-Laboratories, Stroustrup take the best features of simula67 and C, and designed a language which support object oriented programming features. ‘Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula6?, Since the class was a major addition tothe original C language, Stroustrup initially called the new language *C with classes". However in 1983 the name was changed to C+ The idea of C+ comes from C increment operator ++, thereby suggesting that C+ isan augmented (incremented) version of C. ‘The most important facilities that C++ adds on to C are classes, inheritance, function overloading and operator ‘overloading, These features enable creation of abstract data types, inherit properties from existing data types, and support polymorphism, therehy making C+ a truly object-oriented! language, ‘The object-oriented features in C++ allow programmers to buik large program with clarity, extensibility and éase of ‘maintenance, incorporating the spirit and efficiency of C. The addition of new features has transformed C from a language that ‘currently fucilitates top-down, sructured design, 10 one that provides bottom-up, object-oriented design. 2.2 A simple C++ Program Example 2-1: #includeciostream> include beader fle using namespace stds int main() { cout<<"Hello World”; return 0; 1 * Output Operator ‘coute< “Hello World”; > The above statement print the string Hello world on to sercen. > cout (pronounced “c out”) is a predefined object that represent the standard output stream in C+. > In above statement the operator << iicalled insertion or put to operator. It inserts the contents of the variable an its right to the cout abject. Saess =| cou |e Cw “Tiel Werle” | Object Inscrion ‘Variable perce % Input Operator cn; >The abeve statement takes a value assign thot value to n, > Same like cout, cin (pronounced “c in”) is also predefined object in C++, cin represent standard input stream, > The operator >> is known as extraction or get from operator. It extracts the value from the keyboard and assign it to variable (Revised lan }—+ > Jf ] Object ‘Extraction Variable pert Compiled by: = Naresh Prasad Das PagedObject Oriented Programming in C++ | Unit > Cascading of inpat and output operator is also possible. > If suppose we want to read the value of variable nl, n2 and n3 then we can write statement cin >> ml >> n2.>> 03; This is equivalent to cin >> m1; cin>> m2; cin >> m3; > Same we can do with output operatoralso for example suppose we want to print the value of a and b then wean write the statement like cout << as <
Directive ‘The two lines that begin the example 2.1 program are directive. The first isa preprocessor dircetive, and the second is a using directive Preprocessor Directive ‘include
> The firs line of the program might look like a program statement, but itis not, Itisn’t part of function body and doesn’t cend with a semicolon, as program statements must. Instead, it starts with a number sign (#) > The program statement are instruction to the computer to do something, such as adding two numbers or printing a sentence. A preprocessor directive, on the other band, is an instruction to the compiler. A part of the compiler called the preprocessor deals with thew directive before 4 begins the real compilation process. > The preprocessor directive #include tells the conipiler ta insert another file into your source file. In effect, the #inelude directive is replaced by the contents of the file indicated > The#inelude is only one of many preprocessor directives, all of which can be identified by the initial # sign. > ostream is an example of header file (sometimes called an include file). It’s concerned with basic input/output, ‘operations, and contains declarations that are needed by the cout identifier and the << operator. Without these declarations, the compiler won"t recognize cout and will think << is being used incomecily. > There are many such include files. The newer standard C+ header files don’t have a file extension, but some older header files, let over froin the days of the C language, have the extension .h. > We can add more tharrone header file in the program, if necessary. ‘The using Directive > A C++ progtam can be divided into different namespaces. A namespaces is a part of the program in which certain names are recognized, outside of the namespaces they are unknown, > Thedirective using namespace std; Says that the program statements that follow are within the sid namespace. Various program component such as cout are declared within this namespace. If we didn't use the using directive, we would need to add the std name to many program ‘elements. For example, the program of example 2.1 we'd need to say std::cout << “Hello World; > To avoid adding std:: dozens of time in program we use the using directive instead. SS Compiled by: ~ Naresh Prasad Das Page 10,Object Oriented Programming in C+ | Unit-2 Following Program read two number and then print the sum of these two. #includeciostream> #includecconio.h> using namespace std, int main { intab. ‘coute<" Enter First number:": ‘coute<"Enter Second number:"; ibs a4; coute<"The sum of two numbers are:"<
#include
using namespace std int main { float fparts intipars coute< Enter a floating point number:" ‘anp>it ipart=n; fpart=n-ipart; ccoute<"The integer part of number is ‘coute<"The fractional part of number is:"
> > 2.341 2.32 A sinucture is a collection of simple variable, The variable in s structure can be of different types: Some can be int, some can be float, and so on, ‘The data item of structure is called member of the structure. ‘The difference between array and structure is the element ofan array has the same type while the element of structure can be of different type. For C++ programmers, structures are one of the two important building blocks in the understanding of objects and classes. In fact, the syntax of a structure is almost identical to that of a class. The only difference being that in a class, all members are private by default. But in a C-++ structure, all members are public by default. In C, there isno concept ‘of public or private. So by learning about structures we'll be paving the way for an understanding of classes and objects. Defining the Structure ‘The structure definition tells how the structure is organized: It specifies what member the structure will have ‘Syntax: struct tag_name ( data_type variablel; data_type variablel; of ‘The keyword struct introduces the structure definition. Next comtiés the structure name or tag. The declaration of the structure members are enclosed in braces. A semicolon follows the closing brace, terminating the entire structure. Example: struct student t char name[ SO}; int roll; char branch[20]; Creating structure variable We can also create structure variable at the time struct student f char name[50]; int roll; ‘char branch{20}; Js1.82835 ‘We can create structure variable like following also > Structure declaration’ struct student t char name[50]; int roll; ‘char branch{20); h > Structure variable creation: student s1,s2,s35, ‘Note: One of the aims of C+ isto make the syntax and operation of user-defined data types as similar as possible to that of builtin datatypes. In C we need to inclide the keyword struet in structure type variable creation asin struct student s1.s2,s33. In C++ the keyword is not necessary. Compiled by: = Naresh Prasad Das Pege 12Object Oriented Programming in C+ | Unit-2 233° Accessing member af structine ‘Any member of a structure can be accessed as Structure_variable name. member_name > ‘The structure member is written in three parts: the name of the structure variable, the dot operator which consisit of a period (.), and the member name. > Forexample: sl.roll = 32 Example 2-4: includeciostream> includecconio.h> using namespace std struct student i cchar name{50} int roll char branch[20]; } int main) t students coute<" Enter name af student cin.get(s.name.50); cout<<" Enter Roll number of student.” cin>>sroll; cout<<" Enter branch of student: cin>>s.branch; cout<<" Entered Information: "cena coute<"Name!"
Inject oriented programming data and functions are organized in one entity > tis necessary to understand some of the concepts used extensively in object-oriented programming, These include # Objects and Classes Method Encapsulation Data abstraction Inheritance Polymorphism Dynamic binding * Message passing + Objects and Classes > Classes is an entity in which data and functions (which operate these data) are organized. > Object isa class variable, When a program is executed, the object interaet by sending messages to Oe another. > Object are the basic run-time entities in an object-oriented system. They may represent a person, a place, a table of data or any item that the program has to handle. > Programming problem is analyzed in terms of objects and the nature of communication between them, > Program objects should be chosen such that they match closely with the real-world objects. > ‘The entire set of data and code of an object can be made a user-defined dita with the help of a classes. > Once a class has been defined, we can create any number of abjects belonging to that class. > A classis thus a collection of objects of similar type. For example; mango, apple and orange are members of the class fruit yest obec Dutt best pent Date tember orekysct x A objens > fobject3 Wants to acess function! then that access throws the object > The data and function inside a classes are known as member of that class, + Method > An operation required for an object or entity when coded in a class is called method > The operation required for an object is defined ina c > Functions of elass is refemed as methods ar member functions. > Usually data members are declared private and methods as public in a clas. Encapsulation > ‘The wrapping up of data and functions into a single unit (called class) is known as encapsulation. > Data encapsulation is the most stiking features of a class. The data is not accessible to the outside of class, Only the function which are inside the class can access the data > The insulation of the data from direct access by the program is called data hiling or information hiding. Compiled by: = Naresh Prasad Das Poge 14Object Oriented Programming in C++ | Unit-2 +» Data abstraction > Abstraction refers to the act of representing essential features without including the background details or explanations. > Class use the concept of abstraction and are defined as a list of abstract data and functions to operate on these data > Classes encapsulate all the essential properties of the object that are to be created. > Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT). Inheritance > Inheritance is the process by which objects of one class acquire the properties of objects of another class > Inheritance is a method by using which we can create a new class by extending and enhancing existing dass. The existing class is called the base class and the new class is ealled derived class. > Inheritance is very powerful features of oop. > For example we have a class X which has following member: two functions F] and F2 and three data di, @2 and d3, Classx Suppose after sometimes we want to add one function, F3 and data d4 in that class X. We can do this by designing the ‘class again but the main drawback of this is we have again to check the class X (test & debug), But in oop with the help of inheritance we can do this, Drive a new clas®-¥ from the base class X. In clays ¥ add only function F3 and data d4, because the class Y is inherited from the ¢fass X, Therefore the member of class X are automatically copied into clas. a] Le) + =] m Lm] Le) can clus ¥ pase cas) @aived cis) If we create an object of class Y then in that object the member are dl, €2, d3, d4, FI, F2 and F3. But if we create an ‘object of class X, in that object the member are d1, ¢3, €3, FI and F2. That means the base member are transformed {nto defived class but notin reverse order. ‘morphism > Polymorphism, a Greek term, means the ability to take more than one form, > Using function in different ways, depending on what they are operating on is called the polymorphism. i.e. one thing with several distinct forms. > For example suppose we are writing a program, which calculates the area of circle, area of triangle, area of rectangle. With the help of polymorphism we can give same name area to all the area functions. In other words function ‘overloading is called polymorphism. > Wecan overload the operator also that is known as operator overloading for example + operator is used to add, numeric ata (int oF load, If we use Sune + operator for adding two objects, then this is known as operator overloading, Compiled by: = Naresh Prasad Das Pege 15Object Oriented Programming in C++ | Unit + Dynamic binding >” Dynamic binding refers to linking a procedure call to the code that will be executed only at run time, > The code associated with the procedure is not known until the program is executed, which is also known as late binding. + Message Passing > An object-oriented program comists of a set of objects that communicate with each other. The process of programming in an object-oriented language, therefore, involves the following basic steps: (© Creating clases that define objects and their behavior. (© Creating objects from class definitions, and © Establishing communication among objects. > A message for an object is a request for execution of a procedure, and therefore will invoke a function (piocedure) in the receiving object that generates the desired result > Message passing involves specifying the name of the object, the name of the function (message) and thé information to be sent. > Example: soplajesalay(namy objet tommin message > Objects have a life cycle. They can be created and destroyed. Comnunigation with an object is feasible as long as itis, alive. 2.5. Specitying a class > A class is a way to bind the data and its associated furictions together. It allows the data (and function) to be hidden, if necessary, from external use. > When defining a class we are creating a new abstract datatype that can be treated like any other built-in datatype. > The data inside the class are called member data and the functions are called member function. > ‘The binding of data and functions togethét into a single class type variable is called encapsulation, which is one of the benefit of object-oriented programming, > The general form of declaring class is: lass class_name t _access-specifier]: member_datal; ‘member_data2s member_function!; access-specifier2: member_datal; member_functionl; member_data; In above declaration, class is keyword. class_name is any identifier name. The number of member data and member function depends on the requirements. An object is an instance of a class i, variable of a class. The general form of declaring an object is lass_name object_name; Compiled by: = Naresh Prasad Das Pege 16Object Oriented Programming in C++ | Unit OR lass class_name variable_declaration: function_dectaration; variable_declaration: function_dectaration; h ‘The class declaration is similar to a struct declaration. The keyword class specifies that what follows is an abstract data of type class_name. The body of a class is enclosed within braces and terminated by a semicolon, The class body contains the
Finelude
using namespace std; ‘class stulent { private: ‘char name{50);, int age: int roll; public: void getdataQ) i oute<"Enter names"; coutce"Enter age:”; cins>aget coute<*Enter roll:"; cin>>rolls 1 Void showdata() ( coutc<*Name:"
Theaccess specifier tells about the visibility of member. > The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body. The keywords public, private, and protected are called access specifiers. > A class can have multiple public, protected, or private labeled sections. Bach section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private. > Access specifier are followed by colon & Public > The members defined in public section can be accessed anywhere from the program. This allows the/tlass to expose its data members and member function to other funetions and objects. > When this publie access specifier is used all the details ofthe data member and! member function are visible to other class. > Usually data members(ie. variables} are not declared in this section > I'data members are declared in this section, Data hiding rule is violated in oop. ** Private > A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members. ‘Thisallows a class o hide its member variables and member functions Froniather élass objects and functions, Usually data member are declared in this section. If member function is declared in private other public function should €all that member function. vy * Protected > A protected member variable or function is very similar t a privitte member but it provided one additional benefit that they can be accessed in child classes which are called derived classes. 2.5.2. Creating Objects > A typical class declaration would look like: class item ( int number: ‘hvariable declaration float cost; ‘private by default public: Void getdata(inta, float b); ‘Munction declaration using prototype Void showdata 0); h > Remember that the declaration of item as shown above does not define any objects of item but only specifies what they will contain. Once # class has been declared, we can create variables of that type by using the class name, > For example item p; Mtmemory for p is created ‘create & variable p of type item, In C++, the class variables are known as objects, Therefore, p is called an object of type item, We may also declare more than one object in one statement. Example item par: > Object can also be created when a class is defined by placing their names immediately alter the closing brace, as we do in the case of structure > For Example lass item Jp. ‘Would create the objects p. q and r of type item, SS Compiled by: ~ Naresh Prasad Das Page 18
You might also like
Programming in C++ For BCA BIT BE PDF
PDF
No ratings yet
Programming in C++ For BCA BIT BE PDF
129 pages
Programming in C++ For BCA BIT BE
PDF
No ratings yet
Programming in C++ For BCA BIT BE
0 pages
Programming in C++ For BCA BIT BE
PDF
No ratings yet
Programming in C++ For BCA BIT BE
129 pages
OOP Handwritten Book
PDF
No ratings yet
OOP Handwritten Book
93 pages
CH 1 C++
PDF
No ratings yet
CH 1 C++
22 pages
C++ Notes
PDF
No ratings yet
C++ Notes
370 pages
OOP in C++ Full Theory Notes
PDF
No ratings yet
OOP in C++ Full Theory Notes
93 pages
basics of oops
PDF
No ratings yet
basics of oops
8 pages
C++ Infosystems 1
PDF
100% (1)
C++ Infosystems 1
232 pages
Document 15
PDF
No ratings yet
Document 15
84 pages
Oops Notes PDF
PDF
No ratings yet
Oops Notes PDF
93 pages
Data
PDF
No ratings yet
Data
93 pages
C++ Final Material
PDF
No ratings yet
C++ Final Material
221 pages
Introduction To C++ and Object Oriented Concepts: Mrs. Deepashree Mehendale
PDF
No ratings yet
Introduction To C++ and Object Oriented Concepts: Mrs. Deepashree Mehendale
274 pages
Programming in C and C++ - Unit IV
PDF
No ratings yet
Programming in C and C++ - Unit IV
49 pages
chap 1 oopnotes
PDF
No ratings yet
chap 1 oopnotes
19 pages
021623000780.pdf
PDF
No ratings yet
021623000780.pdf
45 pages
CPP-Unit 1-A4
PDF
No ratings yet
CPP-Unit 1-A4
7 pages
Oops
PDF
No ratings yet
Oops
39 pages
OOPs With C--_CSE 2001_ Unit 1.Pptx
PDF
No ratings yet
OOPs With C--_CSE 2001_ Unit 1.Pptx
104 pages
Oops Notes
PDF
No ratings yet
Oops Notes
162 pages
Introduction To Object Oriented Programming: UNIT-1
PDF
No ratings yet
Introduction To Object Oriented Programming: UNIT-1
30 pages
20CS6205C Fund. of JAVA Programming UNIT-I (1)
PDF
No ratings yet
20CS6205C Fund. of JAVA Programming UNIT-I (1)
70 pages
Unit1-OOPs
PDF
No ratings yet
Unit1-OOPs
92 pages
285 - OOPS Lecture Notes Complete
PDF
No ratings yet
285 - OOPS Lecture Notes Complete
305 pages
Lecture 1 - SWE 234 - Progaramming II
PDF
No ratings yet
Lecture 1 - SWE 234 - Progaramming II
14 pages
BCA C++ Unit 1 A
PDF
No ratings yet
BCA C++ Unit 1 A
51 pages
Objected Oriented Programming With C++: (India) Private Limited, New Delhi
PDF
No ratings yet
Objected Oriented Programming With C++: (India) Private Limited, New Delhi
65 pages
Procedure Oriented Programming Language
PDF
No ratings yet
Procedure Oriented Programming Language
273 pages
Oops Notes Final
PDF
No ratings yet
Oops Notes Final
120 pages
CPP Unit 1
PDF
No ratings yet
CPP Unit 1
73 pages
Unit-1 OOPM
PDF
No ratings yet
Unit-1 OOPM
47 pages
l1a Intro to Oop
PDF
No ratings yet
l1a Intro to Oop
3 pages
C Programming Language & C++ Programming Language All Topics Covered.: Programming in C & C++ For Begineers and Advanced Level
PDF
No ratings yet
C Programming Language & C++ Programming Language All Topics Covered.: Programming in C & C++ For Begineers and Advanced Level
90 pages
OOP notes
PDF
No ratings yet
OOP notes
79 pages
OOPS Note Lect-1 To 7
PDF
No ratings yet
OOPS Note Lect-1 To 7
26 pages
class notes
PDF
No ratings yet
class notes
54 pages
C++ Module-1 Notes K
PDF
No ratings yet
C++ Module-1 Notes K
40 pages
unit-1-new-cpp
PDF
No ratings yet
unit-1-new-cpp
35 pages
PPT Lecture 1.1
PDF
No ratings yet
PPT Lecture 1.1
12 pages
Oops BS - 240406 - 101940
PDF
No ratings yet
Oops BS - 240406 - 101940
90 pages
Unit 1 C++
PDF
No ratings yet
Unit 1 C++
19 pages
Lecture 1 - Introduction To Oop
PDF
No ratings yet
Lecture 1 - Introduction To Oop
22 pages
LECTURE 1 - Inroduction To OOPs
PDF
100% (1)
LECTURE 1 - Inroduction To OOPs
22 pages
OOP1.1 and 1.2
PDF
No ratings yet
OOP1.1 and 1.2
21 pages
by Muskan-1
PDF
No ratings yet
by Muskan-1
30 pages
Introduction To Object Oriented Programming1
PDF
No ratings yet
Introduction To Object Oriented Programming1
215 pages
oops1
PDF
No ratings yet
oops1
62 pages
Intro To OOP
PDF
No ratings yet
Intro To OOP
24 pages
Bca3rd Sem Unit 1 TO 4 C++
PDF
No ratings yet
Bca3rd Sem Unit 1 TO 4 C++
312 pages
Object Oriented Programming With C++
PDF
No ratings yet
Object Oriented Programming With C++
159 pages
Introduction To Programming (C++) Introduction To Object Oriented Programming (OOP)
PDF
No ratings yet
Introduction To Programming (C++) Introduction To Object Oriented Programming (OOP)
12 pages
C++_Chapter1
PDF
No ratings yet
C++_Chapter1
7 pages
C++ notes
PDF
No ratings yet
C++ notes
101 pages
01 What Is OOP
PDF
No ratings yet
01 What Is OOP
19 pages
Unit 1
PDF
No ratings yet
Unit 1
143 pages
Chapter 1 - Principal of Object Oriented Programming
PDF
No ratings yet
Chapter 1 - Principal of Object Oriented Programming
15 pages
C++ Notes
PDF
No ratings yet
C++ Notes
182 pages
Most Asked Must-Know String + Array_11
PDF
No ratings yet
Most Asked Must-Know String + Array_11
1 page
Most Asked Must-Know String + Array_1
PDF
No ratings yet
Most Asked Must-Know String + Array_1
1 page
Most Asked Must-Know String + Array_41
PDF
No ratings yet
Most Asked Must-Know String + Array_41
1 page
AssemblyLanguageARM
PDF
No ratings yet
AssemblyLanguageARM
188 pages
Hello_4
PDF
No ratings yet
Hello_4
1 page
Layer1Phy
PDF
No ratings yet
Layer1Phy
1 page
CyclicPrefix
PDF
No ratings yet
CyclicPrefix
1 page
Python Book by Example
PDF
No ratings yet
Python Book by Example
90 pages
Python Book by Example
PDF
No ratings yet
Python Book by Example
90 pages