Object Oriented Programming using C

++
UNIT-1

Applications of OOP
• OOP has been in the area of user interface design such as windows. • Real-business systems are often much more complex and contain many more objects with complicated attributes and methods. • OOP is useful in these types of applications because it can simplify a complex problem. • The promising areas for application of OOP include: • Real-time systems • Simulation and modeling • Object-oriented databases • Hypertext, hypermedia and expert text • AI and expert systems • Neural networks and parallel programming • Decision support and office automation systems

Scope of C++
• C++ has a vast area of application like in Software Engineering, Computer Graphics, Application programming in C++ is associated with everything you can associate with computers. Areas where C++ is used:  Device drivers  Graphics  Photoshop  Operating Systems and component in windows XP and other OS components.  Compilers  chip design  Chip manufacturing  Semiconductor tools

 Software for e-commerce.  Customer service software such as electronic ticketing, car and flight reservations, etc.  Telecommunication services.  Real time control applications.  2-D and 3-D animations and games.  Multiprocessor multimedia software.  Portable set up box and digital TV software.  CAD software.  Software for medical instruments and systems.  Java virtual machine (JVM).  Telephones services.  Mobile phones billing systems and other infrastructural facilities.  Irrigation control systems.  Speech recognition and dictation systems.

Why Do We Need Object-Oriented Programming? • Object-Oriented Programming was developed because limitations were discovered in earlier approaches to programming. • Procedural Languages • Some characteristics exhibited by procedure-oriented programming are: • Emphasis is on doing things (algorithms) • Large programs are divided into smaller programs known as functions. • Functions transform data from one form to another. . • Data move openly around the system from function to function. • Employs top-down approach in program design. • Most of the functions share global data.

Such a unit is called an object. . typically provide the only way to access its data. you call a member function in the object. The data is hidden. Data and its functions are said to be encapsulated into a single entity. so it is safe from accidental alteration. “ • An object’s functions. • If you want to read a data item in an object. • You can’t access the data directly. called member functions in C++. • It will access the data and return the value to you.Object-Oriented Programming Paradigm • “The fundamental idea behind object-oriented languages is to combine into a single unit both data and the functions that operate on that data.

Object Oriented Paradigm .

• • • • • • • • Some of the striking features of object-oriented programming are: Emphasis is on data rather than procedure. Functions that operate on the data of an object are tied together in the data structure. Follows bottom-up approach in program design. Data is hidden and cannot be accessed by external functions. New data and functions can be easily added whenever necessary. Objects may communicate with each other through functions. . Data structures are designed such that they characterize the objects. Programs are divided into that are known as objects.

Characteristics of Object-Oriented Programming Languages • • • • • • • Objects Classes Data abstraction and encapsulation Inheritance Polymorphism Dynamic binding Message passing .

a bank account. time and lists. 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. . • They may represent a person. • They may also represent user-defined data such as vectors. a place.Objects • Objects are the basic run-time entities in an object-oriented system.

Examples of objects .

.Classes • Wrapping up of data and functions into a single unit is called class.

• The data is not accessible to the outside world. • These functions provide the interface between the object's data and the program. • Data encapsulation is the most striking feature of a class.Encapsulation • The wrapping up of data and functions into a single unit (called class) is known as encapsulation. and only those functions which are wrapped in the class can access it. . • This insulation of the data from direct access by the program is called data hiding or information hiding.

• Classes use the concept of abstraction and are defined as a list of abstract attributes such as size.Abstraction • Abstraction refers to the act of representing essential features without including the background details or explanations. and functions to operate on these attributes. weight and cost. • The main idea behind data abstraction is to give a clear separation between properties of data type and the associated implementation details. • They encapsulate the essential properties of the objects that are to be created. .

• For example. and closed is the part of class figure.Inheritance • Inheritance is the process by which objects of one class acquire the properties of objects of another class. • It supports the concept of hierarchical classification. . figure ‘rectangle’ is a part of the class polygon which is again a part of the class closed. • The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived.

