Вы находитесь на странице: 1из 18

Chapter: 2 Principles of Object Oriented Programming

Procedure-oriented programming: A program in procedure language is a list of instructions. In the procedure-oriented approach, the problem is viewed as a sequence of things to be done such, as reading, calculating, and writing are known as procedure-oriented programming. A number of functions have written to perform/accomplish these tasks. Here the primary focuses on functions/tasks/actions. COBOL, FORTRAN and C are the example of procedure-oriented language. A typical program structure for procedure programming is shown in figure below: Main program F1 F2 F3

F4

F5

F6

F7

F8

Procedure-oriented programming basically consists of writing a list of instructions (or actions) for computer to follow, and organizing these instructions into groups known as functions. Drawbacks of POP: (1) In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we also need to revise all functions that access the data. This provides an opportunity for bugs to creep in. (2) Another serious drawback with the procedure approach is that it does not model real world problems very well. This is because functions are action-oriented and do not really correspond to the elements of the problem. Characteristics of POP: (1) Emphasis (focus) is on doing things (algorithm). (2) Large programs are divided into smaller programs known as functions. (3) Most of the functions share global data. (4) Data move openly around the system from functions to function. (5) Functions transform data from one form to another. (6) It follows (employs) top-down approach in program design. Object-Oriented Programming: The invention of object-oriented approach is to remove some of the problem encountered in the procedure approach. OOPs treats data as critical element in the program development and do not allow it to flow freely around the system. OOPs allow decomposition Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

of a problem into a number of entities called objects. The organization of data and functions in OOPs is shown in figure bellow: Object A Data Functions Data Functions Object C [Organization of data and functions in oop] The data of an object can be accessed only by the functions associated with that object. However functions of one object can access the functions of other objects. Characteristics of OOPs: (1) Emphasis on data rather than procedure. (2) Programs are divided into a number of entities are known as objects. (3) Functions that operate on the data of an object are tied together in the data structure. (4) Data is hidden and cannot be accessed by external functions. (5) Objects may communicate with each other through functions. (6) New data and functions can be easily added whenever necessary. (7) Follows bottom-up approach in program design. Basic concept of object-oriented programming: Some of the basic concepts used in OOPs are: (1) Objects (2) Classes (3) Data abstraction and encapsulation (5) Polymorphism (6) Dynamic Binding (7) Message Passing

Object B Data Functions

(4) Inheritance

(1) Objects: In object-oriented system they are treated as basic run-time entities. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. They may also represent user-defined data such as vectors, time and lists. Object contains data and functions that operate on that data. In other words we can say that objects contains data and code to manipulate that data. Objects are variable of type class. In object, functions are known as member function (in c++) whereas in some language known as method (i.e. in VB, Smalltalk). In object, data are known as data member or

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

