Programming In C++


Published on

C++ has certain characteristics over other programming languages.

Published in: Education, Technology
  • Very Nice, If you want more good Presentations visit, Its a wonderful website for latest Presentations and Research
    Are you sure you want to  Yes  No
    Your message goes here
  • Beginning C++ Through Game Programming ---
    Are you sure you want to  Yes  No
    Your message goes here
  • The C++ Programming Language, 4th Edition ---
    Are you sure you want to  Yes  No
    Your message goes here
  • Jumping into C++ ---
    Are you sure you want to  Yes  No
    Your message goes here
  • very goog.thank you.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Programming In C++

  1. 1. Course:- B.C.A & B.SC(IT) Date:-17-October-2006 SHAMMI KUMAR (B.C.A)
  2. 2. Chapter-1st
  3. 3. Software Crisis Development in software technology continue to be dynamic. New tools and techniques are announced in quick succession. This has forced the software engineers and industry to continuously look for new approaches to software design and development, and they are becoming more and more critical in view of the increasing complexity of software systems as well as the highly competitive nature of the industry. These rapid advances appear to have created a situation
  4. 4. of crisis within the industry. The following issues need to be addressed to face this crisis: How to represent real-life entities of problems in system design? How to ensure reusability and extensibility of modules? How to develop modules that are tolerant to any changes in future? How to improve software productivity and decrease software cost?
  5. 5. How to improve the quality of software? How to manage time schedules? These studies and other reports on software implementation suggest that software products should be evaluated carefully for their quality before they are delivered and implemented. Some of the quality issues that must be considered for critical evaluation are: Correctness Maintainability
  6. 6. Reusability Portability Security User friendliness Procedure-Oriented Programming In the procedure-oriented approach, the problem is viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. Procedure-oriented programming basically
  7. 7. consists of writing a list of instructions (or actions) for the computer to follow, and organizing these instructions into groups known as functions. We normally use a flowchart to organize these actions and represent the flow of control from one actions to another. In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Figure below shows the relationship of data and functions in a procedure- oriented program.
  8. 8. Global data Global data Function-1 Local data Function-2 Local data Function-3 Local data Fig. Relationship of Data and Functions in Procedural Programming
  9. 9. Some characteristics exhibited by procedure- oriented programming are: Emphasis is on doing things (algorithms). Large programs are divided into smaller programs known as functions. Most of the functions share global data. Data move openly around the system from function to function. Employs top-down approach in program design.
  10. 10. Object-Oriented Programming Paradigm The major objective of Object-oriented approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The organization
  11. 11. of data and functions in object-oriented programs is shown in figure below. 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. Some of the striking features of object-oriented programming are: Programs are divided into what are known as objects. Programs are divided into what are
  12. 12. known as objects. • Functions that operate on the data of an object are tied together in the data structure. • Data is hidden and cannot be accessed by external functions. • Objects may communicate with each other through functions. • New data and functions can be easily added whenever necessary.
  13. 13. Follows bottom-up approach in program design. Data Functions Object A Data Functions Object B Functions Data Object C Communication Fig. Organization of data and functions in OOP
  14. 14. It is necessary to understand some of the concepts used extensively in object-oriented programming. These include: 1. Objects and Classes 2. Data abstraction and encapsulation 3. Inheritance 4. Polymorphism
  15. 15. 5. Dynamic binding 6. Message passing 1 Objects and Classes:- Objects are the basic runtime entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program may handle. They may also represent user-defined data types such as vectors and list.Each data contains data and code to manipulate the data.
  16. 16. The entire set of data and code of an object can be made a user-defined data type using the concept of a class.A class may be thought of as a ‘data type’ and an object as a ‘variable’ of that data type. For example Mango, Apple,and Orange are members of the class Fruit.
  17. 17. Person Name BasicPay Salary () Tax () Object Data Methods Fig. Representation of an Object
  18. 18. 2. Data Abstraction and Encapsulation:- The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. Abstraction refers to the act of representing essential features without including the background details or explanations. 3. Inheritance:- It is the process by which
  19. 19. objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. For example, the bird robin is a part of the class flying bird, which is again a part of the class bird. As illustrated in fig. below, the principle behind this sort of division is that each derived class shares common characteristics with
  20. 20. derived. Bird Attributes: Feathers Flying Bird Attributes: Nonflying Bird Attributes: Robin Attributes: Swallow Attributes: Pigeon Attributes: Kiwi Attributes:
  21. 21. In OOP, the concept of inheritance provides 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. 4. Polymorphism:- Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. For example, an
  22. 22. operation may exhibit different behaviour in different instances. The behaviour depends upon the types of data used in the operation. For example, 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. Figure below shows that a single function name can be used to handle different number and different types of
  23. 23. arguments. Shape Draw ( ) Circle Object Draw ( ) Box Object Draw ( ) Draw ( ) Triangle Object Fig. Polymorphism
  24. 24. Dynamic 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 runtime. 6. Message Communication:- An object- oriented program consists of a set of objects that communicate with each
  25. 25. other. The process of programming in an object-oriented language, therefore, involves the following basic steps: 1.Creating classes that define objects and their behaviour. 2. Creating objects from class definitions. 3. Establishing communication among objects. Objects communicate with one another
  26. 26. by sending and receiving information much the same way as people pass messages to one another as shown in fig. below Object 1 Object 5 Object 2 Object 4 Object 3 Fig. Network of objects communicating between them
  27. 27. Message passing involves specifying the name of the object, the name of the method (message) and the information to be sent. For example, consider the statement Employee. Salary (name); Here, Employee is the object, salary is the message and name is the parameter that contains information.
  28. 28. OOP offers several benefits to both the program designer and the user.The principle advantages are:  Through inheritance, we can eliminate redundant code and extend the user of existing classes. We can build programs from the standard
  29. 29. 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.  The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.  Message passing techniques for
  30. 30. communication between objects make the interface descriptions with external systems much simpler.  Software complexity can be easily managed.  It is possible to have multiple instances of an objects to co-exist without any interference.
  31. 31. Object-Oriented Languages The languages should support several of the OOP concepts to claim that they are object-oriented. Depending upon the features they support, they can be classified into the following two categories: 1. Object-based programming languages, and 2. Object-oriented programming languages. Object-based programming is the style of
  32. 32. programming that primarily supports encapsulation and object identity. Major features that are required for object-based programming are:  Data Encapsulation  Data hiding and access mechanisms  Automatic initialization and clear-up of objects  Operator overloading Languages that support programming with objects are said to be object-based
  33. 33. programming languages. They do not support inheritance and dynamic binding. Ada is a typical object-based programming language. Object-Oriented programming incorporates all of object-based programming features along with two additional features, namely, inheritance and dynamic binding. Object- oriented programming can therefore be characterized by the following statement: Object-based features + Inheritance + Dynamic binding
  34. 34. Applications of OOP There appears to be a great deal of excitement and interest among software engineers in using OOP. Applications of OOP are beginning to gain importance in may areas. The most popular application of object- oriented programming has been in the area of user interface design such as windows. OOP is useful in these types of applications because it can simplify a complex problem. The promising areas for application of OOP include:
  35. 35. • Object-Oriented Databases •AI and Expert Systems • Decision support and office Automation Systems It is believed that the richness of OOP environment will enable the software industry to improve not only the quality of software systems but also its productivity. Object-Oriented technology is certainly going to change the way the software engineers think, analyze, design and implement future systems.
  36. 36. Chapter-2nd
  37. 37. What is C++ C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the languages and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula67. Since the class
  38. 38. was a major addition to the original C language, Stroustrup initially called the new language ‘C with classes’. However, later in 1983, the name was changed to C++. The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is an augmented (incremented) version of C. During the early 1990’s the language underwent a number of improvements and changes. In November 1997, the ANSI/ISO standards committee standardised these changes and added several new features to the language specifications.
  39. 39. C++ is a superset of C. Most of what we already know about C applies to C++ also. The most important facilities that C++ adds on to C are classes, inheritance, function overloading, and operator overloading. These features enable creating of abstract data types, inherit properties from existing data types and support polymorphism, thereby making C++ a truly object-oriented language.
  40. 40. C++ is a versatile (flexible) language for handling very large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication systems and any complex real-life application systems.  Since C++ allows us to create hierarchy- related objects, we can buildspecial object- oriented libraries which can be used later by many programmers. Applications of C++
  41. 41.  While C++ is able to map the real-world problem properly, the C part of C++ gives the language the ability to get close to the machine- level details.  C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, it is very easy to add to the existing structure of an object. A Simple C++ Program #include<iostream> // include header file int main( )
  42. 42. { cout<<“C++ is better than c.n”; // C++ statement return o; } // end of example The simple program demonstrates several C++ features. • Program Features :- Like C, the C++ program is a collection of functions. The above example contains only one function, main( ). As usual, execution begins at main( ). Every C++ program
  43. 43. must have a main(). Like C, the C++ statement terminate with semicolons. • Comments :- C++ introduces a new comment symbol // (double slash). Comments start with a double slash symbol and terminate at the end of the line. A comment may start anywhere in the line, and whatever follows till the end of the line is ignored. The double slash comment is basically a single line comment. Multiline comments can be written as follows: // This is an example of
  44. 44. // C++ program to illustrate // Some of its features The C comment symbols /*,*/ are still valid and are more suitable for multiline comments. The following comment is allowed: /* This is an example of C++ program to illustrate Some of its features */
  45. 45. • Output Operator :- The statement cout<<“C++ is better than C.”; Causes the string in quotation marks to be displayed on the screen. This statement introduces two new C++ features, cout and <<. The identifier cout (pronounced as ‘C out’) is a predefined object that represents the standard output stream in C++. 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.
  46. 46. Cout << “C++” Screen Object Insertion Operator Variable Fig. Output using Insertion Operator
  47. 47. • The iostream File :- We have used the following #include directive in the program: #include<iostream> This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator <<. Some old versions of C++ use a header file called iostream.h. This is one of the changes introduced by ANSI C++.(We should use iostream.h if the compiler does not support ANSI C++ features.) The header file iostream should be included at
  48. 48. the beginning of all programs that use input/output statements. We must include appropriate header files depending on the contents of the program and implementation. • Return Type of main() :- 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:- The default return type for all functions in C++ is int.
  49. 49. The following main without type and return will run with a warning: main() { -------- -------- }
  50. 50. More C++ Statements #include<iostream> int main() { float number1, number2, sum, average; cout<<“Enter two numbers:”; cin>>number1; cin>>number2; sum=number1+number2;
  51. 51. average=sum/2; cout<<“Sum=“<<sum<<“n”; cout<<“Average=“<<average<<“n”; return 0; } Structure of C++ Program A typical C++ program would contain four sections as shown in fig. Below. These sections may be placed in separate code files and then compiled independently or jointly.
  52. 52. It is a common practice to organize a program into three separate files. The class declarations Include files Class declaration Member function definitions Main function program Fig. Structure of a C++ program
  53. 53. are placed in a header file and the definitions of member functions go into another file. This approach enables the programmer to separate the abstract specification of the interface (class definition) from the implementation details (member functions definition). Finally, the main program that uses the class is placed in a third file which “includes” the previous two files as well as any other files required. This approach is based on the concept of client-server model as shown in fig. below. The class definition including the member functions constitute the server that provides services to the
  54. 54. main program known as client. The client uses the server through the public interface of the class Member functions Class definition Server Main function program Client Fig. The client-server model
  55. 55. Creating The Source File Like C programs, C++ programs can be created using any text editor. For example, on the INIX, we can use vi or ed text editor for creating and editing the source code. On the DOS system, we can use editor or any other editor or a word processor system under non-document mode. Some systems such as Turbo C++ provide an integrated environment for developing and editing programs. The file name should have a proper file
  56. 56. extension to indicate that it is a C++ program file. C++ implementations use extensions such as .c, .C, .cc, .cpp and .cxx. Turbo C++ and Borland C++ use .c for C programs and .cpp for C++ programs. Zortech C++ systems uses .cxx while UNIX AT&T version uses .C and .cc. The operating system manuals should be consulted to determine the proper file name extensions to be used.
  57. 57. Compiling and Linking The process of compiling and linking again depends upon the operating system. A few popular systems are discussed in this section. Unix AT&T C++ :- The process of implementation of a C++ programs under UNIX is similar to that of a C program. We should use the “CC” (uppercase) command to compile the program. Remember we use lowercase “cc” for compiling C programs.
  58. 58. Turbo C++ and Borland C++ :- It provide an integrated program development environment under MS DOS. They provide a built-in editor and a menu bar which includes options such as File, Edit, Compile and Run. Visual C++ :- It a Microsoft application development system for C++ that runs under Windows. Visual C++ is a visual programming environment in which basic program components can be selected through menu choices, buttons, icons and other predetermined methods.
  59. 59. Chapter-3rd
  60. 60. C++ is a superset of C and therefore most constructs of C are legal in C++ with their meaning unchanged. However, there are some exceptions and additions. Tokens The smallest individual units in a program are known as tokens. C++ has the following tokens: • Keywords
  61. 61. • Identifiers • Constants • Strings • Operators Keywords:- The keywords are also the identifiers but can’t be user-defined since they are reserved words. The following words are reserved for use as keywords. We should not choose them as variables or identifiers. It is mandatory that all keywords be in lowercase letters. int, long, float, auto, class, char, static, private,
  62. 62. switch, long, return, goto, short, throw, while, inline, friend, extern, catch, enum, else, default, protected, new, signed, etc. Identifiers:- It can be defined as the name of the variables and some other program elements using the combinational of following characters. Alphabets----- a-z, A-Z Numerals----- 0-9 Underscore----- _ Constants:- There are three types of constants:-
  63. 63. 1. String Constant 2. Numeric Constant 3. Character Constant String Constant:- String constant is a sequence of alphanumeric characters enclosed in double quotation marks whose maximum length is 256 characters. Numeric constants:- There are the +ve and –ve numbers. There are four types of numeric constants:- integer constants, floating constants,
  64. 64. hexadecimal constants and octal constants. An integer may either be short and long integer. A floating point constant may be either single or double. • Integer constant:- It don't contain decimal points. Variables can be declared as integers in the following ways: Data types Size int 2-4 bytes short int 2 bytes long int 4 bytes
  65. 65. • Floating point constants:- It consists of +ve and –ve numbers but in decimal form. Floating point consists of three data types: float, double, long double. The floating point types and its size in C++ are given in the following table: Data types Size float 4 bytes double 8 bytes long double 12-16 bytes
  66. 66. • Hexadecimal Constants:- Hexadecimal numbers are integer numbers of base 16 and their digits are 0-9 and A to F. Any hexadecimal number characterized in the hexadecimal constant groups. In C++ it is normally represented using the character x. • Octal Constants:- Octal numbers are the integer numbers of base 8 and their digits are 0-7. Any octal number is characterized in the octal constant group. Character Constants:- The character constants are represented within the single quotes.
  67. 67. For Example: ‘A’, ‘a’ etc. Basic Data Types Data types are those keywords which shows what type of variables we are going to declare. Data types used in C++ area re as under:- 1. Integer Data types:- Integer data types consists of integer values I.e non-zero values. There are three types of Integer data types. Data types Size int 2-4 bytes short int 2 bytes
  68. 68. long int 4 bytes 2. Float data types:- Floating point data types are used to declare variables of floating types. Variables of floating types. Variables of floating types consists of values having a decimal in it. Floating values are both in +ve and –ve form. There are three types of floating data types: float, double and long double. Data types Size float 4 bytes double 8 bytes
  69. 69. long double 12-16 bytes 3. Character Data types:- Any character belonging to the ASCII character set is considered as a character data type whose size is 8 bits long. The character is a keyword to represent the character data types in C++ For Example:- char ‘c’.
  70. 70. User-Defined Data Types Structures and Classes:- C++ also permits us to define another user-defined data type known as class which can be used, just like any other basic data type, to declare variables. The class variables are known as objects, which are the central focus of object-oriented programming. Enumerated Data Type:- It is another user- defined type which provides a way for attaching names to numbers, thereby increasing comprehensibility of the code. The enum keyword (from C) automatically enumerates a
  71. 71. list of words by assigning them values 0,1,2 and so on. This facility provides an alternative means for creating symbolic constants. The syntax of an enum statement is similar to that of the struct statement. Examples: enum shape{circle,square,triangle}; enum colour{red,blue,green,yellow}; enum position{off,on};
  72. 72. Derived Data Types Arrays:- The application of arrays in C++ is similar to that in C. The only exception is the way character arrays are initialized. When initializing a character array in ANSI C, the compiler will allow us to declare the arrays size as the exact length of the string constant. For instance, char string[3]=“xyz”; is valid in ANSI C. It assumes that the programmer intends to leave out the null character 0 in the definition. But in C++, the size
  73. 73. should be one larger that the number of characters in the string. char string[4]=“xyz”; //O.K. for C++ Functions:- Functions have undergone major changes in C++. While some of these changes are simple, others require a new way of thinking when organizing our programs. Many of these modifications and improvements were driven by the requirements of the object-oriented concept of C++. Pointers:- A data type that holds the address of a location in memory. Pointers are extensively
  74. 74. used in C++ for memory management and achieving polymorphism. Symbolic Constants There are two ways of creating symbolic constants in C++: • Using the qualifier constant, and • Defining a set of integer constants using enum keyword. In both C and C++, any value declared as const cannot be modified by the program in any
  75. 75. way. However, there are some differences in implementation. In C++, we can use const in a constant expression, such as const int size=10; Another method of naming integer constants is by enumeration as under; enum{x,y,z}; This defines x,y and z as integer constants with values 0,1 and 2 respectively. This is equivalent to: const x=0;
  76. 76. const y=1; const z=2; 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. It also makes the program easier to understand because the variables are declared in the context of their use.
  77. 77. The example below illustrates this point. #include<iostream.h> #include<conio.h> int main() { float x; // declaration float sum=0; for(int i=1;i<5;i++) // declaration {
  78. 78. cin>>x; sum=sum+x; } float average; // declaration average=sum/i; cout<<average; getch(); return 0; }
  79. 79. Dynamic Initialization of Variables C++, however, permits initialization of the variables at run time. This is referred to as dynamic initialization. In C++, a variable can be initialized at run time using expressions at the place of declaration. For example Float area=3.14*rad*rad;
  80. 80. Reference Variables C++ introduces a new kind of variable known as the reference variable. A reference variable provides an alias (alternative name) for a previously defined variable. For example, if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable. A reference variable is created as follows: Syntax: data-type & reference-name= variable-name
  81. 81. Example: 1. float total=100; float sum=total; 2. int n[10]; int &x=n[10]; // x is alias for n[10] Operators in C++ The different types of operators and their usage in C++ are explained in the following sections. There are some unusual operators making unlike the other high level languages
  82. 82. 1. Arithmetic Operators 2. Assignment operators 3. Comparison operators 4. Logical operators (Relational, Equality, Logical) 5. Special operators (Unary, Ternary, Comma, Scope, new and delete, other operators)
  83. 83. 3. Comparison Operators:- The comparison operators can be grouped into three categories. They are the Relational operators, Equality operators and Logical operators. a). Relational Operators:- It compare the values to see if they are equal or if one of them is greater than the other and so on. Operators Meaning < Less than > Greater than <= Less than equal to
  84. 84. >= Greater than equal to b). Equality Operators:- Equality operators are used to check the equality of the given expression. Operators Meaning == Equal to != Not equal to C). Logical Operators:- There are three logical operators used in C++, AND, OR and NOT. • Logical AND:- A compound expression is true when two conditions are true. The results of an
  85. 85. AND logical operators are as under:- Situation Results True && True True True && False False False && True False False && False False • Logical OR:- In logical Or if one or both the conditions are satisfied then the result is true. Situation Results
  86. 86. True||False True False||True True False||False False • Logical NOT:- Logical NOT can changed the condition from true to false and false to true. Situation Results !(True) False !(False) True 4. Special Operators:- These are special type of operators used in C++ language to perform
  87. 87. 4. particulars function. • Unary Operators:- The unary operators require only a single expression to produce a line. Unary operators usually precede their single operands. Sometimes some unary operators may be followed by the operands such as incremental and decremental. Operators Meaning -- Decrement ++ Increment
  88. 88. * The pointer operator is used to get the content of the address & Address operator is used to get the address of the variable. • Cast Operators:- This operators is used to convert one data type to another • Ternary Operator • Comma Operator • Scope Operator:- The double colon is used as the scope resolution operator in C++.
  89. 89. • New and Delete Operator:- New operator is used for giving memory allocation to an object and delete is used to remove the memory allocation of an object. Scope Resolution Operator Like C, C++ is also a block-structured language. Blocks and scopes can be used in constructing programs. We know that the same variable name can be used to have different meanings 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.
  90. 90. --------- { int x=10; ------ ------ { int x=1; -------- -------- } --------- } Block 1 Block 2
  91. 91. Block 2 is contained in block 1. Note:- 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 with in the inner block. C++ resolves 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: Syntax:- ::variable_name
  92. 92. Program on Scope Resolution Operator #include<iostream.h> #include<conio.h> int m=10; //global m int main() { int m=20; //m redeclared, local to main { int k=m;
  93. 93. int m=30; //m declared again // local to inner block cout<<“We are in inner blockn”; cout<<“k=“<<k<<“n”; cout<<“m=“<<m<<“n”; cout<<“::m=“<<::m<<“n”; } cout<<“n we are in outer blockn”; cout<<“m=“<<m<<“n”;
  94. 94. cout<<“::m=“<<::m<<“n”; getch() return 0; } Memory Management Operators C uses malloc() and calloc() functions to allocate memory dynamically at run time. Similarly, it uses the function free() to free dynamically allocated memory. We use dynamic allocation techniques when it is not known in advance how much of memory space is needed. Although C++ supports these functions, it also defines two unary operators new and delete that
  95. 95. perform the task of allocating and freeing the memory in a better and easier way. 1. New:- The new operator is used to create heap of memory space for an object of a class. The allocation is carried out as:- a) Storage for object is found. b) Object is initialized. c) A suitable pointer to the object is returned. If the ‘New’ operator is successful a pointer to the space is returned otherwise it returns the value zero. Syntax:- data_type pointer=new data_type
  96. 96. For example:- int *p=new int; 2. Delete:- The delete operator is used to destroy the space for the variable which has been created by using the new operator. In reliability, the delete keyword calls upon the function operator delete( ). Syntax:- delete pointer_variable; For example:- delete p;
  97. 97. Manipulators Manipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw. The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It has the same effect as using the newline character “n”. For example:- cout<<“m=“<<m<<endl;
  98. 98. The manipulator setw specifies a field width for printing the value of the variable. This value is right-justified within the field. Program on Manipulators:- #include<iostream.h> #include<conio.h> #include<iomanip.h> int main() { int basic=950,allowance=95,total=1045;
  99. 99. cout<<setw(5)<<“basic”<<setw(5)<<basic<<endl <<setw(5)<<“allowance”<<setw(5)<<allowance<<endl <<setw(5)<<“total”<<setw(5)<<total<<endl; getch(); return 0; } Type Cast Operator Conversion by using the assignment operator is carried out automatically but one may not get the desired results. The cast operator is a technique to forcefully
  100. 100. convert one data type to another. The operator used for type casting is called as the cast operator and the process is called as casting. Syntax:- (cast_type) expression; or cast_type (expression);
  101. 101. Expressions and their Types An expression is a combination of operators, constants and variables arranged as per the rules of the language. It may also include function calls which return values. An expression may consist of one or more operands , and zero or more operators to produce a value. Expressions may be of the following seven types: • Constant expressions • Integral expressions • Float expressions • Pointer expressions
  102. 102. •Relational expressions • Logical expressions • Bitwise expressions An expression may also use combination of the above expressions. Such expressions are known as compound expressions. Constant Expressions:- It consist of only constant values. Integral Expressions:-These are those which produce integer results after implementing all the automatic and explicit type conversions.
  103. 103. Float Expressions:- These are those which, after all conversions, produce floating-point results. Pointer Expressions:- These expressions produce address values. Relational Expression:- Relational expressions yield results of type bool which takes a value true or false. Examples:- x<=y a+b==c+d m+n>100 When arithmetic expression are used on either side of a relational operator, they will be evaluated first and then
  104. 104. the results compared. Relational expressions are also known as Boolean expressions. Logical Expressions:- Logical expressions combine two or more relational expressions and produces bool type results. Examples: a>b && x==10; x==10 || y==5 Bitwise Expressions:- These are used to manipulate data at bit level. They are basically used for testing or shifting bits. Examples: x<<3 //shift three bit position to left
  105. 105. y>>1 //shift one bit position to right Special Assignment Expressions 1. Chained Assignment:- x=(y=10); or x=y=10; First 10 is assigned to y and then to x. A chained statement cannot be used to initialize variables at the time of declaration.
  106. 106. For instance, the statement float a=b=12.34 //wrong is illegal. This may be written as float a=12.34, b=12.34 //correct 2. Embedded Assignment:- x=(y=50)+10; (y=50) is an assignment expression known as embedded assignment. Here, the value 50 is assigned to y and then the result 50+10=60 is assigned to x. This statement is identical
  107. 107. y=50; x=y+10; 3. Compound Assignment:- Like C, C++ supports a compound assignment operator which is a combination of the assignment operator with a binary arithmetic operator. For example, the simple assignment statement x=x+10; may be written as x+=10; The operator += is known as compound
  108. 108. assignment operator or short-hand assignment operator. Implicit Conversions We can mix data types in expressions. For example, m=5+2.75; is valid statement. Wherever data types are mixed in an expression, C++ performs the conversion automatically. This process is known as implicit or automatic conversion.
  109. 109. Operator Overloading The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. The behaviour depends upon the types of data used in the operation. For example:- 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. The main advantage of using an overloading operator in a program are that is much easier to read and debug.
  110. 110. Operator Precedence Although C++ enables us to add multiple meanings to the operators, yet their association and precedence remain the same. For example, the multiplication operator will continue having higher precedence than the add operator. Control Structures
  111. 111. Chapter-4th
  112. 112. Introduction Functions play an important role in program development. Dividing a program into functions is one of the major principles of top-down, structured programming. Another advantage of using functions is that it is possible to reduce the size of a program by calling and using them at different places in the program. Syntax:- void show(); /*Function declaration*/ main()
  113. 113. { ------ show(); /*function call*/ ------- } void show() /*function definition*/ { -------- -------- /*function body*/ ---------
  114. 114. Function Prototyping Function prototyping is one of the major improvements added to C++ functions. The 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. With function prototyping, a template is always used when declaring and defining a function. When a function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. Any violation in matching the
  115. 115. arguments or the return types will be caught by the compiler at the time of compilation itself. Syntax:- type function_name(argument_list); For Example:- float volume(int x,float y,float z);
  116. 116. Call By Reference Whenever a function with formal arguments is invoked, the address of the actual arguments are copied into the formal arguments though they have different variable names. Now if the arguments are changed in the formal function, they will be returned to the calling function in altered form, as the formal and actual arguments have the same memory location. Hence when the arguments are passed to the formal function by reference, it means that their address is passed and
  117. 117. so any change that is made in the formal function will change the calling function. For Example:- void main() { int a=10,b=20; swap(&a, &b); cout<<a<<b;
  118. 118. swap(int *x, int *y) { int=temp; temp=*x; *x= *y; *y=temp; getch(); }
  119. 119. Default Arguments C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns 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. For example:- void main() { float amount();
  120. 120. float value(int p,int b,float r=5.13); amount=value(50,5); cout<<“nfinal value=“<<amount<<“n; } float value(int p,int n,float r) { float temp; temp=p+n+r; cout<<“sum=“<<temp;
  121. 121. getch(); return(temp); } Function Overloading It is a logical method of calling several functions with different arguments and data types that perform basically identical things by same name. Its main advantages are:- Elimination of use of different function names for same operations. Helps to understand, debug and grasp easily.
  122. 122. Easy maintenance of the data. The function declaration and function definition are essential for each function with same name but different arguments. Function Overloading with various Data types It allows to use the same function name for various data types. The function declaration,definition and function call are done with the same name but different data arguments. The correct name will be selected by C++
  123. 123. compiler for comparing the types of actual parameters with formal parameters. Function Overloading with Arguments A function can also be overloaded for number of arguments in the function call. Scoping Rules for Function Overloading The overloading mechanism is acceptable only within the same scope of the function declaration. The same function name in various classes is not said to be overloaded.
  124. 124. Program on Function Overloading:- void main() { int square(int); float square(float); int x, xsqr; float y, ysqr; cout<<“Enter x and y”; cin>>x>>y;
  125. 125. xsqr=square(x); cout<<xsqr; ysqr=square(y); cout<<ysqr; } int square(int a) { return(a*a); }
  126. 126. float square(float a) { return(a*a); } getch(); } Friend Function Friend function are the functions that are used to have an access to the data members that are declared in a private category of a class. Friend
  127. 127. a special mechanism for letting a non-member function access private data. A friend function may be either declared are defined within the scope of a class definition. The keyword “friend” informs the compiler that is it not a member function of the class. The general syntax is:- friend return_type function_name(arguments); A friend function has the following characteristics:- • It is not in the scope of the class to which is has been declared as friend.
  128. 128. • Since it is not in the scope of the class, it cannot be called using the object of that class. • It can be invoked like a normal function without the help of any object. Usually it has the objects as arguments. • It can be declared either in private or public part of the class without affecting its meaning. • Unlike member function, it cannot access the member names directly and has to use an object name and dot membership operator with each member name (e.g a.x).
  129. 129. Program on Friend Function:- class sample { int x; public: void getdata(); friend void display(sample); }; void sample::getdata()
  130. 130. { cout<<“Enter a value of x”; cin>>x; } void display(sample s) { cout<<“Entered no. is”; cout<<s.x; cout<<endl;
  131. 131. } void main() { sample s; s.getdata(); display(s); getch(); }
  132. 132. Inline Functions It is used only in function declaration to give a hint to the compiler that inline substitution of the function body is to be preferred to usual function call implementation. Syntax:- class class_name { various sections
  133. 133. inline return_type functionname (argument list) } Advantages:- • The size of the object code is reduced. • The speed of execution is increased. • These are compact function calls.
  134. 134. Program on Inline Functions:- inline int mul(int x,int y) { return(x*y); } inline int div(int p,int q) { return(p/q);
  135. 135. } int main() { int a=9; int b=9; clrscr(); cout<<mul(a,b)<<“n”; cout<<div(a,b)<<“n”;
  136. 136. getch(); return 0; } Virtual Function A virtual function is one that does not really exist but it appears real in some parts of a program. When we use the same function name in both the base and derived classes, the function in base class is declared as virtual using the keyword ‘virtual’ preceding its normal declaration. To make a member function virtual, the
  137. 137. keyword virtual is used in the method while it is declared in the class definition but not in the member function definition. The compiler gets information from the keyword virtual that it is virtual function and not a conventional functional declaration. The general syntax of the virtual function declaration is: class class_name { private:
  138. 138. statements; public: virtual return_type function_name(arguments); }; For example: class base { public: void display()
  139. 139. { cout<<“Display base”; } virtual void show() { cout<<“Show base”; } }; class derived:public base
  140. 140. { public: void display() { cout<<“Display derived”; } void show() { cout<<“Show derived”;
  141. 141. } }; void main() { base b; derived d; base *ptr; ptr=&b; (*ptr).display();
  142. 142. (*ptr).show; ptr=&d; (*ptr).display(); (*ptr).show(); getch(); }
  143. 143. Chapter-5th
  144. 144. Class A class is a derived data type that groups related data items called data members and the functions called member functions that operate on data members. Syntax:- class class_name { private: data member declaration;
  145. 145. member function declarations; public: data member declarations; member function declarations; }; The variables declared inside the class known as data members and the functions are known as member functions. These functions and variables are collectively called class members. They are usually grouped under two sections:- Private and public.
  146. 146. Thus a class is a technique to bind the data and the associated functions together. This binding of data and functions in the form of a class is known as Encapsulation. The keywords private, protected and public are used to specify the three levels of access protection for hiding data and function members internal to the class. • Private scope:- In this section, a member data can only be accessed by the member functions and friends of this class. The member functions and friends of this class can always read or write
  147. 147. private data members. The private data members are not accessible to the outside world. •Protected scope:- In this section, a member data can only be accessed by the member functions and friends of this class. Also, these functions can be accessed by the member functions and friends derived from this class. It is not accessible to the outside worlds. • Public scope:- The members which are declared in the public section, can be accessed by any function in the outside world (out of the class).
  148. 148. Program:- class student { public: int rollno; char name[10]; void display() { cout<<“Enter your name”;
  149. 149. cin>>name; cout<<“n Enter your RollNo”; cin>>rollno; } }; void main() { student s; cout<<“Enter name and RollNo”;
  150. 150. cin>>; cin>>s.rollno; cout<<“ and s.rollno”; } void display() { cout<<“name”<<name; cout<<“Rollno”<<rollno; }
  151. 151. }; Defining Member Functions The member functions of a class are also called class functions. These functions may be defined in two ways:- • Inside the class declaration, called as inline functions. Example:- class item {
  152. 152. int number; float cost; public: void putdata(int a,int b) { cout<<“enter the values of a and b”; cin>>a>>b; } };
  153. 153. • Outside the class declaration, with function declaration in the class. Syntax:- datatype specifier classname:: functionname (List of arguments) { function body } 1. While defining a function outside the class, the function prototype must be declared within the class declaration.
  154. 154. 2. The appearance of class name before the function name allows a user to use identical function names for different classes, because the class name limits the scope of the function to the specified class. Nesting of Member Functions A member function of a class can be called only by an object of the class using a dot operator. However, there is an exception to this. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member function.
  155. 155. class set { int m,n; public: void input(); void display(); int largest(); }; int set::largest()
  156. 156. { if(m>=n) return(m); else return(n); } void set::input() { cout<<“Input values of m and nn”;
  157. 157. cin>>m>>n; } void set::display() { cout<<“nlargest value=“<<largest(); } int main() { set a;
  158. 158. a.input(); a.display(); return 0; } Static Data Members The static variables are automatically initialized to zero unless these are initialized explicitly. In C++, these are of two types I.e static data member and static member function. Properties of Static data members:-  The access rule of a static data member is
  159. 159. same as that of normal data member.  Whenever a static data member is declared it will be shared by all instance of the class.  The static data members should be created and initialized before the main function. Properties of static member function:-  It can manipulate only one the static data members of the class.  It acts as global for members of its class.  It can’t be a virtual function.
  160. 160.  It is also not a part of the objects of the class. Program on static data member:- class sample { static int count; public: sample(); void display(); };
  161. 161. int sample::count=0; sample::sample { ++count; } void sample::display() { cout<<“Counter value=“<<count<<endl; }
  162. 162. void main() { sample obj1,obj2; obj2.display(); } Program on Static member function:- class sample { static int count;
  163. 163. public: sample(); static void display(); }; int sample::count=0; sample::sample() { ++count; }
  164. 164. void sample::display() { cout<<count; } void main() { sample::display(); sample obj1,obj2,obj3; sample::display();
  165. 165. getch(); } Arrays of Objects An array can be of any data type including struct. Similarly, we can also have arrays of variables that are of the type class. Such variables are called arrays of objects. For Example:- class employee {
  166. 166. float age; public: void getdata(); void putdata(); }; void employee::getdata() { cout<<“Enter name:”; cin>>name;
  167. 167. cout<<“Enter age:”; cin>>age; } void employee::putdata() { cout<<“name:”<<name<<“n”; cout<<“age:”<<age<<“n”; } const int size=2;
  168. 168. int main() { employee manager[size]; for(int i=0;i<size;i++) { cout<<“nDetails of manager”<<i+1;<<“n”; manager[i].getdata(); } for(i=0;i<size;i++)
  169. 169. { cout<<“nManager”<<i+1<<“n”; manager[i].putdata(); } getch(); return 0; }
  170. 170. Memory Allocation For Objects We have stated that the memory space for objects is allocated when they are declared and not when the class is specified. This statement is only partly true. Actually, the member functions are created and placed in the memory space only once when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions, no separate space is allocated for member functions when the objects are created. Only space for member variables is allocated separately for
  171. 171. object. Separate memory locations for the objects are essential, because the member variables will hold different values for different objects. Objects As Function Arguments Like any other data type, an object may be used as a function argument. This can be done in two ways:  A copy of the entire object is passed to the function.  Only the address of the object is transferred to the function
  172. 172. The first method is called pass-by-value. Since a copy of the object is passed to the function, any changes made to the object inside the function do not affect the object used to call the function. The second method is called pass-by-reference. When an address of the object is passed, the called function works directly on the actual object used in the call. This means that any changes made to the object inside the function will reflect in the actual object. The pass-by-reference method is more efficient since it requires to pass only the address of the object and not the entire object.
  173. 173. Program on call-by-value:- void main() { int x,y; void swap(int,int); x=100; y=20; cout<<“Values before swap()”<<endl; cout<<“x=“<<x<<“and y=“<<y<<endl;
  174. 174. swap(x,y); //call by value cout<<“values after swap()”<<endl; cout<<“x=“<<x<<“and y=“<<y<<endl; } void swap(int x,int y) //values will not be swapped { int temp; temp=x;
  175. 175. y=temp; } Program on pass-by-reference:- void main() { int x,y; void swap(int *x,int *y); x=100; y=20;
  176. 176. cout<<“Values before swap()”<<endl; cout<<“x=“<<x<<“and y=“<<y<<endl; swap(&x,&y); //call by reference cout<<“values after swap()”<<endl; cout<<“x=“<<x<<“and y=“<<y<<endl; } void swap(int *x,int *y) //Values will be swapped { int temp;
  177. 177. temp=*x; *x=*y; *y=temp; } Returning Objects A function cannot only receive objects as arguments but also can return them. The example below illustrates how an object can be created (within a function) and returned to another function.
  178. 178. class complex { float x; float y; public: void input(float real,float imag) { x=real; y=imag;
  179. 179. } friend complex sum(complex,complex); void show(complex); }; complex sum(complex c1,complex c2) { complex c3; //object c3 is created c3.x=c1.x+c2.x; c3.y=c1.y+c2.y;
  180. 180. return(c3); //returns object c3 } void complex::show(complex c) { cout<<c.x<<“+j”<<c.y<<“n”; } int main() { complex A,B,C;
  181. 181. A.input(3.1,5.65); B.input(2.75,1.2); C=sum(A,B); //C=A+B cout<<“A=“;; cout<<“B=“;; cout<<“C=“;;
  182. 182. return 0; }
  183. 183. Chapter-6th
  184. 184. It is a special member function used for automatic initialization of an object. Whenever an object is created, the constructor will be executed automatically. It can be overloaded to accommodate many different forms of initialization. Syntax Rules for Writing Constructor Functions:- • Its name must be same as that of its class name. • It is declared with no return type (not even void).
  185. 185. •It may not be static and virtual. • It should have public or protected access within the class and only in rare circumstances it should be declared private. Syntax:- class username { private: -------- --------
  186. 186. protected: ---------- --------- public: username(); //constructor ---------- ---------- }; username::username()
  187. 187. { -------- ---------- } Program:- class sample { int m,n; public:
  188. 188. sample(int,int); void display(); }; sample::sample(int x,int y) { m=x; n=y; } void sample::display() {
  189. 189. cout<<m<<n; } void main() { sample s(100,20); s.display() getch(); }
  190. 190. Default Constructor It is special member function invoked automatically by C++ compiler without any arguments for initializing the objects of class. Syntax:- class username { private: --------
  191. 191. protected: ---------- --------- public: username(); //default constructor ---------- ---------- }; username::username() //without any arguments
  192. 192. { -------- ---------- } Program:- class student { private: char name[20];
  193. 193. long int rollno; char sex; float height; float weight; public: student(); //constructor void display(); }; student::student()
  194. 194. { name[0]=‘0’; rollno=0; sex=‘0’; height=0; weight=0; } void student::display() {
  195. 195. cout<<“name=“<<name<<endl; cout<<“rollno=“<<rollno<<endl; cout<<“sex=“<<sex<<endl; cout<<“height=“<<height<<endl; cout<<“weight=“<<weight<<endl; } void main() { student a;
  196. 196. cout<<“demonstration of default constructorn”; a.display(); } Copy Constructor These are always used when the compiler has to create a temporary object of a class. The copy constructors are used in the following situations:- 1. The initialization of an object by another object of the same class. 2. Return of objects as function value.
  197. 197. Syntax:- classname::classname(classname &ptr) Program:- class code { int id; public: code()
  198. 198. } code(int a) { id=a; } code(code &x) {; }
  199. 199. void display() { cout<<id; } }; void main() { code a(20); code b(a);
  200. 200. code c=a; a.display(); b.display(); c.display(); getch(); }
  201. 201. Destructor It is a function that is automatically executed when an object is destroyed. Its primary use is to release the scope that is occupied. It may be invoked explicitly by the programmer. Syntax Rules for writing Destructors:- 1. Its name is as that of its class expect it starts with the tilde(~). 2. It is declared with no return type. 3. It can’t be declared static.
  202. 202. 4. It takes no arguments and therefore can’t be overloaded. 5. It should have a public access. Syntax:- class classname { various sections classname(); //constructor ~classname(); //destructor
  203. 203. Program:- int count=0; class alpha { public: alpha() { count++; cout<<“no. of objects created<<count;
  204. 204. } ~alpha() { cout<<“no. of objects destroyed”<<count; count--; } }; int main() {
  205. 205. alpha a1,a2,a3,a4; { alpha a5; } { alpha a6; } cout<<“reenter main”; getch();
  206. 206. return 0; } Dynamic Initialization Of Objects Class objects can be initialized dynamically too. That is to say, the initial value of an object may be provided during run time. One advantage of dynamic initialization is that we can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the
  207. 207. Dynamic Constructors The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is allocated with the help of the new operator.
  208. 208. Chapter-7th
  209. 209. It is logical method of calling several functions with different arguments and data types that perform basically identical things by same name. Its main advantages are:- 1. Elimination of use of different function names for same operations. 2. Helps to understand, debug and grasp easily. 3. Easy maintenance of the code. The function declaration and function definition are essential for each function with same
  210. 210. name but different arguments. Function Overloading with Various Data Types:- It allows to use the same function name for various data types. The function declaration, definition and function call are done with the same name but different data arguments. The correct name will be selected by C++ compiler for comparing the types of actual parameters with formal parameters. Function Overloading with Arguments:-
  211. 211. arguments in the function call. Scoping Rules for Function Overloading :- The overloading mechanism is acceptable only within the same scope of the function declaration. The same function name in various classes is not said to be overloaded. The operator can also be overloaded that is they can be redefined. Its main advantages in a program is that it is much easier to read and
  212. 212. debug. Only predefined C++ operators can be overloaded. Syntax:- return_type operator operator-to-be operated(parameters) Example:- void operator++(); is equal to void increment();
  213. 213. Rules for Operator Overloading:- 1. Only predefined C++ operators can be overloaded. 2. Users can’t change any operator template i.e its use,template and precedence. 3. Overloading of an operator can’t change its natural meaning.
  214. 214. Unary Operator like (++,--) takes no formal arguments when overloaded by member functions. They take single arguments when overloaded by friend function. The assignment operator is also an unary operator because it is connected only to the entity on the right side. Whenever it is overloaded in a base class, it can’t be inherited in the derived class.
  215. 215. Program on Overloading Unary Minus:- class space { int x; int y; int z; public: void getdata(int a,int b, int c); void display();
  216. 216. void operator-(); //Overload Unary minus }; void space::getdata(int a,int b,int c) { x=a; y=b; z=c; } void space::display()
  217. 217. { cout<<x<<“ “; cout<<y<<“ “; cout<<z<<“n“; } void space::operator-() { x=-x; y=-y;
  218. 218. z=-z; } int main() { space s; s.getdata(10,-20,30); cout<<“s:”; -s; cout<<“s:”;
  219. 219. s.display(); getch(); return 0; } Program on Function Overloading:- void main() { int a,b; float x;
  220. 220. void area(int); void area(int ,int); void area(int,float); cout<<“Enter the side of square”; cin>>a; area(a); cout<<“n Enter the sides of rectangles”; cin>>a>>b; area(a,b);
  221. 221. cout<<“n Enter the sides of triangle”; cin>>a>>x; area(a,x); getch(); } void area(int b,float h) { float t; t=1/2*b*h;
  222. 222. cout<<“Area of Triangle=“; cout<<t; } void area(int l,int b) { int r; r=l*b; cout<<“n Area of Rectangle=“; cout<<r;
  223. 223. } void area(int f) { int s; s=f*f; cout<<“n Area of Square=“; cout<<s; }
  224. 224. In certain situations, some variables are declared as integers but sometimes it may be required to get the result as floating point numbers. The type conversions is to convert the set of declared type to some other required type. The assignment operator can be used for type conversions. The type of data to the right of an assignment operator is automatically converted to the type of the variable on the left. For Example:- int m; float x=3.14159;
  225. 225. m=x; convert x to an integer before its value is assigned to m. Thus the fractional part is truncated. The type conversions are automatic as long as the data types invalid are built-in- type The compiler does not support automatic type conversions for user-defined data types. Three types of situations might arise in the data conversions between incompatible type:- 1. Conversion from basic type to class type. 2. Conversions from class type to basic type.
  226. 226. 3. Conversions from one class type to another class type. Program on Overloading Binary Operators:- class complex { float x,y; public: complex(){} complex(float real,float imag)
  227. 227. x= real; y=imag; } complex operator+(complex); void display(); }; complex complex::operator+(complex c) { complex temp;
  228. 228. temp.x=x+c.x; temp.y=y+c.y; return(temp); } void complex::display() { cout<<x<<“+j”<<y; } void main()
  229. 229. { complex c1,c2,c3; c1=complex(2.5,3.5); c2=complex(3.6,2.1); c3=c1+c2; cout<<“c1=“; c1.display(); cout<<“c2=“; c2.display();
  230. 230. cout<<“c3=“; c3.display(); getch(); } Overloading Binary Operators using Friends class complex { float x; float y;
  231. 231. public: complex() {} complex(float real,float imag) { x=real; y=imag; } friend complex operator+(complex,complex);
  232. 232. void display(); }; complex operator+(complex c1,complex c2) { complex c3; c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return(c3); }
  233. 233. void complex::display() { cout<<c.x<<“+j”<<c.y; } void main() { complex A,B,C; A=complex(2.5,3.1); B=complex(6.2,1.9);
  234. 234. C=A+B; cout<<“A=“; A.display(); B.display(); C.display(); getch(); }
  235. 235. Chapter-8th
  236. 236. Inheritance is the process by which objects of one class acquire the properties of the objects of another class. Inheritance provides 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 will have the combined features of both the classes. The old class is referred to as the Base class and the new one is called as Derived class or subclass.
  237. 237. A derived class with only one base class is called as Single Inheritance. One class with several base classes is called Multiple Inheritance. The process of inheriting one class by more than one class is called as Hierarchical Inheritance. The process of deriving a class from another derived class is called as Multilevel Inheritance.
  238. 238. A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is: Syntax:- derivedclass:visibility mode baseclass { Members of derived class }
  239. 239. The colon indicates that the derived class name is derived from the base class name. The visibility mode is either private or public. By default visibility mode is private. For Example:- class abc:private xyz { members of abc }; class abc:public xyz
  240. 240. { Members of abc; }; When a base class is privately inherited by a derived class, public members of the base class become ‘private members’ of the derived class and therefore the public members of the base class can only be accesses by the members function of the derived class. They are inaccessible to the objects of the derived class. When base class is publicly inherited, public members of the base class become public
  241. 241. members of the derived class and therefore they are accessible to the objects of the derived class. Single Inheritance is the process of creating a number of new classes from an existing base class. The existing class is known as the direct base class and the newly created class is called as a singly derived class. Single Inheritance is the ability of a derived class to inherit the member function and variables of the existing base class. The General Syntax is:-
  242. 242. { members of the derived class }; Program On Single Inheritance:- class basic { private: char name[20]; int rollno;
  243. 243. public: void getdata(); void display(); }; class sample:public basic { private: float height; float weight;
  244. 244. public: void getdata(); void display(); }; void basic::getdata() { cout<<“Enter name and Rollno”; cin>>name>>rollno; }
  245. 245. void basic::display() { cout<<name<<rollno; } void sample::getdata() { cout<<“Enter height and weight”; cin>>height>>weight; }
  246. 246. void sample::display() { cout<<height<<weight; } void main() { sample s; s.getdata(); s.display();
  247. 247. The process of deriving a class from another derived class is called as Multilevel Inheritance. The class A serves as a base class for the derived class B and B serves as a base class for the derived class C. The class B is known as getch(); }
  248. 248. Intermediate base class since provides a link for the inheritance between A and C. The ABC chain is known as Inheritance Path. A derived class with Multilevel Inheritance is declared as:- class A { -------- }; class B:public A
  249. 249. { ---------- }; class C:public B { -------- };
  250. 250. Program on Multilevel Inheritance:- class student { protected: int rollno; public: void getnumber(); void shownumber(); };
  251. 251. void student::getnumber() { cout<<“Enter rollno”; cin>>rollno; } void student::shownumber() { cout<<rollno; }
  252. 252. class test:public student { protected: float sub1; float sub2; public: void getmarks(); void putmarks(); };
  253. 253. void test::getmarks() { cout<<“Enter sub1”<<endl; cin>>sub1; cout<<“Enter sub2”<<endl; cin>sub2; } void test::putmarks() { cout<<sub1<<sub2;}
  254. 254. class result:public test { private: float total; public: void display(); }; void result::display() {
  255. 255. total=sub1+sub2; shownumber(); putmarks(); cout<<“Total=“<<total; } void main() { result r; r.getnumber();
  256. 256. r.getmarks(); r.display(); getch(); }
  257. 257. A class can inherit the attributes of two or more classes. This is known as Multiple Inheritance. In other words, a class with several base classes is known as Multiple Inheritance. Multiple Inheritance allows us to combine the features of several existing class as a starting point for defining a new class. Syntax:- class D:visibility base1,visibility base2 {
  258. 258. body of D }; Program on Multiple Inheritance:- class m { protected: int m; public: void getm();
  259. 259. }; class n { protected: int n; public: void getn(); }; class p:public m,public n
  260. 260. { public: void display(); }; void m::getm() { cout<<“Enter m”; cin>>m; }
  261. 261. } void n::getn() { cout<<“Enter n”; cin>>n; } void p::display() { cout<<m<<endl;
  262. 262. cout<<n<<endl; cout<<m*n; } void main() { p p1; p1.getm(); p1.getn(); p1.display();
  263. 263. getch(); } The situation where all the three kinds of inheritance namely multilevel, multiple and hierarchical are invoked. The duplication of inherited members due to the multiple paths can be avoided by making the common base class as a Virtual Base Class while declaring the direct or intermediate base classes.
  264. 264. Grandparent Parent 1 Parent 2 Child Fig. Multipath Inheritance
  265. 265. The ‘child’ has two direct base classes ‘parent1’ and ‘parent2’ which themselves have a common base class ‘grandparent’. The ‘child’ inherits the traits of ‘grandparent’ via two separate paths. It can also inherit directly as show by the broken line. The ‘grandparent’ is sometimes referred to as indirect base class. Inheritance by the ‘child’ as shown in fig. Might pose some problems. All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first via ‘parent1’ and again via ‘parent2’. This means , ‘child’ would have duplicate sets of the members inherited from
  266. 266. ‘grandparent’. This introduces ambiguity and should be avoided. The duplication of inherited members due to these multiple paths can be avoided by making the common base class (ancestor class) as virtual base class while declaring the direct or intermediate base classes which is shown as follow: class A //grandparent { ------
  267. 267. --------- }; class B1:virtual public A //parent1 { --------- --------- }; class B2:public virtual A //parent2 {
  268. 268. -------- -------- }; class C:public B1,public B2 //child { ------- //only one copy of A ------- //will be inherited }; When a class is made a virtual base class, C++
  269. 269. that class is inherited, regardless of how many inheritance paths exist between the virtual base class and a derived class. Program on Virtual Base Classes:- class student { protected: int rollno; public: void getnumber()
  270. 270. { cout<<“Enter Rollno”; cin>>rollno; } void putnumber() { cout<<rollno; } };
  271. 271. class test:virtual public student { protected: float sub1,sub2; public: void getmarks() { cout<<“Enter sub1”; cin>>sub1;
  272. 272. cout<<“Enter sub2”; cin>>sub2; } void putmarks() { cout<<sub1<<sub2; } }; class sports: public virtual student
  273. 273. { protected: Float score; public: void getscore() { cout<<“enter score”; cin>>score; }
  274. 274. void putscore() { cout<<score; } }; class result:public test,public sports { float total; public:
  275. 275. void display(); }; void result::display() { total=sub1+sub2; putmarks(); putnumber(); putscore(); cout<<“total=“<<total;
  276. 276. } void main() { result r; r.getnumber(); r.getscore(); r.getmarks(); r.display(); getch(); }
  277. 277. An abstract class is one that is not used to create any objects. An abstract class is a class which consists of pure virtual functions. It is designed to act as a base class only (to be inherited by another classes). It is a design concept in program development and provides a base upon which other classes may be built. Program on Abstract Classes:- class base1 {
  278. 278. private: int x,y; public: virtual void getdata(); virtual void display(); }; class base2:public base1 { private:
  279. 279. int rollno; char name[20]; public: void getdata(); void display(); }; void base1::getdata() { }
  280. 280. void base1::display() { } void base2::getdata() { cout<<“Enter rollno and name”; cin>>rollno>>name; } void base2::display()
  281. 281. { cout<<rollno<<name; } void main() { base1 *ptr; base2 b; ptr=&b; (*ptr).getdata();
  282. 282. (*ptr).display(); getch(); } Inheritance can be used to modify a class when it did not satisfy the requirements of a particular problem on hand. Additional members are added through inheritance to extend the capabilities of a class. Another interesting application of inheritance is to use it as a support to the hierarchical; design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level.
  283. 283. Account Saving account Current account Fixed-deposit account Short-term Medium-term Long-term
  284. 284. There should be situations where we need to apply two or more types of inheritance to design a program. For instance, consider the case of processing the student results. Assume that we have to give weightage for sports before finalising the results. The weightage for sports is stored in a separate class called sports. The new inheritance relationship between the various classes would be as shown in fig. below.
  285. 285. Student Test Result Sports Fig. Multilevel, multiple inheritance
  286. 286. Program on Hybrid Inheritance:- class student { protected: int rollno; public: void getnumber(int a) { rollno=a;
  287. 287. } void putnumber() { cout<<“rollno=“<<rollno<<“n”; } }; class test:public student { protected:
  288. 288. float part1,part2; public: void getmarks(float x,float y) { part1=x; part2=y; } void putmarks() {
  289. 289. cout<<“marks obtained”<<“n”; cout<<“part1=“<<part1<<“n”; cout<<“part1=“<<part2<<“n”; } }; class sports { protected: float score;
  290. 290. public: void getscore(float s) { score=s; } void putscore() { cout<<“sports wt:”<<score<<“nn”; }
  291. 291. }; class result:public test,public sports { float total; public: void display(); }; void result::display() {
  292. 292. total=part1+part2+score; putnumber(); putmarks(); putscore(); cout<<total=“<<total<<n”; } int main() { result r;
  293. 293. r.getnumber(1234); r.getmarks(27.5,33.0); r.getscore(6.0); r.display(); getch(); return 0; }
  294. 294. The constructors play an important role in initializing objects. We did not use them earlier in the derived classes for the sake of simplicity. One important thing to note here is that, as long as no base class constructor takes any arguments, the derived class need not have a constructor function. However, if any base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors.
  295. 295. Note:- While applying inheritance we usually create objects using the derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor. When both the derived and base classes contains constructors, the base constructor is executed first and then the constructor in the derived class is executed. Program on Constructors in Derived Class class alpha { int x;
  296. 296. public: alpha(int i) { x=i; cout<<“alpha initializedn”; } void show_x() { cout<<“x= “<<x<<“n”;
  297. 297. } }; class beta { float y; public: beta(float j) { y=j;
  298. 298. cout<<“beta initializedn”; } void show_y() { cout<<“y= “<<y<<“n”; } }; class gamma:public beta,public alpha {
  299. 299. int m,n; public: gamma(int a,float b,int c,int d):alpha(a),beta(b) { m=c; n=d; cout<<“gamma initializedn”; } void show_mn()
  300. 300. { cout<<“m= “<<m<<“n”; cout<<“n= “<<n<<“n”; } }; int main() { gamma g(5,10.75,20,30); cout<<“n”;
  301. 301. g.show_x(); g.show_y();; getch(); return 0; }
  302. 302. Chapter-9th
  303. 303. Nesting of Classes Inheritance is the mechanism of deriving certain properties of one class into another. This is implemented using the concept of derived classes. C++ supports yet another way of inheriting properties of one class into another. This approach takes a view that an object can be a collection of many other objects. That is, a class can contain objects of other classes as its members as shown below: Syntax:- class XX
  304. 304. { private: int x1; int x2; public: void fun1(); void fun2(); }; class YY
  305. 305. { private: int y1; XX ox; //Object of class XX public: void funy(); }; Class YY has ox as one of it’s members. ox is an object of class XX. So you can have access to public members of class XX.
  306. 306. #include<iostream.h> #include<conio.h> #define PIE 3.14159 class circle { private: float radius; public: float area()
  307. 307. { float ar; cout<<“nRadius ?”; cin>>radius; ar=PIE*radius*radius; return(ar); } }; class cylinder
  308. 308. { private: circle c; //c is an object of class circle float height; public: float float volume() { float ar; float vol;
  309. 309. ar=c.area(); //Member function of class circle called cout<<“Height ?”; cin>>height; vol=ar*height; return(vol); } }; void main()
  310. 310. cylinder c; cout<<“Volume of the cylinder is “<<c.volume(); }
  311. 311. Chapter-10th
  312. 312. Polymorphism The word ‘Poly’ means many and the word ‘Morphism’ means form. Therefore it means many forms. It is a process of defining a number of objects of different classes into a group and call the methods to carry out the operation of the objects using different function calls. It treats objects of related classes in a generic manner. The keyword Virtual is used to perform the polymorphism concept in C++. Polymorphism refers to the run time binding to a pointer to a method.
  313. 313. Early Binding When function is chosen in a normal way,during the compilation time, it is called as Early Binding/Static Binding/Static Linkage. The compiler determines which function is to be used based on the parameters passed and the return type of function. In Early Binding, the function call is made4 from the base class pointer to access the members of the derived class. But the function call not reaches the derived class an the function of the base class are executed. It is because, the
  314. 314. member function of base class and derived class are declared non-virtual and C++ complier takes only the static Binding by default. C++ supports Polymorphism through virtual method and pointers. If the member function of the base and the derived class are made Virtual, then the functions of both the classes will be executed.
  315. 315. Late Binding Choosing functions during execution time is called as Late Binding or Dynamic Binding. Late Binding requires some overhead but provides increased power and flexibility. The Late Binding is implemented through Virtual functions. An object of a class must be declared either as a pointer to a class or a reference to a class. The keyword “Virtual” must be followed by return type of a member function if a run time is to be bound. It is called as Dynamic Binding because the selection of the appropriate function is done dynamically at run time.
  316. 316. Polymorphism Compile time polymorphism Run time polymorphism Function overloading Operator overloading Virtual functions
  317. 317. Pointers To Objects Object pointers are useful in creating objects at run time. We can also use an object pointer to access the public members of an object. We can access the member functions of a class in two ways • One by using the dot operator and the object. • Second by using the arrow operator and the object pointer.
  318. 318. Program to Pointers to Objects:- class item { int code; float price; public: void getdata(int a,float b) { code=a;
  319. 319. price=b; } void show() { cout<<“Code: “<<code<<endl; cout<<“Price: “<<price<<endl; } }; void main()
  320. 320. { item x; item *ptr; ptr=&x; ptr->getdata(100,25.7); ptr->show(); getch(); }
  321. 321. this Pointer A pointer is a variable that holds the memory address of another variable.”this” pointer is a variable that is used to access the address of the class itself. This unique pointer is automatically passed to a member function when it is called. The pointer “this” acts as an implicit argument to all the member function. When a binary operator is overloaded by means of member function, we pass only one argument to the function explicitly. The other argument is implicitly passed using the pointer “this”.
  322. 322. Program on this pointer:- class point { private: float x; float y; public: void getxy() {
  323. 323. cout<<“Coordinates of the point “; cin>>this->x>>this->y; //Accessing data members //through pointer this } void showxy() { cout<<“nX coordinate= “<<this->x; cout<<“nY coordinate= “<<this->y;
  324. 324. void where() { cout<<“nAddress of p is “<<this; //Displays the //address of object } }; void main() { point p;
  325. 325. p.getxy(); p.showxy(); p.where(); getch(); }
  326. 326. Pointers To Derived ClassesPointers To Derived Classes We can use pointers not only to the base objects but also to the objects of derived classes. C++ allows a pointer in a base class to point to either a base class object or to any derived class object. Therefore, a single pointer variable can be made to point to objects belonging to different classes. For example:- If B is a base class and D is derived class from B, then a pointer declared as a pointer to B can also be a pointer to D
  327. 327. Virtual FunctionsVirtual Functions A Virtual functions is one that does not really exist but it appears real in some parts of a program. When we use the same function name in both the base and derived classes, the function in base class is declared as Virtual using the keyword Virtual preceding its normal declaration. To make a number function Virtual, the keyword Virtual is used in the method while it is declared in the class definition but not in the member function definition. The compiler gets
  328. 328. information from the keyword Virtual that it is virtual function and not a conventional functional declaration. The general syntax of the Virtual function declaration is: class user_defined_name { private: statements; public:
  329. 329. Virtual return_type function_name(arguments); }; Rules for Virtual Functions:- They are accessed by using object pointers. A Virtual function can be a friend of another class. A Virtual function in a base class must be declared, even though it may not be used. We can’t have Virtual constructors, but can have virtual destructors.
  330. 330. If a Virtual function is defined in the base class, it need not be necessarily redefined in the derived class. In such cases, calls will invoke the base function. Program on Virtual Functions:- class base { public: void display() {
  331. 331. cout<<“Display base”; } Virtual void show() { cout<<“Show base”; } }; class derived:public base {
  332. 332. public: void display() { cout<<“Display derived”; } void show() { cout<<“Show derived”; }
  333. 333. }; void main() { base b; derived d; base *ptr; ptr=&b; (*ptr).display(); (*ptr).show();
  334. 334. ptr=&d; (*ptr).display(); (*ptr).show(); getch(); }
  335. 335. Pure Virtual FunctionsPure Virtual Functions A pure virtual function is a function that is only declared in the base class but have no definition relative that base class. A class containing such pure virtual function is called as abstract base class. These classes cannot be used to declare any objects of its own. For Example:- class base {
  336. 336. int x; float y; public: Virtual void getdata(); Virtual void display(); }; class derived:public base { int rollno;
  337. 337. char name[2]; public: void getdata(); void display(); }; void base::getdata() { } void base::display()
  338. 338. { } void derived::getdata() { cout<<“Enter name and rollno”; cin>>name>>rollno; } void derived::display() {
  339. 339. cout<<rollno; cout<<name; } void main() { base *ptr; derived d; ptr=&d; (*ptr).getdata();
  340. 340. (*ptr).display(); getch(); }
  341. 341. Program on Static Binding class square { protected: int x; public: void getdata(); void display();
  342. 342. int area(); }; class rectangle:public square { protected: int y; public: void getdata(); void display();
  343. 343. int area(); }; void square::getdata() { cout<<“Enter the value of side x”n”; cin>>x; }; void square::display() {
  344. 344. cout<<“Value of x=y= “<<x<<endl; cout<<“Area of the Square= “<<area(); cout<<endl; } int square::area() { int temp=x*x; return(temp); }
  345. 345. void rectangle::getdata() { cout<<“Enter the value of sides x and y?n” cin>>x>>y; } void rectangle::display() { cout<<“Value of x= “<<x<<“ and y= “; cout<<y<<endl;
  346. 346. cout<<“Area of the rectangle= “<<area(); cout<<endl; } int rectangle::area() { int temp=x*y; return(temp); } void main()
  347. 347. { square sq; rectangle rect; sq *ptr; ptr=&sq; ptr=&rect; ptr->getdata(); ptr->area(); ptr->display(); }
  348. 348. A program to illustrate the Dynamic binding of member functions of a class class base { private: int x; float y; public: virtual void getdata();
  349. 349. virtual void display(); }; class derived:public base { private: int rollno; char name[20]; public: void getdata();
  350. 350. void display(); }; void base::getdata() { cout<<“Enter an integern”; cin>>x; cout<<“Enter a real numbern”; cin>>y; }
  351. 351. void base::display() { cout<<“Entered numbers are x= “<<x<<“ and y= “<<y; cout<<endl; } void derived::getdata() { cout<<“Enter roll number of a student ?n”;
  352. 352. cout<<“Enter name of student?n”; cin>>name; } void derived::display() { cout<<“roll number student’s namen”; cout<<roll no<<‘t’<<name<<endl; } void main()
  353. 353. { base *ptr; derived d; ptr=&d; ptr->getdata(); ptr->display(); }
  354. 354. Pointers to Derived Classes class b { public: int x; void show() { cout<<“x= “<<x<<endl; };
  355. 355. class d:public b { public: int y; void show(){ cout<<“y =“<<y<<endl; cout<<“x= “<<x<<endl; } };
  356. 356. void main() { b *ptr; b bc; ptr=&bc; (*ptr).x=100; (*ptr).show(); d dc; ptr=&dc;
  357. 357. (*ptr).x=200; (*ptr).show(); d *ptr1; ptr1=&dc; (*ptr1).y=300; (*tr1).show(); getch(); }
  358. 358. Chapter-11th
  359. 359. IntroductionIntroduction Every program takes some data as input and generates processed data as output following the familiar input-process-output cycle. It is, therefore, essential to know how to provide the input data and how to present the results in a desired form. C++ supports a rich set of I/O functions and operations to do this. Since these functions use the advanced features of C++ (such as classes, derived classes and virtual functions), we need to know a lot about them
  360. 360. before really implementing the C++ I/O operations. C++ supports all of C’s rich set of I/O functions. We can use any of them in the C++ programs. But we restrained from using them due to two reasons. First, I/O methods in C++ support the concepts of OOP and secondly, I/O methods in C cannot handle the user-defined data types such as class objects. C++ uses the concept of stream and stream classes to implement its I/O operations with the console and disk files.
  361. 361. C++ StreamsC++ Streams A stream is a sequence of bytes. It acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides data to the program is called the input stream and the destination stream that receives output from the program is called the output stream. It other words, a program extracts the bytes from an input stream and inserts bytes into an output stream as illustrated in fig. below.
  362. 362. Input device Output device Program Input stream Output stream Extraction from input stream Insertion into output stream Fig. Data Streams
  363. 363. The data in the input stream can come from the keyboard or any other storage device. Similarly, the data in the output stream can go to the screen or any other storage device. A stream acts as an interface between the program and the input/output device. Therefore, a C++ program handles data (input or output) independent of the device used. C++ contains several pre-defined streams that are automatically opened when a program begins its execution. These include cin and cout which have been used very often in our programs. We know that cin represents the input stream
  364. 364. connected to the standard input device (usually the keyboard) and cout represents the output stream connected to the standard output (usually the screen). C++ Streams Classes The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal with both the console and disk files. These classes are called stream classes. Fig below shows the hierarchy of the stream classes used for input and output operations with the console unit. These classes are declared in the header file iostream. This file should be included in all the programs that communicate with the console unit.
  365. 365. ios istream streambuf ostream iostream istream_withassign iostream_withassign ostream_withassign pointer input output Fig. Stream classes for Console I/O operations
  366. 366. ios is the base class for istream (input stream) and ostream (output stream) which are, in turn, base classes for iostream (input/output stream). The class ios is declared as the virtual base class so that only one copy of its members are inherited by the iostream. The class ios provides the basic support for formatted and unformatted I/O operations. The class istream provides the facilities for formatted and unformatted input while the class ostream (through inheritance) provides the facilities for formatted output. The class iostream provides the facilities for handling both input and output streams.
  367. 367. UNFORMATTED I/O OPERATIONS Overloaded Operators >> and << We have used the objects cin and cout (pre- defined in the iostream file) for the input and output of data of various types. cout is used to display an object into standard device, normally the video screen. The insertion operators (the double less than <<) is used along with cout stream. The general syntax for cout is:- cout<<variable name;