Example of inheritance .

then the operation would produce a third string by concatenation. means the ability to take more than one form. • Compile time polymorphism (Also called as static binding/ function overloading) and • Run time polymorphism. For two numbers. • If the operands are strings. • An operation may exhibit different behaviors in different instances. consider the operation of addition. a Greek term.Polymorphism • Polymorphism. • The process of making an operator to exhibit different behaviors in different instances is known as operator overloading.) . the operation will generate a sum. The behavior depends upon the types of data used in the operation. • For example. (Also called as Runtime binding/ operator overloading.

Polymorphism .

• It is associated with polymorphism and inheritance. • A function call associated with a polymorphic reference depends on the dynamic type of that reference.Dynamic Binding • Binding refers to the linking of a procedure call to the code to be executed in response to the call. • Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. .

. involves the following basic steps: 1. Creating classes that define objects and their behavior. • The process of programming in an object-oriented language. • The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. the name of the function (message) and the information to be sent. • A message for an object is a request for execution of a procedure. and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Creating objects from class definitions. • Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. • Message passing involves specifying the name of the object. 2.Message Passing • An object-oriented program consists of a set of objects that communicate with each other. therefore. and establishing communication among objects.

• We can build programs from the standard working modules that communicate with one another rather than having to start writing the code from scratch. • It is possible to map objects in the problem domain to those in the program. we can eliminate redundant code and extend the use of existing classes.Benefits of OOP • Through inheritance. . • Software complexity can be easily managed. • It is possible to have multiple instances of an object to co-exist without any interference. • It is easy to partition the work in a project based on objects. • Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler. • The data-centered design approach enables us to capture more details of a model in implementable form. • Object-oriented systems can be easily upgraded from small to large systems. • The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.

function overloading. • The most important facilities that C++ adds on to C are classes. thereby making C++ a truly object-oriented language. thereby suggesting that C++ is an augmented (incremented) version of C. • However. Stroustrup initially called the new language with classes'. and operator overloading.What is C++? • C++ is an object-oriented programming language. inherit properties from existing data types and support polymorphism. class was a major addition to the original C language. • These features enable creating of abstract data types. • The idea of C++ comes from the C increment operator ++. inheritance. . • C++ is an extension of C with a major addition of the class. • It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in the early 1980's. later in 1983 the name was changed to C++.

2. This approach enables the programmer to separate the abstract specification of the interface from the implementation details (member function definition). Include Files Class declaration Member functions definitions Main function program . The class declarations are placed in a header file and the definitions of member functions go into another file. the main program that uses the class is places in a third file which “includes: the previous two files as well as any other file required. It is a common practice to organize a program into three separate files. C++ program would contain four sections. 3. 4. Finally. This section may be placed in separate code files and then compiled independently or jointly.Structure of C++ Program • • • • • • 1.

PROGRAM DEVELOPMENT IN C++ .

• Function is a collection of declarations and statements.FUNCTIONS INTRODUCTION • Functions are the building blocks of C++ programs where all the program activity occurs. .

The functions code is stored in only one place in memory.Need for a Function • Monolethic program (a large single list of instructions) becomes difficult to understand. //clears the screen disp(). //freeze the monitor } //function definition void disp() { cout<<”Welcome to the GJU of S&T\n”. cout<<”Programming is nothing but logic implementation”.h> include<conio. even though it may be executed as many times as a user needs. //function call getch(). For this reason functions are used. A function has a clearly defined objective (purpose) and a clearly defined interface with other functions in the program.h> void main() { void disp(). //function prototype clrscr(). Reduction in program size is another reason for using functions. } • . The following program illustrates the use of a function : //to display general message using function #include<iostream.

and the return value is treated correctly. T • he prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. the compiler uses the template to ensure that proper arguments are passed. a template is always used when declaring and defining a function. • With function prototyping. When a function is called.Function Prototyping • Function prototyping is one of the major improvements added to C++ functions. • Any violation in matching the arguments or the return types will be caught by the compiler at the time of compilation itself . .

cout<<”value of addition is:”<<c } void main() { Cout<<”you want addition of two numbers:” Fun1(). b. cout<<”enter value of a and b”. c . c=a+b. • So in the function definition we have to take the variable as input and also display the result in the called function. because the function will never returns a value.h> Void fun1() { int a. #include<iostream.Types of functions • Function without argument and no return value: • in this case the calling function will not have a value in its argument list as well as the return type of the called function will be void. } . cin>>a>>b.

Function with argument and no return value: • In this case the calling function must have the arguments and the called function receive the values or references but returns no value to the calling function. .

cout<<”\nRate of interest:”. //local variables void calculate (float.e. i. cout<<”\nPrincipal:”.Call by Value • In this method the values of the actual parameters (appearing in the function call) are copied into the formal parameters (appearing in the function definition). The following program illustrates this concept : #include<iostream. cout<<”\nTime period (in yeaers) :”. rate. cin>>time.h> //for pow()function void main() { Float principal. float). cout<<”\nEnter the following values:\n”. float.h> #include<conio.. //function call getch (). cin>>principal. } . //function prototype clrscr(). cin>>rate.h> #include<math. rate. the function creates its own copy of argument values and operates on them. time). Calculate (principal. time.

Cout<<”\nCompound interest is : “<<interest. //local variable Interest = p* (pow((1+r/100.0). } . float t) { Float interest. float r.//function definition calculate() Void calculate (float p.t))-p.

a reference to the actual arguments(s) in the calling program is passed (only variables). • Any change in the original data in the called function gets reflected back to the calling function.for the variable.. the same variable’s value can be used by two different names : the original name and the alias name.Call by Reference: • A reference provides an alias . It is useful when you want to change the original variables in the calling function by the called function. i.e.an alternate name . • So the called function does not create its own copy of original value(s) but works with the original value(s) with different name. • In call by reference method. .

h> #include<conio. int &). //function prototype cin>>num1>>num2.num2). b=temp. getch().h> void main() { clrscr(). //function call cout<<”\n\nAfter swapping : \Num1: “<<num1. } . a=b.num2. void swap (int &. cout<<endl<<”num2: “<<num2. } //function fefinition swap() void swap (int & a.//Swapping of two numbers using function call by reference #include<iostream. cout<<”\nBefore swapping:\nNum1: “<<num1. int & b) { int temp=a. int num1. swap(num1. cout<<endl<<”num2: “<<num2.

In case of C. In case of C++. each step is processed into detail while in C++. We can use functions inside structures in C++ but not in C. the program is formulated step by step. the data is not secured while the data is secured (hidden) in C++. In case of C. C is function-driven while C++ is object-driven. This difference is due to specific OOP features like Data Hiding which are not present in C. C++ supports function overloading while C does not. • • • • . • In case of C.Difference between C and C++ • C follows the procedural programming paradigm while C++ is a multi-paradigm language (procedural as well as object oriented). functions can be used inside a structure while structures cannot contain functions in C. Overloading means two functions having the same name in the same program. the base elements are first formulated which then are linked together to give rise to larger systems. importance is given to the steps or procedure of the program while C++ focuses on the data rather than the process. This can be done only in C++ with the help of Polymorphism(an OOP feature). C uses the top-down approach while C++ uses the bottom-up approach. Functions are the building blocks of a C program while objects are building blocks of a C++ program.

/* C version */In C++. local variables can be declared anywhere. For example if a function f1( ) takes no parameters (and returns a char). The universities are two different namespace & hence contain the same roll number(identifier) but the same university(one namespace) cannot have two students with the same roll number(identifier) . The use of void in C++ Is not illegal. the void is optional. its prototype has the word void inside its function parameter list. local variables can be declared close to where they are first use to prevent unwanted side effects. We cannot use these variables in C programming. • The NAMESPACE feature in C++ is absent in case of C. Thus. • in C. C++ uses NAMESPACE which avoid name collisions. Reference variables allow two variable names to point to the same memory location. In C++. //C++ version this means that the function has no parameters.• C++ allows the use of reference variables while C does not. local variables can be declared only at the start of a block. Remember these two declarations are equivalent. Therefore the prototype for f1( ) is usually written as: char f1( ). two students enrolled in the same university cannot have the same roll number while two students in different universities might have the same roll number. • In C. it is just redundant. when a function takes no parameters. its prototype will look like this: char f1(void). For instance. prior to any ‘action’ statement.

a sequence of bytes that represent memory content. • The standard input and output stream objects of C++ are declared in the header file iostream.Stream • A stream is the source or destination of a series of data. or in the case of binary files. either characters. .

. in this case: cin stream. which is an object. the variable prog is declared as an integer type variable. cin >> prog. int prog. • In the example above. For inputting. • Syntax for using the standard input stream is cin followed by the operator >> followed by the variable that stores the data extracted from the stream. the device used for input is the keyboard. >>. • The next statement is the cin statement. the keyword cin is used. is used on the standard input stream. • The operator of extraction. The cin statement waits for input from the user’s keyboard that is then stored in the integer variable prog.Input Stream • Generally.

• Output on the standard stream is performed using the cout object. disk. • Variables can be of any basic data type. • The syntax for the standard output stream operation is as follows: cout << variable. called the insertion or put-to operator. etc. .Output Streams • The output streams allow to perform write operations on output devices such as screen. • C++ uses the bit-wise left-shift operator for performing console output operation. • The word cout is followed by the symbol <<. and then with the items (variables/constants/expressions) that are to be output.

a specified amount of memory is set aside at compile time.  delete operator for dynamic memory deallocation .  new operator for dynamic memory allocation.Runtime Memory Management • Whenever an array is defined. the memory allocation can be performed during execution. If a situation arise in which the amount of memory required is unknown at compile time. which may not utilized fully or may not be sufficient. Such a technique of allocation memory during run time on demand is known as dynamic memory allocation.

The following statement allocates 21 bytes of memory and assigns the starting address to cptr : char * cptr. //size must be specified • • • • • • • . The above statements allocate 1 byte and assigns the address to cptr. For example. Where the data type is any allowed C++ data type and the pointer_variable is a pointer of the same data type. Allocate memory as and when required new operator helps in this context. Where value is the value to be stored in the newly allocated memory space and it must also be of the type of specified data_type. the pointer support dynamic memory allocation (allocation of memory during runtime). The syntax of the new operator is given below : pinter_variable = new data_type. We can also allocate and initialize the memory in the following way : Pointer_variable = new data_type (value).new Operator • • • • • • In C++. cptr = new char [21]. char * cptr cptr = new char. For example. Int *empno = new int [size].

• delete cptr. //some versions of C++ may require size . The syntax of delete operator is : • delete_pointer_variable. • For example. • delete [ ] empno.Delete Operator • It is used to release or deallocate memory.

i++) cin >> k[i]. • for (int n = 0 . for (int i =0. k = new int[5].m++) cin >> ch[m]. ch = new char[6] .• • • • • • • • • • • • • #include <iostream. cout<< “Enter 5 integers : ” .h> int main() { int* k . So ch[m] // represents element at index value m • cout<< “Address of k = ” << k <<endl. n++) • cout << k[n]<<“ ”. // ch is similar to name of array. // user input of array elements char *ch . // here k is similar to name of array . m<6. n<5.i<5. for (int m = 0 . cout<<“Enter a name of 6 characters: ”.

} . j++) cout << ch[j]<<“” . // for output of array elements cout<<“\n”. //notice the code for deletion of new array delete []ch. delete []k. j<6. for (int j = 0 .cout<<“\n”. return 0.

Sign up to vote on this title
UsefulNot useful