attributes (or properties (in VB)) of an object. An object is said to be an instance of a class. (2) Classes: A class is a collection of objects of similar type. e.g. mango, apple and orange is member of the class fruit. It specifies what data and what functions will be included in object of that class. Classes are user-defined data types and behave like the built-in types of a programming language. Once a class has been defined we can create any number of objects belonging to that class i.e. fruit mango, apple; Here fruit is a class and mango and apple is object of type fruit. (3) Data abstraction and Encapsulation: To combine (the wrapping up of) data and functions into a single unit is known as encapsulation. The data is not accessible to the outside world, and only those functions that are wrapped in the class can access it. These functions provide the interface between the objects data and the program. Protecting data from access by unauthorized function is called data hiding. Data abstraction is a mechanism of representing essential features without including the background details or explanations. e.g. spell checker in MS-Word. (4) Inheritance: Inheritance is the process by which objects of one class acquire the properties (data) of objects of another class. The existing class is known as base class and new class is known as derived class. It supports the concept of hierarchical classification. In OOPs, the concepts of inheritance provide the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class has the combined feature of both the classes. We know that the class of vehicles divided into cars, trucks, buses and motorcycles. The principle in this division is that each subclass shares common characteristics with the class from which it is derived. Cars, trucks, buses, and motorcycles all have wheels and motor; these are defining characteristics of vehicles. In addition to the characteristics shared with other members of the class, each subclass also has its own particular characteristics: buses, for instance, have seats for many people, while trucks have space for hauling heavy loads. (5) Polymorphism: It is a Greek word. Poly means many and morphism means forms. i.e. Polymorphism means one name multiple forms. The ability of a functions and operators to act in different ways on different data types is called polymorphism. e.g. consider the operation of addition, for two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation.

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. To use one function name for many different purposes called function overloading. (6)Dynamic Binding (Late binding): Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time. (7) Message Passing: 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 a desired result. Message passing involves specifying the name of the object, the name of the functions (message) and the information to be sent. e.g. employee.salary (name); Benefits of OOP: OOP offers several benefits to both the program designer and the user. The principal advantages are: (1) Through inheritance, we can eliminate redundant code and extend the use of existing. (2) Classes (3) We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity. (4) The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program. (5) It is possible to have multiple instances of an object to co-exist without any interference. (6) It is possible to map objects in the problem domain to those in the program. (7) It easy to partition the work in a project based on objects. (8) The data-centered design approach enables us to capture more details of a model in implementable form. (9) Object-oriented systems can be easily upgraded from small to large systems. (10) Message passing techniques for communication between objects makes the interface descriptions with external systems much simple. (11) Software complexity can be easily managed. Object-based programming language: A languages that support following features such as : Data encapsulation Data hiding and access mechanisms Automatic initialization and clear-up of objects Operator overloading are known as object-oriented programming languages. ADA is an example of object based language. Object-Oriented programming language: Languages that supports all the features of object-based language such as Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming Data encapsulation Data hiding and access mechanisms Automatic initialization and clear-up of objects Operator overloading and additional two features Inheritance and Dynamic binding are known as object-oriented languages. Application of OOP: The promising areas for application of OOP includes: Real-time system Simulation and modeling Object-oriented databases Hypertext, hypermedia and expertext AI and expert system Neural networks and parallel programming Decision support and office automation systems CIM/CAM/CAD systems.

(1) (2) (3) (4) (5) (6) (7) (8)

How does a main() function in C++ differ from main() in C? 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. Since main() returns an integer type value, return type for main() is explicitly specified as int. Note that the default return type for all function in C++ is int. Declaration of variables: C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write and reduces the errors that may be caused by having to scan back and forth. The only disadvantage of this style of declaration is that we cannot see all the variables used in a scope at a glance. Dynamic initialization of variables: In C, a variable must be initialized at the time of compilation. However, C++ permits initialization of the variable at run time. This is referred to as dynamic initialization. In C++, a variable can be initialized at run-time using the expressions at the place of declaration. e.g. ----------------int n = 5; ----------------float A = 3.14 * r * r; Thus, both the declaration and the initialization of a variable can be done simultaneously at the place where the variable is used for the first time. Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

Dynamic initialization is extensively used in object-oriented programming. We can create exactly the type of object needed, using information that is known only at the run time. Reference variable: C++ introduce a new kind of variable known as reference variable. A reference variable provides an alias (alternative name) for a previously defined variable. A reference variable is created as follows: Data-type &reference-name = variable-name e.g. float total = 100; float &sum = total; Here total is a float type variable that has already been declared, sum is the alternative name declared to represent the variable total. If we write sum = 0 will change the value of both the variables to zero. e.g. main() { int n=100; // int n=100 int &n1 = n; // int n1 = n cout<<n=<<n<<n1=<<n1<<\n; n=0; cout<<n=<<n<<n1=<<n1<<\n; } o/p: n = 100 n1 = 100 // n = 100 n1 = 100 n=0 n1 = 0 // n = 0 n1 = 100 A reference variable must be initialized at the time of declaration. This establishes the correspondence between the reference and the data object that it names. it is important to note that the initialization of a reference variable is completely different from assignment to it. C++ assigns additional meaning to the symbol &. Here, & is not an address operator. The notation int & means reference to int. e.g. (i) int a[10]; int &x = n[10]; //x is alias for n[10] (ii) char &a = \n; // initialize reference to a literal (iii) int x; int *p = &x; int &a = *p; (iv) int &n = 50; A major application of reference variable is in passing arguments to functions. Consider the following: Void f(int &x) { x = x + 10; } int main() Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming { int m = 10; f(m) ------------}

When the function f(m) is executed, the following initialization occurs. Int &x = m; Thus x becomes an alias of m after executing the statement f(m). such function calls are known as call by reference. Characteristics of reference variable: (1) A reference must be always be initialized. Thus the following statements produce an error. Int I = 4; Int &j; //error j =I; (2) once a reference variable has been defined to refer to a particular variable, it cannot refer to any other variable. I.e. once the variable and the reference are linked they are tied together inseparably. (3) We can create a reference to an int, or a float or a char, we can also create a reference to a pointer. e.g. char *p = hello; char *&q = p; (4) A variable can have multiple references. Changing the value of one of them effects changes in all others. (5) Though an array of pointers is acceptable, an array of reference is not. Reference parameter offers several advantages over their equivalent pointer alternatives. (1) From a practical point of view, you no longer need to remember to pass the address of an argument. When a reference parameter is used, the address is automatically passed. (2) in the opinion of many programmers, reference parameters offer a cleaner, more elegant interface than the rather clumsy explicit pointer mechanism. (3) when an object is passed to a function as a reference, no copy is made. This is one way to eliminate the troubles associated with the copy of an argument damaging something needed elsewhere in the program when its destructor function is called. Note: It is critical to understand that a reference is not a pointer. Therefore, when an object is passed by reference, the member access operator remains the dot(.) not the arrow (). Programming exercise: Write a program using reference variable as arguments to swap the value of a pair of integers. Operators in C++: All C operators are valid in C++. In addition, C++ introduces some new operators such as: << Insertion operator

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

>> extraction operator :: Scope Resolution operator ::* Pointer to member declaration ->* Pointer to member operator .* Pointer to member operator delete Memory Release operator endl Line feed operator new Memory allocation operator setw Field width operator

Output operator: Output operator used to display result on the screen. e.g. cout << Object-oriented programming; The string in quotation marks to be displayed on the screen. This statement introduces two new C++ features, cout and <<. The identifier cout is a predefined object that represents the standard output stream in C++. Here the standard output stream represents the screen. The operator << is called the insertion or put to operator. It inserts (or sends) the contents of the variable on its right to the object on its left. Screen

cout Object

<< Insertion operator

C++ Variable

The operator << is the bit-wise left shift operator and it can still be used for this purpose. This is an example of how one operator can be used for different purpose, depending on the context. This concept is known as operator overloading. Input operator: It is used to accept the value from the standard input device. e.g. cin >> no; The number key is placed in the variable no. The identifier cin is a predefined object in C++ that corresponds the standard input stream (k/b). Object Extraction operator Variable

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming >>

cin Keyboard

no

The operator >> is known as extraction or get from operator. It extracts (takes) the value from the k/b and assigns it to the variable on its right. The operator >> can also be overloaded. Cascading of I/O operators: The multiple use of << or >> in one statement is called cascading. e.g. cout <<sum=<<sum<<\n; First sends the string sum= to cout and then sends the value of sum. Finally, it sends the new line character so that the i/o will be in new line. Exercise: Write a C++ program that will ask for a temperature in Fahrenheit and display it in Celsius. Scope Resolution Operator (::): Like C, C++ is also a block structure language. Blocks and scopes can be used in constructing programs. We known that the same variable name can be used to have different meaning in different blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside a block is said to be local to that block. e.g. ---------{ int x = 10; ----------------------} --------------------{ int x=5; --------------------} The two declarations of X refer to two different memory locations containing different values. Statements in the second block cannot refer to the variable X declared in the first block, and vice-versa. Blocks in C++ are often nested. e.g. ---------{ int x = 10; --------Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming { int x = 15; --------} }

10

Here inner block is contained in outer block. Note that a declaration in an inner block hides a declaration of the same variable in an outer block and therefore each declaration of X causes it to refer to a different data object. Within the inner block, the variable X will refer to the data object declared therein. In C, the global version of a variable cannot be accessed from within the inner block. C+ + resolves/removes this problem by introducing a new operator :: called the scope resolution operator. This can be used to uncover a hidden variable. It takes the following form: ::variable-name This operator allows access to the global version of a variable. Following are the applications of scope resolution operator: (1) To access the value of global variable. (2) To change/reinitialize the value of global variable. (3) It is used to identify the class to which member function belongs. e.g. #include <iostream.h> int x = 10; main() { int x = 5; { int k = x; int x = 15; cout<<Inner block; cout<<k=<<k<<\n cout<<x=<<x<<\n; cout<<::x=<<::x<<\n; } cout<<Main block; cout<<x=<<x<<\n; cout<<::x=<<::x<<\n; } Memory management operators: C uses malloc() and calloc() functions to allocate memory dynamically at run time. Similarly, it uses the function free() to release dynamically allocated memory. C++ provides two unary operators new and delete that perform the task of allocating and freeing the memory in a better and easier way. An object can be created by using new, and destroyed by using delete, as and when required. The new operator can be used to create object of any type. The general form of new operator is: Pointer-variable = new data-type; Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

11

Here, pointer-variable is a pointer of type data-type. The new operator allocates sufficient memory to hold a data object of type data-type and returns the address of the object. e.g. int *x; x = new int; Alternatively, we can combine the declaration of pointers and their assignments as follows: e.g. int *x = new int; We can also initialize the memory using the new operator. The syntax is: Pointer-variable = new data-type (value); e.g. int *p = new int(25); will assign 25 to the newly created int object. New cab be used to create a memory space for any data type including user-defined types such as arrays, structures and classes. The general form for 1-D array is: Pointer-variable = new data-type[size] e.g. int *p = new int[10]; creates a memory space for an array of 10 integers. When a data object is no longer needed, it is destroyed to release the memory space for reuse. The general form is: Delete pointer-variable e.g. delete p; If we want to free a dynamically allocated array, we must use Delete [size]pointer-variable; e.g. delete [10]p; The problem with this form is that the programmer should remember the size of the array. Recent versions of C++ do not require the size to be specified. e.g. delete []p; will delete the entire array pointed to by p. If sufficient memory is not available in that case new returns a null pointer. The new operator offers the following advantages over the function malloc(): (1) It automatically computes the size of the data object. We need not use the operator sizeof. (2) It automatically returns the correct pointer type, so that there is no need to use a typecast. (3) It is possible to initialize the object while creating the memory space. (4) Like any other operator, new and delete can be overloaded. Manipulators: Manipulators are operators that are used to format the data display. The most commenly use manipulators are endl and setw. Endl, is used to insert newline in an statement. It is similar to new-line character \n e.g. cout<<this line1<<endl<<this line 2; By default an integer values are left-justified. Now we want to display numbers right-justified, setw manipulators is used. e.g. cout<<a=<<setw(3)<<a<<endl<<b=<<setw(3)<<b; we can also write our own manipulaters as follows: #include<iostream.h> Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

12

ostream &symbol(ostream &output) { return output <<\tRs; } Here the symbol is new manipulator, which represents Rs, and output is stream-name. The identifier symbol can be used whenever we need to display the string Rs. New features that are added to C++ functions and their implementation: Main function: C dose not specify any return type for the main() function which is the starting point for the execution of a program. The definition of main() would like this: main() { //body of function } In C++, main() returns an integer type value to the operating system. In C++, the definition of main() is as follows: int main() { return 0; } Return by reference: A function can also return a reference. Consider the following function: int &max(int &x, int &y) { if(x>y) return x; else return y; } Here the function returns reference to x or y. then a function call such as max(a,b) will yield a reference to either a or b depending on their values. This means that this function call appear on the left-hand side of an assignment statement. i.e. max(a,b) = -1; is legal and assign 1 to a if it is larger, otherwise 1 to b. Inline function: One of the objectives of using function in a program is to save some memory space, which becomes appreciable when a function is likely to be called many times. However, every time a function is called, it takes a lot of extra time in executing a series of instructions for tasks

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

13

such as jumping to the function, saving registers, pushing arguments into the stack, and returning to the calling function. To overcome this problem, C++ introduced a new feature called inline function. An inline function is a function that is expanded in line when it is invoked. I.e. the compiler replaces function call with the corresponding function code. The inline functions are defined as follows: Inline function-header { function-body; } e.g. inline double area_sqr(double a) { return(a * a); } Keyword inline is required to create inline function. All inline functions must be defined before they are called. Inline functions are small enough to be defined in one or two lines. Inline function makes a program run faster because the overhead of a function call and return is eliminated. However, it makes the program to take up more memory. The speed benefits of inline functions diminish as the function grows in size. Some the situations where inline expansion may not work are: (1) If loop, a switch or a goto exists. (2) For functions not returning values, if a return statement exists. (3) If function contains static variables. (4) If inline functions is recursive. Inline expansion makes a program run faster because the overhead of a function call and return is eliminated. However, it makes the program to take up more memory because the statements that define the inline function are reproduced at each point where the function is called. So a trade-off becomes necessary. Do inline functions improve performance? Yes and no. Sometimes. Maybe. There are no simple answers. inline functions might make the code faster, they might make it slower. They might make the executable larger, they might make it smaller. They might cause thrashing, they might prevent thrashing. And they might be, and often are, totally irrelevant to speed. inline functions might make it faster: As shown above, procedural integration might remove a bunch of unnecessary instructions, which might make things run faster. inline functions might make it slower: Too much inlining might cause code bloat, which might cause "thrashing" on demand-paged virtual-memory systems. In other words, if the executable size is too big, the system might spend most of its time going out to disk to fetch the next chunk of code.

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

14

inline functions might make it larger: This is the notion of code bloat, as described above. For example, if a system has 100 inline functions each of which expands to 100 bytes of executable code and is called in 100 places, that's an increase of 1MB. Is that 1MB going to cause problems? Who knows, but it is possible that that last 1MB could cause the system to "thrash," and that could slow things down. inline functions might make it smaller: The compiler often generates more code to push/pop registers/parameters than it would by inline-expanding the function's body. This happens with very small functions, and it also happens with large functions when the optimizer is able to remove a lot of redundant code through procedural integration that is, when the optimizer is able to make the large function small. inline functions might cause thrashing: Inlining might increase the size of the binary executable, and that might cause thrashing. inline functions might prevent thrashing: The working set size (number of pages that need to be in memory at once) might go down even if the executable size goes up. When f() calls g(), the code is often on two distinct pages; when the compiler procedurally integrates the code of g() into f(), the code is often on the same page. inline functions might increase the number of cache misses: Inlining might cause an inner loop to span across multiple lines of the memory cache, and that might cause thrashing of the memory-cache. inline functions might decrease the number of cache misses: Inlining usually improves locality of reference within the binary code, which might decrease the number of cache lines needed to store the code of an inner loop. This ultimately could cause a CPU-bound application to run faster. inline functions might be irrelevant to speed: Most systems are not CPU-bound. Most systems are I/O-bound, database-bound or network-bound, meaning the bottleneck in the system's overall performance is the file system, the database or the network. Unless your "CPU meter" is pegged at 100%, inline functions probably won't make your system faster. (Even in CPU-bound systems, inline will help only when used within the bottleneck itself, and the bottleneck is typically in only a small percentage of the code.) There are no simple answers: You have to play with it to see what is best. Do not settle for simplistic answers like, "Never use inline functions" or "Always use inline functions" or "Use inline functions if and only if the function is less than N lines of code." These one-size-fits-all rules may be easy to write down, but they will produce sub-optimal results. Programming exercise: (1) write a inline function for the following: (a) meter to centimeter conversion (b) find the area of cube

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

15

Default arguments: C++ allows us to call a function without specifying all its arguments. In such cases, the functions assign a default value to the parameter, which does not have a matching argument in the function call. Default values are specified when the function is declared. e.g. a prototype (i.e. function declaration) with default values: float amount (float p, int n, float r = 0.15); we can call this function like value = amount(5000,7) //rate is missing Here the default value of rate (0.15) is pass to the amount function. e.g. value = amount (5000,5,0.12) passes an explicit value of 0.12 to rate. A default argument is checked for type at the time of declaration and evaluated at the time of call. Only the trailing arguments can have defaults values. Default values must add from rigth-to-left. We cannot provide a default value to a particular argument in the middle of an argument list. Some of the examples with default argument are as follows: Float amount(float p, int n=3, float r=0.10); //valid Float amount(float p=3000, int n, float r=0.10); //invalid Float amount(float p=2000, int n=3, float r=0.10); //valid Default arguments are useful in situations where some arguments always have the same value. e.g. #include<iostream.h> #include<conio.h> int main() { float amt; clrscr(); float value(float p, int n,float r=0.12); void pline(char ch='*', int len=20); pline(); amt = value(5000,5); cout<<"\nFinal value="<<amt<<endl; pline(); return(0); } float value(float p, int n, float r) { int amt; amt = p * r * n / 100; return(amt); } void pline(char ch, int l) { for(int i=1;i<=l;i++) cout<<ch; }

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

16

Write an area function that calculates area of cube, rectangle or square. (Hint: Use default argument) area(int a, int b=0, int c=0) { if (b==0 && c==0) return a * a; //calculate area of square else if(c==0) return a * b; //calculate area of rectangle else return a * b * c; //calculate area of cube } Advantages of providing the default arguments are: (1) We can use default arguments to add new parameters to the existing functions. (2) Default arguments can be used to combine similar functions into one. Function overloading: Overloading means to use of the same thing for different purposes. C++ also permits function overloading. This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function overloading/polymorphism. Using the concept of function overloading, we can design a family of functions with one function name but with different argument lists. Consider the following function prototype: //declarations Int add(int,int); //prototype 1 Int add(int,int,int); //prototype 2 double add(double,double); //prototype 3 double add(int,double); //prototype 4 double add(double,int); //prototype 5 //function calls cout<<add(5,10); cout<<add(5,10.0); cout<<add(12.5,10.5); cout<<add(5,10,15); cout<<add(0.75,5); //uses prototype 1 //uses prototype 4 //uses prototype 3 //uses prototype 2 //uses prototype 5

A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. The function selection involves the following steps: (3) The compiler first tries to find an exact match in which the type of actual arguments are the same, and use that functions. (4) If an exact match is not found, the compiler uses the integral promotions to the actual arguments such as char to int, float to double and so on to find a match.

Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming

17

(5) When either of them fails, the compiler tries to use the built-in conversions to actual arguments and then uses the function whose match is unique. If conversion is possible to have multiple matches, then the compiler will generates an error message. e.g. long square(long n) double suare(double x) a function call such as square(10) will cause an error because int argument can be converted to either long or double. (6) If all of the steps fail, then the compiler will try the user-defined conversions in combination with integral promotions and built-in conversions to find a unique match. Friend and virtual function: C++ introduces two new type of functions, namely, friend and virtual function. Limitation of C structure: (1) You cannot add two structure variables (complex). e.g. struct complex { float a; float b; }c1,c2,c3; c3 = c1 + c2; //illegal in C (2) By default the members of structure are public i.e. structure member can be directly accessed by the structure variable by any function anywhere in their scope. Self-referential structure: A self-referential structure is one which contains a pointer to its own type. e.g. struct student { int no; char name[30]; struct student *next; }; Here the structure student has a pointer next, which can point to another student structure. Self-referential structures are very useful in applications that involve linked data structures, such as lists and trees etc. e.g. #include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> #define NULL 0 main() { struct student { int no; Object Oriented Programming

Chapter: 2 Principles of Object Oriented Programming char name[30]; struct student *next; }*first=NULL,*curr,*temp; int n,i; printf("\nEnter no of student:"); scanf("%d",&n); while(n>0) { temp=new struct student; if(temp==NULL) { printf("\nMemory not available"); exit(0); } printf("\nEnter no:"); scanf("%d",&temp->no); printf("\nEnter a name:"); flushall(); gets(temp->name); temp->next=NULL; if(first==NULL) { first=temp; curr=temp; } else { curr->next=temp; curr=curr->next; } n--; } curr=first; while(curr!=NULL) { printf("\n%d\t%s",curr->no,curr->name); curr=curr->next; } }

18

Object Oriented Programming