P. 1
OOPs Lab Manual

OOPs Lab Manual

|Views: 3,521|Likes:
Published by kingraaja

More info:

Published by: kingraaja on Nov 18, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

07/10/2013

pdf

text

original

KALASALINGAM UNIVERSITY

(KALASALINGAM ACADEMY OF RESEARCH AND EDUCATION) ANAND NAGAR, KRISHNANKOIL – 626190.

Department of computer Science and Engineering

OBJECT ORIENTED PROGRAMMING LAB (CSE285)
LAB MANUAL

Prepared By, P.Deepalakshmi, Course Coordinator – CSE285.

Verified By, Dr.S.Radhakrishnan, HOD/CSE.

-1-

Table of contents
S.No 1 Topic Introduction 1.1 1.2 1.3 1.4 1.5 1.6 2 3 4 5 6 7 8 9 10 11 Object Oriented Programming Lab Objectives Tools Required Lab Plan Instructions to faculties Instructions to students Method of evaluation Page No 3 3 4 4 5 6 7 9 12 16 24 28 31 37 46 58 64 70 71 83 88

Simple C++ Programs Programs using functions Programs using classes Function overloading Operator overloading Inheritance Polymorphism and Virtual functions File Handling and I/O Manipulation Templates – Function and class templates Exception handling Appendix A – C++ reserved words Appendix B – C++ Programming Guidelines Appendix C – Sample Programs Reference

-2-

OBJECT ORIENTED PROGRAMMING LAB
LAB MANUAL 1. Introduction

CSE285

Programming language which serves as the intelligent of any computer systems has evolved tremendously since it was first developed. Currently, in most electronic devices ranging from mobile handset to washing machine even to cars have computer embedded system and thus requires some form of programming language to govern the operation of those devices. Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based on the real world. It utilizes several techniques from previously established paradigms, including modularity, polymorphism and encapsulation. Even though it originated in 1960’s, OOP was not commonly used in mainstream software application development until the 1990s. Today, many popular programming languages such as Java, JavaScript, C# , C++, Python support OOP. OOP may be seen as a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a collection of functions, or simple as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility. OOP is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods. C++ is one of the high-level language that is developed by Bjarne Stroustrup (http://www.research.att.com/~bs/homepage.html), of which is
-3-

actually C is a subset of C++. It is developed on basis of enabling object-oriented programming, where the students will learn and apply its concept in this subject.

1.1 Object Oriented Programming Lab Objectives
To provide the student with the fundamental knowledge and skills to become a proficient C++ programmer. To learn to transpose the physical problem domain into a hierarchy of objects. To develop ability of using OOP to solve simple engineering problems To work with advanced futures of C++ (templates, exception handling).

1.2 Tools Required
Hardware Requirement Pentium IV 512 MB RAM 20 GB Hard disk drive Software Requirement Windows 9x or above Turbo C++ compiler Microsoft Visual C++ 6.0

1.3 Lab Plan
Week # Lab Content Software Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++

Week 1 Simple C++ programs Week 2 Programs Using Functions Week 3&4 Programs using Classes ( Constructor, destructor, Friend Functions etc)

Week 5 Function Overloading Week 6 Operator Overloading Week 7 Simple and Multiple Inheritance Week 8 Multilevel and hybrid Inheritance

-4-

specifications of Equipment / Instruments / Software. Faculties shall assess the performance of students continuously. Explain prior concepts to the students before starting of each experiment. procedure. Know your Laboratory Work: To understand the layout of laboratory. working in groups. To knowrelated skills to be developed such as Intellectual skills. -5- . planning time etc. Faculties shall ensure that required equipments are in working condition before start of experiment. Faculties shall instruct the students to attempt all questions given at the end of each experiment / exercise.Week 9 Model Lab Exam # 1 Week 10 Virtual Functions Week 11 Polymorphism Week1 2 File Handling and I/O Manipulation Week 13 Templates – Function Templates and Class Templates Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++ Turbo C++ / VC++ VC++ VC++ Turbo C++ / VC++ Week1 4 Exception Handling Week 15 Model Lab Exam # 2 1. Also to knowtotal amount of work to be done in the laboratory. List of questions is given at the end of each experiment.4 Instructions to Faculties Learning Overview: To develop better understanding of importance of the subject. Faculties shall ensure that each student writes the answers to the allotted questions in the laboratory manual after performance is over. Faculties should ensure that the respective skills and competencies are developed in the students after the completion of the practical exercise. Involve student’s activity at the time of conduct of each experiment. also keep operating instruction manual available.

1. The student shall study all the questions given in the laboratory manual and practice to write the answers to these questions.Faculties are expected to share the skills and competencies to be developed in the students. -6- . Organize the work in the group and make a record of all programs. Faculties may suggest the students to refer additional related literature of the Technical papers / Reference books / Seminar proceedings. Read the write up of each experiment to be performed. Student should not hesitate to ask any difficulty faced during conduct of practical / exercise. etc. Understand the purpose of experiment and its practical implications. skills to be developed and procedure method of continuous assessment. During assessment faculties are expected to ask questions to the students to tap their achievements regarding related knowledge and skills so that students can prepare while submitting record of the practical. Listen carefully to the lecture given by teacher about importance of subject. tentative plan of work in laboratory and total amount of work to be done in a semester.5 Instructions to Students Students shall read the points given below for understanding the theoretical concepts and practical applications. curriculum philosophy. but immediately. algorithms. Faculties should enlist the skills to be developed in the students that are expected by the industry. a day in advance. Write the answers of the viva questions allotted by the teacher during practical hours if possible or afterwards. Faculties may provide additional knowledge and skills to the students even though not covered in the manual but are expected from the students by the industries. learning structure.

cpp. Algorithm Program . Student shall develop the habit of evolving more ideas. 2.4 marks -7- . Student should be well prepared while submitting the write up of the exercise. proceedings of the Seminars.6 Method of Evaluation For each Exercise (Out of 10 Marks) 1.on .2 Marks . Student should develop the habit of not to depend totally on teachers as well as their classmates but to develop self learning techniques. refer websites related to the scope of the subjects and update his knowledge and skills. Student shall attempt to develop related hands . 1. skills etc.skills and gain confidence. Student shall focus on development of skills rather than theoretical or codified knowledge. For loading C++.Student shall develop maintenance skills as expected by the industries. process is same as of C. exercise continuously and progressively on the scheduled dates and should get the assessment done. Student shall refer technical magazines. those included in the scope of the manual. innovations. Student should develop habit to submit the practical. While saving give extension as . Student should develop the habit of pocket discussion / group discussion related to the experiments / exercises so that exchanges of knowledge / skills could take place. Student should develop the habit to react with the teacher without hesitation with respect to the academics involved. This will develop the continuity of the studies and he will not be over loaded at the end of the term.

3. Output Answers to Viva Questions . 2. 4. Algorithm Program Output Viva Total Marks End Evaluation 1. 4. 3. Model Practical – I Model Practical – II End semester Practical Examination Total Marks 20 Marks 20 Marks 10 Marks 50 Marks 100 ---------------10 (5 for each) 40 (20 for each) 40 (20 for each) 10 _______ 100 _______ Record and Observation Maintenance - ---------------- -8- . 1.2 Marks For Model / End Semester Practical Examination Each student will be given two programs for lab examination. 2.2 Marks . 4. 3.

To get familiar in C++ form of input and output. Simple C++ Programs Aim To let the student experience coding.2. compiling and debugging some simple C++ programs. An electricity board charges the following rates to domestic users to discourage large conceptions of energy. structures and preprocessor statements. To get familiar in writing simple C++ programs using looping statements. arrays and preprocessors. Create a structure book with relevant information for maintaining a book. Write C++ programs that produce following outputs.50 p/unit All users are charged a minimum of Rs 50/-.50 p/unit Rs 1. structures. 2. 3. Instructions 1. number of units consumed and print out the Electricity bill in a neat format. Also print all the books details in a table format. i) A A B A B C A B C D -9- . Create an array of structure to hold a minimum of 5 book’s details. 2. Each student should do a minimum of 4 experiments by using looping statements. Faculties can suggest their own programs also to the students. List of Exercises 1. If the total amount is more than 300 then an additional surcharge of 15% of the calculated amount is added. arrays.80 p/unit From 100 to 200 units Beyond 200 Rs 2. First 100 units Rs 1. Write a c++ program to read the name of an user.

What is the basic difference between C and C++? 2. a variable can be declare anywhere in the scope. Name the C++ input and output statements. 4. i) sin (x) = x – (x3 / 3!) + (x5 / 5!) – (x7 / 7!) +……. Write a c++ program to find the cube of a square using preprocessor statements..0001% accuracy for n terms. Viva Questions 1. 7.. Write a C++ program to find the transpose of a given 3*3 matrix.ii) A B C D E AB CD AB C AB A 4. Write a C++ program that asks to enter any number and then prints the multiplication table of that number from 1 to 10.h> # include<conio. Write a C++ program to enter a matrix of 3*3 and check whether it is an identity matrix. What is the need for the directive # include<iostream. 8.h>? 7. In C++. 9. What is meant by dynamic initialization of a variable? 9. Write a C++ program to find all prime numbers between two given numbers. What are all the differences between C structure and C++ structure? 3. 6. What is the significance of this feature? 8.10 - . 5. What is the purpose of a # include statement? 6. ii) SUM = 1 + (1/2)2 + (1/3)3 + (¼)4 +…. Why an array is called a derived data type? and . Howdoes a main ( ) function in C++ differ from main ( ) in C? 5. Write a program to evaluate the following functions to 0.

Have a good idea of using looping statements Create. execute. loops and arrays. .10. What are the two types of comment styles in C++? 12.11 - . Knowthe input and output format of C++ language. What is the difference between using a break and using continue in a looping statement? Learning Outcome At the end of this experiment the students will Get familiar with basic C++ program format. What are the applications of void data type in C++? 11. and test C++ programs using calculations and decision statements.

or a goto exists. Default argument Default arguments assign a default value to the parameter. a switch. Eg : float amount(float principle.int period. The general form is inline function-header { function body } Situations where inline expansion cannot work. replaced by the statements that define the function. which does not have matching argument in the function call. It is expanded in line when it is invoked. • If functions contain static variables. call by address. Programs Using Functions Aim To make the students to get familiar in problem decomposition by using functions in C++ language. • If inline functions are recursive. • For functions not returning values.15) . float rate=0. To learn various parameter passing techniques like call by value.3. To know how to use inline functions. Default values are specified when the function is declared. default arguments and their significance in C++ programming Theory Inline function It is defined as a function definition such that each call to the function is in effect. if a return statement exists. • For functions returning values. call by reference to functions. if a loop.12 - .

No other initialization is permitted Only one copy of it is created for the entire class and is shared by all the objects It is only visible within the class.13 - .7.Function call is Value=amount(5000.//definition of static data member Static member function A member function that is declared as static has the following properties A static function can have access to only other static data member declared in the same class A static member function can be called only by using the classname as follows classname ::function_name. They are called as class variable because they are associated with the class itself rather than with any class object Features: It is initialized to zero when the first object is created. Here it takes principle=5000& period=7 And default value for rate=0. but its life time is the entire class Type and scope of each static member variable must be defined outside the class It is stored separately rather than along with objects Eg: static int count//count is initialized to zero when an object is created.7).15 Value=amount(5000.34) Passes an explicit value 0f 0. .34 to rate We must add default value from right to left Static data member Static variable are normally used to maintain values common to the entire class. int classname::count.0.

If a member function does not alter any data in the class. Multiplication of two complex numbers 9. 3. Write a C++ program using default arguments to find the simple interest using a function by pasting amount. Eg: const integer i(m. 8.n). Write a C++ program using inline functions to find and print the maximum of three numbers. Write a C++ program to swap two integer values using functions with call by value.14 - . Write a C++ program to find and print the volume of a cube using inline functions. Use function and array of structure to get the details . Write a C++ program using functions to get and print a 3*3 matrix. The default value for time is 1 year and that of rate of interest is 12%. Write a C++ program with a structure to store the student’s details like name. 6. 7. a. It const object can call const member functions. 5. height and weight. Use a default value of 2 for n to make the function to calculate squares when this argument is omitted. Write a C++ program to perform the following arithmetic operations of a complex number using a structure. 4.Const objects and const member functions We can create constant object by using const keyword before object declaration. Write a C++ program to input and output data for finding area of rectangle using functions. Write a C++ program using function to raise a number m (double) to a power n (int). time and rate of interest. Addition of two complex numbers b. then we may declare it as const member function as void mul(int . 2.int) const. List of Exercises 1. roll no. call by reference and call by pointers techniques.

Write the rules to use default arguments in a c++ program. What is inline function? 4. structures to functions learn the way of using default arguments .of 5 students. Mention the uses of default arguments. What is meant by function prototyping / function declaration and function definition? 2. List out the advantages of using functions in C++. 12. What are default arguments? 11. Learning Outcome At the end of this experiment the students will knowhowto use functions and inline functions in programs come to knowvarious parameter passing techniques learn howto pass arrays. What are all the differences between preprocessor statements and inline functions? 6. 3. Viva Questions: 1. When inline functions should not be used? 7. What are all the uses of reference variable? 9. What is reference variable? 8. Also include a function to sort them in an ascending order using the field height. Print the results in a neat format. Write the differences between reference variable and pointer variable? 10.15 - . What are all the advantages of inline function? 5.

16 - . Once a class has been defined. public: data members.4. . Program using Classes Aim To enhance the understanding of students about the underlying concepts of classes To demonstrate the approach to build classes and create object To learn the usage of constructors and destructors in classes Theory A class in C++ can be viewed as a customized ‘struct’ that encapsulates data and function as well. the function would not have to take trouble to ask for some data to be included in its argument list. a table of data or any item that the program has to handle. The entire set of data and code of an object can be made a user-defined data type with the help of a class. member_functions(). member_functions(). When we encapsulate data and function in one entity. but will still need to if it is required. a place. Objects are basic run-time entities in an object-oriented system. They may represent a person. Each object has the data and code to manipulate the data and theses objects interact with each other. most of the time. Classes are user-defined data types and behave like built-in types of the programming language Format of a class definition: class your_class_name { private : // access specifier data members. a bank account. we can create any number of objects belonging to the classes. }.

The properties or attributes of an object can be represented as data members in a class and its behaviors can be represented as member functions. the external properties and behaviors can be kept in the public function through which other part of the program will communicate with. b=y. Eg: class item { private: int a.b . The secret properties and behaviors can be kept in private section which can not be seen by remaining part of program. .int y) { a=x. } }. It is treated as inline function.17 - . Member functions can be defined in two ways Outside the class definition Member function can be defined outside the class by using scope resolution operator: General format: Return type class_name::function-name(arguments list) { //function body } Inside the class definition This method of defining member function is to replace the function declaration by the actual function definition inside the class. Whereas. public : void getdata(int x.

The constructor is invoked whenever an object of its associated class is created. public: integer( ) }//constructor { i = 10.Once the class has been declared. It is called constructor because it constructs the values of data members of the class Eg: Class integer { int i. function-name(actual arguments). invokes the default constructor. Parameterized constructor A constructor with arguments is called parameterized constructor. } }. eg : x . Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as class name. The constructors are of three types • Default Constructor • Parameterized Constructor • Copy Constructor Default Constructor The constructor with no arguments is called default constructor.75. we can create objects which are variables of that type by using the classname as follows Eg : classname x. The statement integer a. getdata(100. This will be automatically created if not specified in the program. Normally . //memory for x is created Then the public members of the class can be accessed as follows: object-name .18 - .5).

19 - . //calls default constructor To invoke parameterized constructor we must pass the initial values as arguments to the constructor function when an object is declared.By calling the constructor explicitly eg: eg: integer int1=integer(10.n=0. integer::integer( )//default constructor { m=0.these arguments will contain the initial values for data members. Copy constructor A copy constructor is used to declare and initialize an object from another object. integer(int x. }. } integer(const integer &i) { m = i.10). m = i. 2. } Invoking constructors integer a. class integer { int m.By calling the constructor implicitly To call copy constructor also we have two ways: . integer int1(10. This is done in two ways 1.n. public: integer( ).m.10).n=y.n } …….int y) // parameterized constructor { m=x. It takes a reference to an object of the same class as an argument Eg.

The memory is allocated with the help of the NEW operator. strcpy(str. Eg: class string { char *name. 2. integer i2(i1). name).20 - . The dynamic constructor can take any form of the above constructor. The compiler upon exit from the program will invoke it. Both the forms define the object i2 as well as time initialize it to the values of i1.1. integer i2 = i1. } Destructor It is used to destroy the objects that have been created by constructor. name3(Lagrange). Destructor name is same as class name preceded by tilde symbol(~) Eg. ~integer() { } A destructor never takes any arguments nor it does return any value. Dynamic constructor Allocation of memory to data members of objects at time of their construction is known as dynamic constructor. int length. void main( ) { string name1(“Louis”). public: string( char str[10]) { length=strlen(str). } }. Whenever new operator is . name=newchar[length +1].

Create two employee objects and display each object’s yearly salary using display function. It cannot access member names directly. A member function should display it. minutes. It can be declared either in the public or private part of a class. The final member function should add two objects of type time passed as arguments. Provide a get method for each instance variable.used to allocate memory in the constructor. A main ( ) program should create two initialized time objects. The general form is friend data_type function_name( ). Friend function is not in the scope of the class to which it has been declared as friend. in 11:59:59 format. 2. we should use delete operator to free that memory. a last name (type String) and a monthly salary (double). Create a class called time that has separate int member data for hours. and another should initialize it to fixed values. x ) List of Exercises 1. Usually it has objects as arguments. eg: ( A . . Friend functions A function that has access to the private member of the class but is not itself a member of the class is called friend functions. and (inside the class) Friend function is preceded by the keyword ‘friend’. Properties of friend functions. One constructor should initialize this data to 0. Give each employee a 10% raise using raise_salary function and display each Employee’s yearly salary again. Create a constructor in above class to initialize the three instance variables. It has to use an object name and dot membership operator with each member name.21 - . and second. Hence it cannot be called using the object of that class. Create a class called Employee that includes three pieces of information as instance variables – a first name (type String).

Create a class complex with real and imaginary as data members. Define a class to represent a bank account. 3. to add two complex number. Also include friend functions to add two complex numbers and multiply two complex numbers.one that isn’t initialized. Write a C++ program to implement the stack data structure using classes. Account number.(note that the statement s2=s1. Include the following members. will be perfectly reasonable expression to copy one string to another. Type of Account. Finally it should display the value of this third variable. Create a class complex with real and imaginary as data members. Define a class String that could work as a user-defined string type. Also include member functions to get the values for a complex number and to print the complex number in a+ib format. leaving the result in the third time variable. 5. 8. Data Members: Name of depositor. (string with length 0) and also to initialize an object with a string constant at the time of creation like String S2( Well done ). To withdraw an amount after checking the balance.22 - . 7. To deposit an amount. 4. Also include member functions to get the values for a complex number. 6. To display name and balance. Include constructors that will enable you to create an uninitialized string String S1. to print the complex number in a+ib format. Then it should add the two initialized values together. to multiply two complex numbers. Write a C++ program to count the number of objects created and destroyed for a class using stating data members and static member functions. . Include a function that adds two string to make a third string. Write a complete program to test your class to see that it does the following tasks: (a) Creates uninitialized string objects (b) Creates objects with string constants. . (Use new and delete operators). Balance amount in the account Member functions : To assign initial values.

30) 10. What is constructor? What is its role? Howdoes constructor differ from normal function? 4.23 - . What is the difference between writing the body of the function in side the class and outside the class? 6. Also include member functions to get. 10. What are friend functions and friend classes? 8. 11. Write a C++ program to depict the concept of friend class in C++.20. What is the basic difference between private and protected? 3. constant members and friend functions. Include necessary member functions to i) to get a vector ii) to add two vectors using friend function iii) to display a vector in the form (10. . Write a C++ program with a class “Pixel” to represent a Cartesian coordinate system. Viva Questions 1. Write a c++ program with a class to represent Vector. What is this pointer? Write its uses. What is the basic difference between class and structure? 2.9. 9. Learning Outcome At the end of this experiment the students will be able to solve any real world problem with concept of classes learn the usage of constructors and destructors Know the ways of using static members. Write the various access types of class members. Write the need for destructor. print and to move (both coordinates by +10) using this pointer. State the uses of static members and constant members. What is data hiding? What is encapsulation? 5. 7.

Function Overloading Aim To understand the fundamentals of function overloading Theory Function overloading is a feature of C++ that allows us to create multiple functions with the same name. C++ will know we mean to call Add(int. because the parameters are different than any other version of Add(). // floating point version Which version of Add() gets called depends on the arguments used in the call — if we provide two ints. double). int nY. Consequently. C++ will know we mean to call Add(double. int nY). } double Add(double dX.5. so long as each Add() function has unique parameters. double dY) { return dX + dY. so long as they have different number and different type of parameters. we can define as many overloaded Add() functions as we want. } We nowhave two version of Add( ): Function Call int Add(int nX. If we provide two floating point numbers.24 - . int nZ) { return nX + nY + nZ. double dY). int). this is valid. In fact. it’s also possible to define Add() functions with a differing number of parameters: int Add(int nX. int nY) { return nX + nY. Consider the following functions: int Add(int nX. // integer version double Add(double dX. } Even though this Add() function has 3 parameters instead of 2. .

C++ tries to find a match through standard conversion. Making a call to an overloaded function results in one of three possible outcomes: 1) A match is found. 2) No match is found. C++ tries to find a match through user-defined conversion. The call is resolved to a particular overloaded function. C++ goes through the following process to determine which version of the function will be called: 1) First. if a function call matches multiple candidates via standard conversion or user-defined conversion. 3) If no promotion is found. The arguments can not be matched to any overloaded function. an ambiguous match will result.Note :The function’s return type is NOT considered when overloading functions. void Print(float fValue). Standard conversions include: 4) Finally. Ambiguous matches If every overloaded function has to have unique parameters. we covered how certain types can be automatically promoted via internal type conversion to other types. When an overloaded function is called. This is the case where the actual argument exactly matches the parameter type of one of the overloaded functions. For example: void Print(unsigned int nValue). C++ tries to find a match through promotion. To summarize. . and all user-defined conversions are considered equal. C++ tries to find an exact match. In the lesson on type conversion and casting. For example: 2) If no exact match is found. 3) An ambiguous match is found. how is it possible that a call could result in more than one match? Because all standard conversions are considered equal. The arguments matched more than one overloaded function.25 - .

to have Print(0) call the Print(unsigned int). 3. you would do this: Print(static_cast<unsigned int>(0)). but there is no Print(int) either. Print(3. as most programmers would assume it matches Print(float). 0 is an int. Consequently. Consequently. C++ applies the matching rules to each argument in turn. Print(3. In the case of Print('a'). C++ can not find an exact match. It matches both calls via standard conversion. Because all standard conversions are considered equal.14159 is a double. Ambiguous matches are considered a compile-time error. it matches both calls via standard conversion. 2) Alternatively. explicitly cast the ambiguous parameter(s) to the type of the function you want to call.14159). // will call Print(unsigned int) Multiple arguments If there are multiple arguments. Then C++ will be able to find an exact match for the function call. For example.Calls Print('a'). and there is no Print(double). Using a standard conversion.26 - . There are two ways to resolve ambiguous matches: 1) Often. an ambiguous match needs to be disambiguated before your program will compile. with at least one argument matching better than all the other functions. The function chosen is the one for which each argument matches at least as well as all the other functions. Print(0) is similar. the best way is simply to define a new overloaded function that takes parameters of exactly the type you are trying to call the function with. this is an ambiguous match. Print(0). In other words. It tries promoting ‘a’ to an int. it can convert ‘a’ to both an unsigned int and a floating point value.14159) might be a little surprising. But remember that all literal floating point values are doubles unless they have the ‘f’ suffix. the function chosen must provide a better . and there is no Print(int).

27 - . In the case that such a function is found. Write a C++ program to swap two integers. . 2. Write a C++ program to find the area of a square and rectangle using function overloading. 2. What are the syntactic rules governing the definition of function overloading. the call will be considered ambiguous (or a non-match). List out the advantages of function overloading. cone and a rectangle using function overloading. the students will be able to Understand the concept of function overloading Learn howambiguity is handled in function overloading. floats. and no worse for all of the other parameters. If no such function can be found. it is clearly and unambiguously the best choice. Write a C++ program to find the volume of a cube. Learning outcome At the end of this exercise. Viva Questions 1.match than all the other candidate functions for at least one parameter. List of Exercises 1. characters and two strings suing function overloading concept. Hence function overloading can lower a programs complexity significantly while introducing very little additional risk. 3.

c=a+b. The behavior of various operator on such user define data types can be specified using operator functions. Op is the operator being overloaded. C++ has the ability to provide the operators with a special meaning for a data type.e. The general form is return type classname :: operator op(op-arglist ) { function body } where return type is the type of value returned by specified operation. Which one is easier to use.. i. Operator functions are either member functions or friend functions. Limitation on operator overloading . classes. Operator Overloading Aim To understand the fundamentals of operator overloading To understand the differences between overloading as member function and non-member friend function Theory Need for operator overloading If we compare the following syntaxes to perform addition of two objects a and b of a user defined class number (assume this class has a member function called add() which adds two fraction objects): 1 2 c=a. operator op is the function name. The op is preceded by a keyword operator. This mechanism of giving such special meanings to an operator is known as Operator overloading. Operator overloading It is needed to make operation with user defined data type.28 - . It provides a flexible option for the creation of new definitions for C++ operators.add(b). can be performed concisely.6. line 1 or 2? Obviously option 2 is easier.

as non member non friend function List of Exercises In all the following experiments. multiplication using operator overloading with member functions. addition. Write a C++ program to perform matrix addition. The precedence of the operator is preserved. []. subtraction. does not change. Write a C++ program to perform matrix addition. multiplication using operator overloading with member functions. as non member friend function 3. Write a C++ program to perform complex number addition. i. Can not create newoperator Operators =.Although C++ allows us to overload operators. as member function 2. with overloading operators There are many ways of performing operator overloading. . +. () and -> can only be defined as members of a class and not as friend or global functions The arity or number of operands for an operator may not be changed.29 - . 3. namely: 1. subtraction. Write a C++ program to perform complex number addition. multiplication using operator overloading with friend functions. 1.. it also imposes restrictions to ensure that operator overloading serves its purpose to enhance the programming language itself. without compromising the existing entity. subtraction. 4. multiplication using operator overloading with friend functions. 2.e. may not be defined to take other than two arguments regardless of data type. For example. The followings are the restrictions: Can not change the original behavior of the operator with built in data types. >> operator overloading functions for print and input of the members of class. subtraction. use <<.

the students will Be familiar in operator overloading in C++ Learn how to overload operators using member functions and friend functions. 7. Overload unary minus operator i) Using member function ii) Using friend function. . What are the limitations of overloading unary increment/ decrement operator? 4. 8. *=. Give justifications. Viva Questions 1. Write a C++ program to check this. 3. What is operator overloading? State the importance of operator overloading? 2. Learning Outcome At the end of this experiment. 9. Define a class space that represents three dimensional coordinate system. For Integer class. Create a class Integer that contains one integer data member. -=.5. Why? 5. 6. List the operators that can’t be overloaded. List the operators that can be overloaded with only member functions. Write a C++ program to overload newand delete operators for the string class.30 - . Overload all possible relational operators (using member functions and using friend functions) so that they operate on he objects of Integer. Write a C++ program to overload all arithmetic assignment operator (+=. /=) for the complex number class using friend functions and member functions. Write the difference between overloading operators using friend functions and member functions. overload post as well as pre increment and decrement operators.

The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. etc. OOP is proposed as a means to increase the efficiency of software developments.e. Features or Advantages of Inheritance: Reusability: Inheritance helps the code to be reused in many situations. (mango. protected access specifier and the sequence of constructor and destructor calls Theory Initially.. Inheritance Aim To understand the fundamentals of inheritance To develop skills on howto use inheritance to simplify development of new classes To understand some concepts such as overridden function. Once a class is developed reliably. a programmer can create a base class named fruit and define derived classes as mango. The base class is defined and once it is compiled. without needing to “reinvent the wheel”. orange would have its own defined features. One of its benefits is promoting software/program reuse. orange. banana. Using the concept of inheritance. after went through all sorts of possible verification processes. orange. banana. it need not be reworked. It can be used right away.31 - .) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes.7. etc. Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. Mango would have its own defined features. . i. etc. Each of these derived classes. it can be used everywhere. banana would have its own defined features. For example. the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed.

Indirect inheritance: inheritance relationship where the derived class inherit indirectly from its base class. class Car and class Vehicle have direct inheritance relationship. Polymorphism (to be discussed in detail in later sections) Important terminologies: Base class: a class which is inherited from by other classes.g. class Vehicle is the base class for all other classes. Increases Program Structure which results in greater reliability.g.. class Vehicle is the base class for all other classes. classes Truck. E. Vehicle Truck Car Bus MPV Sedan Honda Civic Nissan Preside Base class: a class which is inherited from by other classes..Saves Time and Effort: The above concept of reusability achieved by inheritance saves the programmer time and effort. Class Sedan is base class for classes Honda Civic and class Nissan President.g. E. Derived class: a class which inherits from base class (es).. Class Sedan is base class. Car and Bus are derived classes from base class Vehicle.. . Direct inheritance: inheritance relationship where the derived class inherit directly from its base class. E. since the main code written can be reused in various situations as needed.g. E.32 - .

Private Inheritance Protected in derived class can be accessed directly by all non-static member functions and friend functions Protected in derived class can be accessed directly by all non-static member functions and friend functions Hidden in derived class. Single inheritance: a derived class inherits from a single base class.g. class Honda Civic and class Car have indirect inheritance relationship. another member access specifier called ‘protected’ is provided to enable its members accessible directly from: within the class scope friend functions . protected. Protected Inheritance Private in derived class can be accessed directly by all non-static member functions and friend functions Private in derived class can be accessed directly by all non-static member functions and friend functions Hidden in derived class. friend functions and non member functions Protected in derived class can be accessed directly by all non-static member functions and friend functions Hidden in derived class. Can be accessed by nonstatic member function and friend functions through public or protected member functions of base class Protected Private Protected Data Member Since private class members are accessible from within class scope (by member functions of the same class) and friend functions. namely private. public There are three types of inheritance. protected and public inheritances. all examples in above Fig.E. We can observe from following table that different types of inheritances have different effect on how members of the base class can be accessed from the derived classes. Type of inheritance: private. Can be accessed by nonstatic member function and friend functions through public or protected member functions of base class.33 - ..g. E. Base class member access specifier Public Type of Inheritance Public Inheritance Public in derived class can be accessed directly by any non-static member functions.. Can be accessed by nonstatic member function and friend functions through public or protected member functions of base class. are single inheritance Multiple inheritance: a derived class inherits from more than one base classes.

In addition to the members inherited from Circle. General syntax for multiple inheritance: Derived_class_name : type_of_inheritance1 Base_class_name1.…{ } . 2. Create a class publication that stores the title and price. A data member that stores the radius of a circle A constructor function with an argument that initializes the radius A function that computes and returns are of a circle Create two derived classes Sector and Segment that inherit the Circle class.34 - . Write a main function to test the book and tape classes. Create a Circle class with following members. A data member that stores the control angle of a sector(in radians) 2. A constructor function with arguments that initialize radius and angle 3. Imagine a publishing company that market s both book and audio-cassette versions of its work. book includes one more property: page numbers and tape contains its length in minutes (float). Sector and Segment have some specific members as follows: Sector 1. List of Programs 1. Both classes inherit radius and the function that returns the circle’s are from Circle. From this class derive two classes book and tape. type_of_inheritance2 Base_class_name2. A function that computes and returns the area of a sector Segment 1.derived classes friend functions of derived classes General syntax for single inheritance: Derived_class_name : type_of_inheritance Base_class_name{ } . Each of these classes must have getdata ( ) functions and putdata ( ) functions to input/output its data. A data member that stores the length of a segment in a circle 2. A constructor function with arguments that initialize radius and length .

Note :Area_of_circle = r2 Area_of_Sector=r2θ/2 Area_of_segment=r2 arccos((r-h)/r) – (r-h)(2rh-h2)1/2 Where r os the radius of a circle. In main create and object for CEO class and call its functions. salary. The result class contains Total and average of the marks obtained in five subjects. The Boss class contains bonus information and CEO class contains shares that he owns information. Inherit the properties of Student and Text class details in Result class through multiple inheritance. 4. name. Test class contains marks for five subjects. Test and Result classes. The student class contains student relevant information. A function that computes and returns the area of a segment Create the main () function to instantiate an object of each class and then call appropriate member functions to compute and return the area of a circle.3. Create three classes Student. Include AskInfo( ) and writeInfo( ) functions in all the classes. h is the length of a segment and arccos((r-h)/r) is in radians. Create three classes Employee. Test class contains marks for five subjects. . The result class contains Total and average of the marks obtained in five subjects. Inherit the properties of Student and Text class details in Result class through multilevel inheritance. The student class contains student relevant information. department. Note : CEO is a boss and boss is an employee. public and protected access specifiers for declaring class members for a base class. Viva Questions 1. Test and Result classes. θ is the central angle of a sector in radians. What area the implications of using private. employee no. Use scope resolution operator in CEO functions to call Employee and Boss functions. 5. 3.35 - . Create three classes Student. Boss and CEO. Employee class stores basic details like. sector and segment.

4. What are the advantages offered by inheritance? 8. What are the different forms of inheritance? Give example.36 - .2. which can’t be inherited. Describe the base class access control mechanism. What is the firing order of the constructors under multiple and multilevel inheritance. the students should be able to write c++ programs: • using the concepts of inheritance • using inheritance as a tool for code reuse • calling base-class constructors and member functions • Implementing all types if inheritances. Learning Outcome After performing this lab. 7. 3. . What is method overriding? 5. 6. Mention the members of base classes. Write the need for protected visibility specifier to a class member.

8. Polymorphism & Virtual Functions
Aim To learn the difference between inheritance and polymorphism To understand the mechanism of polymorphism through virtual function To understand the concept of an abstract base class Theory Polymorphism is the ability to use an operator or function in different ways. Polymorphism gives different meanings or functions to the operators or functions. Poly, referring to many, signifies the many uses of these operators and functions. A single function usage or an operator functioning in many ways can be called polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different contexts. Polymorphism refers to the ability to call different functions by using only one type of function call. Polymorphism is a powerful feature of the object oriented programming language C++. A single operator + behaves differently in different contexts such as integer, float or strings referring the concept of polymorphism. The above concept leads to operator overloading. The concept of overloading is also a branch of polymorphism. When the exiting operator or function operates on new data type it is overloaded. This feature of polymorphism leads to the concept of virtual methods. Static Binding vs. Dynamic Binding Binding means the actual time when the code for a given function is attached or bound to the function call. Static Binding Actual code is attached during compile time. Implementing function overloading Dynamic Binding Actual code will be attached during run-time/execution time Implementing virtual functions

- 37 -

What are Virtual Functions? Virtual, as the name implies, is something that exists in effect but not in reality. The concept of virtual function is the same as a function, but it does not really exist although it appears in needed places in a program. The objectoriented programming language C++ implements the concept of virtual function as a simple member function, like all member functions of the class. The functionality of virtual functions can be over-ridden in its derived classes. The programmer must pay attention not to confuse this concept with function overloading. Function overloading is a different concept and will be explained in later sections of this tutorial. Virtual function is a mechanism to implement the concept of polymorphism (the ability to give different meanings to one function). Need for Virtual Function: The vital reason for having a virtual function is to implement a different functionality in the derived class. For example: a Make function in a class Vehicle may have to make a Vehicle with red color. A class called Four Wheeler, derived or inherited from Vehicle, may have to use a blue background and 4 tires as wheels. For this scenario, the Make function for FourWheeler should nowhave a different functionality from the one at the class called Vehicle. This concept is called Virtual Function. Properties of Virtual Functions: Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also simple member functions. The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. A non-virtual C++ member function is resolved during compile time or static binding. Virtual Functions are resolved during run-time or dynamic binding • Dynamic Binding Property: • Virtual functions are member functions of a class.

- 38 -

• Virtual functions are declared with the keyword virtual, detailed in an example below. • Virtual function takes a different functionality in the derived class. Declaration of Virtual Function: Virtual functions are member functions declared with the keyword virtual. General syntax class classname //This denotes the base class of C++ virtual function { public: virtual void memberfunctionname() //This denotes the C++ virtual function { ............. ............ } }; Referring back to the Vehicle example, the declaration of Virtual function would take the shape below: class Vehicle //This denotes the base class of C++ virtual function { public: virtual void Make() //This denotes the C++ virtual function { cout <<"Member function of Base Class Vehicle Accessed"<<endl; } }; After the virtual function is declared, the derived class is defined. In this derived class, the newdefinition of the virtual function takes place. When the class FourWheeler is derived or inherited from Vehicle and defined by the virtual function in the class FourWheeler, it is written as: class Vehicle //This denotes the base class of C++ virtual function { public: virtual void Make() //This denotes the C++ virtual function { cout <<"Member function of Base Class Vehicle Accessed"<<endl;

- 39 -

} }; class FourWheeler : public Vehicle { public: void Make() { cout<<"Virtual Member function of Derived class FourWheeler Accessed"<<endl; } }; void main() { Vehicle *a, *b; a = newVehicle(); a->Make(); b = newFourWheeler(); b->Make(); } In the above example, it is evidenced that after declaring the member functions Make() as virtual inside the base class Vehicle, class FourWheeler is derived from the base class Vehicle. In this derived class, the new implementation for virtual function Make() is placed. The programmer might be surprised to see the function call differs and the output is then printed as above. If the member function has not been declared as virtual, the base class member function is always called because linking takes place during compile time and is therefore static. In this example, the member function is declared virtual and the address is bounded only during run time, making it dynamic binding and thus the derived class member function is called. To achieve the concept of dynamic binding in C++, the compiler creates a v-table each time a virtual function is declared. This v-table contains classes and pointers to the functions from each of the objects of the derived class. This is used by the compiler whenever a virtual function is needed. C++ Pure Virtual Function and Virtual Base Class Pure Virtual Function is a Virtual function with no body.
- 40 -

} }. void main() { Exforsys* arra[2]. class Exf2:public Exforsys { public: void example() { cout<<"To Training". Exf1 e1. //Denotes pure virtual Function Definition }. } }. class Exf1:public Exforsys { public: void example() { cout<<"Welcome". refer to this example: class Exforsys { public: virtual void example()=0. Exf2 e2. the programmer must add the notation =0 for declaration of the pure virtual function in the base class.41 - . . arra[0]=&e1. General Syntax of Pure Virtual Function takes the form: class classname //This denotes the base class of C++ virtual function { public: virtual void virtualfunctioname() = 0 //This denotes the pure virtual function in C++ }.Declaration of Pure Virtual Function: Since pure virtual function has no body. To understand the declaration and usage of Pure Virtual Function.

The notation =0 simply indicates the Virtual function is a pure virtual function as it has no body. there are two derived classes Exf1 and Exf2 from the base class Exforsys. The pointers should point to the base class Exforsys. the Training class is derived from both of the derived classes Exf1 and Exf2. arra[0]->example() and arra[1]->example() would result in an error. Special care must be taken not to remove the statement of declaration of the pure virtual function in the base class. In this scenario. Virtual Base Class In the following example. As shown in the above diagram. the pure virtual function example() is declared with notation =0 in the base class Exforsys.42 - . accessing statements of the pure virtual function such as. the output is as in the above example. Two objects named e1 and e2 are defined for derived classes Exf1 and Exf2. } Since the above example has no body. arra[0]->example().arra[1]=&e2. The pure virtual function example() takes up new definition. a list of pointers is defined to the base class. One must clearly understand the concept of pure virtual functions having no body in the base class and the notation =0 is independent of value assignment. The two derived class named Exf1 and Exf2 are derived from the base class Exforsys. The address of the objects e1 and e2 are stored in the array pointers which are then used for accessing the pure virtual function example() belonging to both the derived class EXf1 and EXf2 and thus. arra[1]->example(). if a user has a member function in the class Training where the user wants to access . Without the declaration of the pure virtual function in the base class. We may want to remove this pure virtual function from the base class as it has no body but this would result in an error. In the main function.

This means that each of the subobjects have Exforsys member data and member functions and each have one copy of member data x.public Exf2 { public: int example() { return x. }. class Exf1:public Exforsys { }.the data or member functions of the class Exforsys it would result in error if it is performed like this: class Exforsys { protected: int x. class Training:public Exf1. When the member function of the class Training tries to access member data x.43 - . This results in an error because the derived classes Exf1 and Exf2 (derived from base class Exforsys) create copies of Exforsys called subobjects. The above program results in a compile time error as the member function example() of class Training tries to access member data x of class Exforsys. } }. class Exf2:public Exforsys { }. confusion .

} }. class Training:public Exf1. both Exf1 and Exf2 are created as Virtual base classes by using the keyword virtual.arises as to which of the two copies it must access since it derived from both derived classes. Write a C++ main ( ) function to check this. resulting in a compile time error. class Exf1:virtual public Exforsys { }. 2. average fuel consumption per 100 km and the .public Exf2 { public: int example() { return x. class Exf2:virtual public Exforsys { }. 3. For Example: class Exforsys { protected: int x. Create two more classes Rectangle and Triangle which inherit Shape class. Make the print data function as virtual function in base class. List of Programs 1. In the above example. When this occurs. Create a base class Shape with relevant data members and member functions to get data and print the area. Virtual base class is used. }. Both of the derived classes Exf1 and Exf2 are created as virtual base classes. meaning they should share a common subobject in their base class.44 - . Design a vehicle class that contains the following properties of motor vehicles: Fuel tank capacity. This enables them to share a common subobject of their base class Exforsys. Write a C++ program to implement virtual destructor concept. This results in only one copy that the member function example() of Class Training can access the member data x.

What are pure virtual functions? Howthey differ from normal virtual functions? 3. as well as the distance each vehicle can travel on a full tank. • A function that computes and returns how many times a vehicle has to be refueled to travel a given distance. . Viva Questions 1. The pointer should be used to invoke appropriate member functions to get and process data for car and truck.distance a vehicle can travel on a full tank. • A function that contains data for a vehicle from the user • A function that computes and returns the distance a vehicle can travel on a full tank.45 - . What are the merits and demerits of using pure virtual functions? Learning Outcome At the end of this exercise. What id meant by compile time binding and run time binding? 7. 5. The derived classes should have following member functions. Design the main ( ) function that instantiates a pointer of Vehicle Type and . What is polymorphism? 6. 2. These functions should be used as pure virtual functions in the Vehicle class and refined by the derived classes. What is mean by abstract class? 4. The program should output how many time each vehicle has to be refueled to travel the distance entered by the user. The vehicle class should be designed as an abstract base class from which the Car and Truck classes are derived. Car and Truck object respectively. Justify the need for virtual functions in C++. the students will know • To identify the need for virtual functions in a program • Howto use the concept of abstract classes • Howpolymorphism work with c++. Write the role of virtual destructors.

cout<<”C++”. To open and close a file programmatically To read from a file. endl Manipulator: This manipulator has the same functionality as the ‘\n’ newline character. setfill Manipulator: This is used after setw manipulator. File Handling and I/O Manipulation Aim To understand and use various member functions for C++ formatted I/O. If a value does not entirely fill a field. produces the output: C C++ setw Manipulator: (available in iomanip. to process the data and to write back again to the file Theory Manipulator Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer’s choice of display.46 - . Manipulators are the most common way to control output formating. then the character specified in the setfill argument of the manipulator is used for filling the fields. cout << setw(10) << setfill('$') << 50 << 33 << endl . The syntax is: setw(x) Here setw causes the number or string that follows it to be printed within a field of x characters wide and x is the argument set in setwmanipulator.h) This manipulator sets the minimum field width on output. Example: cout<<”C”<<endl. To understand and use stream manipulators for C++ formatted I/O.9.

So the remaining 8 positions are filled with $ symbol which is specified in the setfill argument. This means that three digits after the decimal point and in fixed notation will output the first cout statement as 0. setprecision Manipulator: The setprecision Manipulator is used with floating point numbers. This may be used in two forms: fixed and scientific. left Left justifies output in field width.100 1. float x = 0. cout << sceintific << x << endl.1.47 - . The second cout produces the output in scientific notation. width(n) Same as setw(n).100. cout << fixed << setprecision(3) << x << endl. The keyword scientific before the setprecision manipulator prints the floating point number in scientific notation. The default value is used since no setprecision value is provided.000000e-001 The first cout statement contains fixed notation and the setprecision contains argument 3. It is used to set the number of digits printed to the right of the decimal point. output: 0. . Only useful after setw(n). These two forms are used when the keywords fixed or scientific are appropriately used before the setprecision manipulator.Output $$$$$$$$5033 This is because the setw sets 10 width for the field and the number 50 has only 2 positions in it. The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation.

operates on the stream. 7 Inserts a null (0) character. cout << Sets the conversion base to n (0. >> cin setbase(n) To use predefined manipulators. Other Manipulators Predefined Manipulator 1 Cout << dec. ostream&. Plain manipulator--Takes an istream&. There are two basic types of manipulator: 1. cout << flush Invokes ostream::flush(). and then returns its argument. setbase(n). 16 only). User defined manipulators. or ios& argument. operates on the stream. cin >> hex cout << oct. Useful when dealing with strstreams. 8. cin Make the integer conversion base 8. 2. Since this is the default. 10. Parameterized manipulator--Takes an istream&. or ios& argument. cin >> dec 2 Cout << ends 3 4 5 6 Description Makes the integer conversion base 10. Cout << hex. one must include the file iomanip. ostream&.right Right justifies output in field width. File Manipulations in C++ . Only useful after setw(n). one additional argument (the parameter).48 - . and then returns its stream argument. >> oct cin >> ws Extracts whitespace characters (skips whitespace) until a non-whitespace character is found (which is left in istr). Makes the integer conversion base 16. it is only used to override the effects of left.h in your program.

ios::app ios::trunc . All output operations are performed at the end of the file. and ostream.49 - . If the file opened for output operations already existed before. If this flag is not set to any value. the initial position is the beginning of the file. Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened. in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. Open in binary mode. Open for output operations. appending the content to the current content of the file. Open a file An open file is represented within a program by a stream object (an instantiation of one of these classes.C++ provides the following classes to perform output and input of characters to/from files: • • • ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files. Set the initial position at the end of the file. Syntax open (filename. This flag can only be used in streams open for output-only operations. and mode is an optional parameter with a combination of the following flags: ios::in ios::out ios::binary ios::ate Open for input operations. These classes are derived directly or indirectly from the classes istream. its previous content is deleted and replaced by the new one. mode).

The default value is only applied if the function is called without specifying any value for the mode parameter. myfile. . ios::out | ios::app | ios::binary). Each one of the open() member functions of the classes ofstream.50 - .All these flags can be combined using the bitwise operator OR (|). if we want to open the file example. ios::out | ios::app | ios::binary). these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. and some translations may occur due to formatting of some special characters (like newline and carriage return characters).open ("example. For example.bin". Non-binary files are known as text files. Therefore. ios::in and ios::out are automatically and respectively assumed. not combined. we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing: ofstream myfile ("example.bin in binary mode to add data we could do it by the following call to member function open(): ofstream myfile. Since the first task that is performed on a file stream object is generally to open a file.bin". File streams opened in binary mode perform input and output operations independently of any format considerations. If the function is called with any value in that parameter the default mode is overridden. ifstream and fstream has a default mode that is used if the file is opened without a second argument: class default mode parameter ofstreamios::out ifstream ios::in fstream ios::in | ios::out For ifstream and ofstream classes. even if a mode that does not include them is passed as second argument to the open() member function.

For example in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left. In order to do that we have to call the stream's member function close(). or false otherwise: if (myfile. In case that an object is destructed while still associated with an open file. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file. the stream object can be used to open another file. and what it does is to flush the associated buffers and close the file: myfile. To check if a file stream was successful opening a file.close().51 - . . eof( ) Returns true if a file open for reading has reached the end. like when an alphabetical character is extracted when we are trying to read an integer number.Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent. This member function takes no parameters. Once this member function is called. the destructor automatically calls the member function close(). fail( ) Returns true in the same cases as bad(). but also in the case that a format error happens. proceed with output */ } Closing a file When we are finished with our input and output operations on a file we shall close it so that its resources become available again. you can do it by calling to member is_open() with no arguments. and the file is available again to be opened by other processes. Checking state flags bad( ) Returns true if a reading or writing operation fails.is_open()) { /* ok.

and cerr (error output. such as appending to the end of an existing file. fp_in. but the program will continue running for a while longer.txt". we can use the member function clear ( ).txt".open("myfile.close(). and then re-open the file for output. as there may be a limit on howmany you can have open at once. It is also a good idea if you intend to open a file for input. . // declarations of streams fp_in and fp_out ofstream fp_out. or specifying that a file is binary for operating systems (e. which also goes to the terminal). ios::in). // open the streams fp_out. it may be possible to specify a variety of other mode options. MS-DOS) which distinguish binary and ASCII files. fp_in.close(). ios::out).txt". Depending on the implementation of C++.good( ) It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true. File streams are of type ifstream (input) or ofstream (output). ifstream fp_in.open("myfile. which takes no parameters. Declaring the pointer and opening the file can be combined: ifstream fp_in("myfile. triggering an error rather than overwriting an existing file. // close the streams fp_out.g. // declare and open The parameters ios::in and ios::out specify the mode in which the file is to be opened.52 - . A file should be closed if you are done with it. This is particularly important when you intend to open a lot of files. ios::in). Header files Getting a stream Three streams just exist: cout (terminal output). cin (terminal input). In order to reset the state flags checked by any of these member functions.

WARNING: when reading data into a character string. floats). it can be used as the test in an if statement or a while loop.. not by value. The extraction operator works for numbers (ints. (You must include the iomanip header file. the items can be read easily using the extraction operator >>. cin >> mystring. the end of the file). newlines). However. the C++ compiler will not complain. float myfloat. char mychar. void myfunction(ifstream &fp.53 - . . . char mystring[64]. The extraction operator returns a zero value if it encounters a problem (typically. int myinteger.. cin >> myfloat. To avoid problems. Item by item input and output If each input item is surrounded by whitespace (blanks. fp_in >> myinteger. use the operator setw to force excessively long input to be broken up.. and strings (declared as arrays of type char or pointers to type char).) // use this void myfunction(ifstream fp.) // not this If you pass streams by value. char *mystring.Passing streams to functions File streams must be passed to functions by reference.) The input to setw should be the length of your string (including the null character '\0' at the end of the string). mysterious bad things will start happening. fp_in >> mychar. Therefore. bad things will happen if the input word is longer than your string. // input from file pointer or standard input // two ways to declare a string // declarations . tabs. often in parts of the code which don't appear to be related to the offending function. characters (char)..

Similarly. particularly if you are producing the output bit-by-bit (e.g.cin >> setw(length) >> mystring. you can use a cast to convince C++ to print an integer as the corresponding character. A flush can be forced by calling the flush function associated with . Forcing all buffered output to actually be printed is known as "flushing" the stream. cast it to the type (void *). characters. Buffering and flush When you send output to a stream. or the standard error using the insertion operator <<. cout << (char)ival. and strings can be written to a file.g. Rather. Numbers. cout << (int)ch.54 - . However.g. e. it is a nuisance for output used in debugging (e. Buffering makes it faster to print a large amount of output. or exit from program. cast it to type int. a statement that informs you that step 3 of your algorithm has been finished). To insert a line break. it may wait in a buffer until some unspecified event. reading from input. it does not necessarily get printed immediately. cout << "My string is " << mystring << " plus a null character\n" << flush. cout << "Value of myinteger " << myinteger << endl. To make a pointer print out as a pointer. The details may vary. cout << (void *)ptr. not as whatever type of data it points to. one character at a time). standard output. To make a character print as a number. buffer full enough. either insert the magic variable endl or write the endof-line character ('\n') to the output.

fp_in.each output stream.read(char *buffer. e. These operations all return zero if something goes wrong. which is zero if it encountered a problem (e.g.getline(char *buffer.putback(char ch) Puts character ch back onto the stream. getline.get(char &ch) Puts the next input character in the variable ch. fp_in.ignore(int n) Remove the next n characters (or until end of file) from the input stream. or read command. cout << endl. they can be used as the condition in an if statement or while loop. or inserting endl.g.55 - . inserting the magic variable flush into the stream. they hit the end of the file. cout. int n) Reads n bytes (or until the end of the file) from the stream into the buffer.flush(). Bad things will happen if this character is not the one most recently extracted from the stream. cout << flush. int length) Reads characters into the string buffer. stopping when (a) it has read length1 characters or (b) when it finds an end-of-line character ('\n') or the end of the file. . Stores a null character ('\0') after the last character read. Other input operations ifstream fp_in. end of file). Therefore. fp_in. fp_in.gcount() Returns the number of characters read by a preceding get. throwing them away into the Great Bit Bucket. Returns an integer value. fp_in. cin.

// forget we hit the end of file fp_in. Other output operations ofstream fp_out. This is done as follows: fp_in. Repositioning and error states In general. if at all. Write a c++ program to create a sequential file and to write 20 random integer numbers in the range 0 to 50 in that file. it is possible to move to any position in a file stream. This is a capability most programmers use rarely. ios::beg). Returns the next character in the stream. Returns the next character in the stream but does not remove it from the stream. fp_in. reading them from the string str. Create a user defined manipulator for displaying the details of employees in a neat table format.write(char *str.56 - . The output of these functions should be put into an integer (not a char) variable. don't try to use repositioning operations on the standard input.clear(). so that you can read its contents again. // move to the start of the file . all numbers < 20 from that file. fp_out. (Hint: Employee details can be maintained as array of structures). there are two more input operations. or error streams. These functions return EOF (which is secretly -1) if they encounter the end of the file. Nowcheck the file and display on screen. fp_in. The most likely reason for using a repositioning command is to rewind a file to the start.get( ) . For fairly obvious reasons. Other options for writing data to an output stream are: fp_out.seekg(0.In addition. get and peek. 2.peek( ).put(char ch) Puts ch onto the stream. output. List of Exercises 1. int n) Puts n characters onto the stream.

humidity and barometric pressure for one month. and average values of the temperature. _________________________________________ NAME Turbo c++ C++ Primer CODE 1001 21 COST $$$$250. Viva Questions 1. What are the different types of errors that might pop-up while processing files? 6.00 ________________________________________ _________________________________________ 4. What is file mode? Describe the various file mode options available. Describe the approaches used to detect end-of-file condition. Produce the following output. book code and book cost from user interactively. the students will be able to Work with stream i/o manipulators Will knowhowto create user defined manipulators Will knowhowto open. humidity and barometric pressure data tat are recorded in the file. Write a C++ program to open two files containing integers (in sorted order) and merge their contents.95 $$$$$$5. 5. What is the difference in using manipulators and ios functions? 3. 5.57 - . It should then open the file for reading and compute and displays the largest. process and close a text file.3. 4. Write a c++ program to read a list containing book name. Write a C++ program to copy the contents of one text file to another text file. 6. Design a program which first creates this file. smallest. . A file is required to record a city’s daily temperature. What are the differences between sequential and random files? Learning Outcome At the end of this experiment. What is a stream? 2.

one can write searching and sorting routines which can be used with any arbitrary type.Templates Function Templates and Class Templates Aim To learn about generic programming To knowhowto implement function templates and class templates Theory Templates are very useful when implementing generic constructs like vectors. Class Templates A class template definition looks like a regular class definition. } int push(const T&). T* stackPtr . For example. except it is prefixed by the keyword template.1 . queues which can be used with any arbitrary type. and the containers have been implemented as class templates. lists. C++ provides two kinds of templates: class templates and function templates. int isEmpty()const { return top == -1 . }. int pop(T&) . } private: int size . ~Stack() { delete [] stackPtr . . For example. template <class T> class Stack { public: Stack(int = 10) . C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code. int top .10. stacks. } int isFull() const { return top == size . Use function templates to write generic functions that can be used with arbitrary types.58 - . here is the definition of a class template for a Stack. The Standard Template Library generic algorithms have been implemented as function templates. // number of elements on Stack.

b <float> bf .H" void main() { b<int> bi .59 - . For example. At this point the compiler has the declarations but no definitions! Using a class template Using a class template is easy. ~b() . At this point the compiler does not need to generate any definitions for template classes.H" template <class t> b<t>::b() { } template <class t> b<t>::~b() { } //MAIN. even though int and Message* are not "classes".H template <class t> class b { public: b() . . Stack<Token>.cpp. T does not have to be a class type as implied by the keyword class. //B.T is a type parameter and it can be any type. // B. where Token is a user defined class. }. The declarations and definitions need to be in the same header file. Create the required classes by plugging in the actual type for the type parameters. the compiler has both the declarations and the definitions available.cpp. For example. This process is commonly known as "Instantiating a class".CPP # include "B.CPP # include "B. Implementing class template member functions Implementing template member functions is somewhat different compared to the regular class member functions. The declarations and definitions of the class template member functions should all be in the same header file. there are two instantiations: template class B<int> and B<float>. Consider the following. } When compiling B. When the compiler compiles main. Stack<int> and Stack<Message*> are valid instantiations. since there are no instantiations.

one can use the typedef name. The STL algorithms are implemented as function templates. # include <iostream> using namespace std . use function templates. char) and max(float. //max returns the maximum of the two elements . for example: the call max(10. } Using Template Functions Using function templates is very easy: just use them like regular functions. the compiler automatically instantiates separate object code functions to handle each type of call appropriately.Example typedef Stack<float> FloatStack . There are two advantages: Function Templates To perform identical operations for each type of data compactly and conveniently. Then throughout the program. # include <iostream> using namespace std .60 - . Similarly the compiler generates definitions for max(char. 15) in function main. You can write a single function template definition. Here is a sample with a function template. int). the compiler generates a function max(int. When the compiler sees an instantiation of the function template. //max returns the maximum of the two elements template <class T> T max(T a. float) in this case. FloatStack fs(5) . except they are prefixed with the keyword template. Implementing Template Functions Function templates are implemented like regular functions. T b) { return a > b ? a : b . A good programming practice is using typedef while instantiating template classes. Based on the argument types provided in calls to the function.

For example. 15) = " << max(10. 15. X<A>. 15) << endl . A static data member generated from a static data member template is called a generated static data member. cout << "max(10. } void main() { cout << "max(10. or even an entire class (possible template class). A function generated from a function template is called a generated function. function or static data members from a template. friend void f1() .2) << endl . cout << "max('k'. and X<Y>.1.61 - .1. Class Template template class <T> class X friend declaration in class template X Results of giving friendship makes f1() a friend of all instantiations of template X. 15. • The compiler generates a class. } Template Instantiation When the compiler generates a class. The table below lists the results of declaring different kinds of friends of a class. T b) { return a > b ? a : b . it is referred to as template instantiation.template <class T> T max(T a. function or static data members from a template when it sees an implicit instantiation or an explicit instantiation of the template. Templates and Friends Friendship can be established between a class template and a global function. .2) = " << max(10. • • A class generated from a class template is called a generated class. 's') = " << max('k'. f1() is a friend of X<int>. a member function of another class (possibly a template class). 's') << endl .

friend C<T>::f5(X<T>&) .. Write a function template for finding the minimum value contained in an array. C<float>::f5(x<float>&) cannot be a friend of class X<A>. template class <T> class X friend class Z<T> . Write a C++ program to represent a stack data structure using class template. and X<Y>. X<A>. float. makes A::f4() a friend of all instantiations of template X. d. all members of class Z<float> become friends of template class X<float>. For example. Write a class template to represent generic vector include member function to perform following tasks. such as a float. For a particular type T for example. To multiply by scalar value. float. f2(x<float>&) cannot be a friend of class X<A>. List of Exercises 1.62 - . makes every member function of class Y a friend of every template class produced from the class template X.template class <T> class X friend void f2(X<T>&) . 2. // C is a class template with a member function f5 template class <T> class X template class <T> class X friend class Y . makes C<float>::f5(X<float>&) a friend of class X<float> only. To display the vector in the form (a..c. c. when a template class is instantiated with a particular type T. // A is a user defined class with a member function f4() . a. template class <T> class X friend A::f4() .b.) . makes f2(X<float>&) a friend of class X<float> only. b. For a particular type T for example. 2. A::f4() is a friend of X<int>. To modify the value of given element. To create a vector.

Howthe compiler processes calls to a function template? 3. the students will be able to Understand the need for generic programming Knowhowto develop C++ program using class template and function template . What is meant by generic programming? 2.63 - . Distinguish between overloaded function and function template. Howthe compiler processes calls to a class template? 4.Viva Questions 1. Learning Outcome At the end of this experiment.

A throw expression accepts one parameter (in this case the integer value 20). which is passed as an argument to the exception handler. Exception handlers are declared with the keyword catch. This is done by enclosing that portion of code in a try block.64 - . The catch format is similar to a regular function that always has at least one parameter. which must be placed immediately after the try block: int main ( ) { try { throw20. an exception is thrown that transfers the control to the exception handler. } catch (int e) { cout << "An exception occurred. " << e << endl.11. Theory Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. As you can see. it follows immediately the closing brace of the try block. A exception is thrown by using the throw keyword from inside the try block. Exception Nr. If no exception is thrown. the code continues normally and all handlers are ignored. is 20. } return 0. The . To catch exceptions we must place a portion of code under exception inspection. } Here An exception is occurred and its exception Number. When an exceptional circumstance arises within that block. The code under exception handling is enclosed in a try block. The exception handler is declared with the catch keyword. Exception Handling Aim To understand the importance of fault tolerance in programming To learn howto handle exceptions .

This can be used as a default handler that catches all exceptions not caught by other handlers if it is specified at last: try { // code here } catch (int param) { cout << "int exception".. It is also possible to nest try-catch blocks within more external try blocks. that handler will catch any exception no matter what the type of the throwexception is. } catch (. not after the throw statement!. } .) { out << "Exception occurred". After an exception has been handled the program execution resumes after the try-catch block. each one with a different parameter type. we have the possibility that an internal catch block forwards the exception to its external level.) as the parameter of catch.. since the type of the argument passed by the throw expression is checked against it. In these cases..) { cout << "default exception". } catch (char param) { cout << "char exception". the exception is caught.. } In this case the last handler would catch any exception thrown with any parameter that is neither an int nor a char. Only the handler that matches its type with the argument specified in the throw statement is executed.type of this parameter is very important.. } } catch (. This is done with the expression throw. with no arguments.65 - . We can chain multiple handlers (catch expressions). If we use an ellipsis (.. and only in the case they match. For example: try { try { // code here } catch (int n) { hrow.

} } myex. either directly or indirectly. operators and destructors. The only exception that this function might throw is an exception of type int.Exception specifications When declaring a function we can limit the exception type it might directly or indirectly throwby appending a throwsuffix to the function declaration: float myfunction (char param) throw (int). // standard exceptions #include <iostream> #include <exception> using namespace std. It is called exception and is defined in the <exception> header file under the namespace std. plus an additional virtual member function called what that returns a null-terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of the exception. // all exceptions allowed . this means the function is not allowed to throw exceptions. Standard exceptions The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. If this throw specifier is left empty with no type. it cannot be caught by a regular int-type handler. If it throws an exception with a different type. This declares a function called myfunction which takes one argument of type char and returns an element of type float. // no exceptions allowed int myfunction (int param).66 - . class myexception: public exception { virtual const char* what() const throw() { return "My exception happened". Functions with no throw specifier (regular functions) are allowed to throwexceptions with any type: int myfunction (int param) throw(). This class has the usual default and copy constructors.

" << endl.67 - . } return 0. } . } catch (exception& e) { cout << e. } catch (bad_alloc&) { cout << "Error allocating memory. like our myex object of class myexception. } We have placed a handler that catches exception objects by reference (notice the ampersand & after the type). therefore this catches also classes derived from exception.what() << endl. if we use the operator new and the memory cannot be allocated. All exceptions thrown by components of the C++ Standard library throw exceptions derived from this std::exception class.int main () { try { throw myex. These are: exception bad_alloc bad_cast description thrown by newon allocation failure thrown by dynamic_cast when fails with a referenced type bad_exception thrown when an exception type doesn't match any catch bad_typeid thrown by typeid ios_base::failure thrown by functions in the iostream library For example. an exception of type bad_alloc is thrown: try { int * myarray= new int[1000].

On my system. which is what happens when this type of exception is thrown and not caught. Write a C++ program to process memory allocation error using exception handling mechanism. default catch block and rethrowing exceptions for your own problem situation. 6. Design two functions with an exception-specification lists as follows: a) A function which can throwonly an integer exception b) A function which can throwonly a string exception Design a main( ) function with a try block that is used to test and handle exceptions thrown by these two functions. What should be placed inside a catch block? 4. 5. When memory allocation fails. Viva Questions 1.It is recommended to include all dynamic memory allocations within a try block that catches this type of exception to perform a clean action instead of an abnormal program termination. When do we use multiple catch handlers? . trying to allocate 1 billion ints threwa bad_alloc exception. Write a C++ program to find the roots of a quadratic equation. 4. howdoes the newoperator notify the error to the caller? 3. Write a C++ program to handle divide by zero exception. 3. Why should we rethrowan exception? 5. Throwan exception whenever an imaginary root is found.68 - . List of Exercises 1. Write C++ programs handle multiple catch block. 2. you can try to allocate a huge array. What happens when a raised exception is not handled by a catch block? 2. If you want to force a bad_alloc exception to see it in action. Write a C++ program to handle array out of bound exception.

69 - . the students will be able to Knowhowto handle the exception in C++ language1 Howto rethrowthe exception Howto handle exception using functions.Learning Outcome At the end of this experiment. .

Token and and_eq bitand bitor compl not not_e or or_eq xor xor_eq && &= & | ~ ! != || |= ^ ^= .Appendix A: C++ Reserved Words C++ reserves some words for its own use in the libraries.70 - Meaning . Reserved words are classified into three categories: C++ Keywords asm catch continue dynamic_cast extern goto mutable protected return static_cast throw typename void auto char default else false if public short struct true union volatile bool class delete enum float inline register signed switch try unsigned wchar_t break const do explicit for int operator reinterpret_cast sizeof template typedef using case const_cast double export friend long private while static this typeid virtual namespace new Alternative Tokens Alternative tokens are the equivalences of operators at the right side of the following list. These words have special “meaning” to the compiler and therefore can not be used as identifiers in a declaration statement.

In this way. use function overloading and default arguments to create an intuitive. Then focus on the code that will be changed.71 - . If class users don’t need to access a function. don’t fix it if it isn’t broken). given the existence of a magic “piece” that handles the hard parts. If you do have a large body of C code that needs changing. provide a function interface rather than expose the actual data. always using functions rather than data. Attempt to make your names so clear that comments are unnecessary. Don t automatically rewrite all your existing C code in C++ unless you need to significantly change its functionality (that is. That “piece” is an object – write the code that uses the object. etc. taking C code that works fine and rewriting it in C++ may not be the best use of your time. keep everything as private as possible. To this end. When you create a class. make it private. Refactoring it into classes to facilitate easy modifications as your maintenance proceeds.Appendix B: Programming Guidelines Remember the divide and conquer principle. first isolate the parts of the code that will not be modified. try to imagine what the basic operation of the program would be. easyto-use interface. unless the C++ version will provide a lot of opportunities for reuse as a class. Access control allows you (the class creator) to change as much as possible in the future without damaging client code in which the class is used. then look at the object and encapsulate its hard parts into other objects. RecompilingC in C++ is a valuable activity because it may reveal hidden bugs. In this light. make your names as clear as possible. implementation . Your goal should be to make the client programmer’s interface conceptually simple. and make only the class interface public. However. possibly wrapping those functions in an “API class” as static member functions. If the problem you’re looking at is too confusing. Make data public only when forced. If a part of your class must be exposed to inheritors as protected.

put that code into a single function in the base class and call it from the derived-class functions. chances are it’s doing too much and should be broken up. You can use an inline function for efficiency. Don’t fall into analysis paralysis. Make classes as atomic as possible. Watch for long member function definitions. this is a fact of life that many design methods don’t account for. it should be broken up into multiple functions. the classes in your system. that is. If you see such a function. let them work for you. Your analysis and design must produce. ask yourself if all the pieces produced by that methodology have value over the lifetime of the program. and/or pass objects in as arguments. maintaining them will cost you. break complex classes into simpler ones. Members of development teams tend not to maintain anything that does not contribute to their productivity. it indicates that. There are some things that you don’t learn until you start coding and get some kind of system working. Watch for long argument lists. and is probably trying to do too much all by itself. Instead. at minimum. If your classes or your system design grows too complicated. give each class a single. C++ has built-in firewalls. read and maintain. If they do not. A function that is long and complicated is difficult and expensive to maintain. at the least. and their relationships to other classes. If your design methodology produces more than that. clear purpose. try to move the member function to a class where it is (more) appropriate. Not only do you save code space. their public interfaces. The most obvious indicator of this is sheer size: if a class is big. Don t repeat yourself. It may also suggest the creation of a newclass.72 - . . If a piece of code is recurring in many functions in derived classes. you provide for easy propagation of changes.changes will have minimal impact on derived classes. Function calls then become difficult to write. especially base classes. Your mistakes in a class or set of classes won’t destroy the integrity of the whole system.

but there’s no real justification to force a superclass/subclass relationship where it doesn’t exist. but you still benefit from inheritance and will probably make an important discovery about the design. and if you are working from an old class library. A suspicious design removes old capabilities during inheritance without adding new ones. That is. and there is a natural temptation to try to make one a subclass of the other just to benefit from inheritance. Watch out for limitation during inheritance. . Watch for switch statements or chained if-else clauses. If an interface element is essential to a class it should be in the base class. not added during derivation. Don’t extend fundamental functionality by subclassing. which means you are choosing what code to execute based on some kind of type information (the exact type may not be obvious at first). This is typically an indicator of type-check coding. Watch out for variance.Sometimes the discovery of this common code will add valuable functionality to your interface. A better solution is to create a general base class that produces an interface for both as derived classes – it requires a bit more space. Two semantically different objects may have identical actions. above the old class. From a design standpoint. But rules are made to be broken. it may be more efficient to restrict an existing class in its subclass than it would be to restructure the hierarchy so your new class fits in where it should.73 - . This is called variance. The clearest designs add new capabilities to inherited ones. perhaps you should rethink the design. look for and separate things that change from things that stay the same. If you’re adding member functions by inheriting. You can usually replace this kind of code with inheritance and polymorphism. or responsibilities. a polymorphic function call will perform the type checking for you. then encapsulate those elements in classes. search for the elements in a system that you might want to change without forcing a redesign. and allowfor more reliable and easier extensibility.

Sometimes you need to inherit in order to access protected members of the base class. leave the existing interface alone (you can combine the functionality in the underlying implementation if you want). users will think they are supposed to upcast. this way you won’t disturb any existing calls to that function. If not. Thus. As the class is used. If you don’t need to upcast. and put default values on all of the new arguments. referring to the relationship between a base class and derived class as “is-a” and member objects as “has-a. Start with a minimal interface to a class. Then make that new class a member object inside any class that needs to use it. If you inherit. rather than inheriting. This can eliminate the perceived need for multiple inheritance. first derive a new class to perform the protected access. If you need to add more functions. . when you create a base class.” When deciding between inheritance and composition. as small and simple as you need to solve the problem at hand. a base class will be used primarily to create an interface to classes derived from it. that’s fine. because all destructors in a hierarchy are always called. If you need to expand the interface of an existing function by adding more arguments. Read your classes aloud to make sure they’re logical. This can lead to a perceived need for multiple inheritance. But even if new member functions replace the functionality of old ones. you’ll discover ways you must expand the interface. but don’t try to anticipate all the ways that your class might be used. ask if you need to upcast to the base type. Typically. other than forcing recompiles. leave the existing arguments in their current order. prefer composition (member objects) to inheritance. once a class is in use you cannot shrink the interface without disturbing client code.74 - . but remember to give the destructor a function body. The destructor can also be pure virtual (to force inheritors to explicitly override it).Less is more. default to making the member functions pure virtual. However. it won’t disturb code.

make an abstraction for that service and localize it within a class. especially repairing class interfaces in which you don’t have control of the broken class. Although it’s in the language and seems to have occasional functionality. and put in a virtual destructor. nesting is beneficial for implementation hiding rather than the class association and prevention of namespace pollution noted above. make all functions in that class virtual. Only start removing the virtual keyword when you’re tuning for efficiency and your profiler has pointed you in this direction. if you find a class that uses state variables along with member functions that switch behavior based on those variables. If you must do something nonportable. as the Standard C++ Library does with iterators inside containers. It’s for getting you out of bad situations. Avoid multiple inheritance. Operator overloading is only syntactic sugar:” a different way to make a function call. Here. try to make one a publicnested friend class of the other. Use data members for variation in value and virtual functions for variation in behavior. you should probably redesign it to express the differences in behavior within subclasses and overridden virtual functions. It allows the class name to be reused by nesting it within another class. This extra level of indirection prevents the nonportability from being distributed throughout your program. Don t use private inheritance. If two classes are associated with each other in some functional way (such as containers and iterators). The other reason you’ll want to nest a class is as part of the private implementation. it introduces significant ambiguities when combined with run-time type identification. This approach prevents surprises in the behavior of the interface. If overloading an operator doesn’t make the class interface clearer .75 - . Create a private member object instead of using private inheritance. That is.When you put a virtual function in a class.

then nothing will happen (the same is true for the member objects). pass it the derived object you’re copying from: Derived(const Derived& d) : Base(d) { // . unless the design requires certain efficiency. Avoid the preprocessor. Always use const for value substitution and inlines for macros. declare them as private. you must create the copy constructor. operator=. Remember that if you create any constructor. destructors.. use the base-class name and scope resolution: Derived& operator=(const Derived& d) { Base::operator=(d). making some functions non virtual. it prevents the default constructor from being synthesized. To call the baseclass assignment operator. remember to call the base-class version of the assignment operator explicitly. That way lies madness. or tweaking code to be efficient when you are first constructing the system. In particular. When you write a copy-constructor for a derived class. Class designers should always say exactly what the class should do and keep the class entirely under control. Create only one automatic type conversion operator for a class. If your class contains pointers. Don t fall prey to premature optimization. When you write an assignment operator for a derived class. If you don’t.. don’t worry about writing (or avoiding) inline functions. . and destructor for the class to work properly. don t let the compiler create the constructors. or the operator= for you. Your primary goal should be to prove the design. Normally.76 - . To call the base-class copy-constructor. don’t do it.and easier to use. If you don’t. remember to call the base-class copy-constructor explicitly. If you don’t want a copyconstructor or operator=. the default constructor will be called for the base class (or member object) and that probably isn’t what you want.

This reduces the chance of using an object in the wrong context and hiding a difficult-to-find bug. the error will be caught at compile time. For example. suppose you have a container and a piece of code that iterates through it. the old container is out of scope.Keep scopes as small as possible so the visibility and lifetime of your objects are as small as possible. For example. you may accidentally end up using the size of the old container as the upper bound of the new one. if a library is big.) Instead. Always strive to put data inside classes. although you may later discover that a global function may fit better as a static member of a class. If you copy that code to use with a new container. (It can speed compilations. When defining operator=. As long as you don’t need to modify the object being passed. If. this practice is best because it has the simplicity of pass-by-value syntax but doesn’t require expensive constructions and destructions to create a local object. pass arguments by const reference as your first choice. When creating your own classes. Return a copy or reference to the lvalue (return *this) so it can be used in a chained expression (A = B = C).77 - . however. When writing a function. consider what will happen if expressions are chained together. provide your users an abbreviated form of the header file with incomplete type specifications (that is. Avoid global variables. if you want to create a function to write to an ostream. remember x=x. always do so by including a header file. Global functions are more likely to occur naturally than global variables.) When choosing the return type of an overloaded operator. which . class name declarations) for cases in which they need to use only pointers. always use the header file: #include <iostream>. This approach leaves your code vulnerable to changes in representation. If you need to declare a class or function from a library. never declare ostream yourself using an incomplete type specification like this. (For example. ostream could actually be a typedef. class ostream.

especially with operator overloading.78 - . watch out for temporary creation. Not only does this produce a lower overhead for constructor calls (many of which may not be under your control) but your constructors are then less likely to throw exceptions or cause problems. In the next-best scenario. you are responsible for catching your own exceptions and then deallocating any resources pointed to before you throw an exception in your constructor. rather than MyType x(i. Be aware of temporaries. j). In the best case. always try to build the object “in place” with a constructor call in the return statement: return MyType(i. consider exceptions. the appropriate action is to throwan exception. The former return statement (the so-called return-value optimization) eliminates a copyconstructor call and destructor call. The responsibility of the destructor is to release resources allocated during the lifetime of the object. If your constructors and destructors are complicated.occurs when passing by value. the cost of creating and destroying temporaries can be high. When returning a value from a function. Normally you don’t want to be worrying too much about efficiency issues when designing and building your system. If you must have naked pointers. When creating constructors. When tuning for performance. If a constructor must fail. Do only what is minimally necessary in your constructors. the class will be composed and inherited from robust classes only. return x. j). not just during construction. but this habit is a sure win. so they will automatically clean themselves up if an exception is thrown. the constructor won’t do anything that throws an exception. .

you cause extra constructions and destructions. Let the exception-handling mechanism handle memory management. If you throw pointers to exception objects that have been created on the heap. When defining pointers. the catcher must know to destroy the exception. When creating templates. and significantly more powerful. In general. Don t write your own class templates unless you must. so your bughunting time will increase. Look first in the Standard C++ Library. which is bad coupling. preferably derived from the Standard C++ exception hierarchy and nested as public classes within the class that throws the exceptions. Whenever you use built-in types as globals or automatics. they are type-safe and type-extensible. but they are much less robust than C++ classes. put . Become proficient with their use and you’ll greatly increase your productivity. don’t define them until you can also initialize them. worse.Use exception hierarchies. you can create templates in which the bulk of the code they contain is type-dependent and therefore essential. Your investment will be rewarded regularly. then to vendors who create special-purpose tools. Don’t use the <cstdio> functions.79 - . They are supported in C++ for backward compatibility. Avoid C s built-in types. Throw exceptions by value and catch exceptions by reference. If you add new derived exceptions. Define variables one per line along with their initialization. always use C++ libraries in preference to C libraries. such as printf( ). If you catch exceptions by value. The person catching the exceptions can then catch the specific types of exceptions. followed by the base type. the derived portions of your exception objects may be sliced during upcasting by value. existing client code will still catch the exception through the base type. Learn to use iostreams instead. Using inheritance or composition. watch for code that does not depend on type and put that code in a non-template base class to prevent needless code bloat.

always be specific and use the form MyType a(b). This one feature is a major source of confusion because it calls a constructor instead of the operator=. The results are identical. and fix your code to remove all warnings. Use all the tools provided by C++: access control. and you end up calling other member functions (probably operator=) on top of that in order to get the initialization you want. but use exceptions for runtime errors. Use assert( ) for debugging. Write code that utilizes the compile-time errors and warnings rather than that which causes runtime errors (for example. which disable all type checking). don’t use variadic argument lists. For clarity. This practice takes a little discipline and must be used consistently throughout your classes. even built-in types (using pseudo-constructor calls). That way you can safely move to the next level of abstraction when building your system. const-correctness. This style tends to be less confusing for the reader. Using the constructor initializer list is often more efficient when initializing subobjects. Use the explicit casts. anyone debugging and maintaining the code can easily find all the places where logical errors are most likely to happen. Use compiler error checking to your advantage. Perform all member initialization in the constructor initializer list. type checking. . You can safely do this if you define one variable per line. and so on in each class you create. For a program to be robust.80 - . exceptions. each component must be robust. Perform all compiles with full warnings. Guarantee that initialization occurs in all aspects of your code. Don’t use the form MyType a = b. instead. but other programmers won’t be confused. but it pays off. otherwise the default constructor is called. Build in const-correctness.the ‘*’ next to the type name. Since the explicit casts divide C’s one-cast-does-all into classes of well-marked casts. to define an object. A cast overrides the normal typing system and is a potential error spot. This allows the compiler to point out bugs that would otherwise be subtle and difficult to find.

Hungarian notation. Don t create your own decorated private data member names (prepending underscores. Watch for overloading. Prefer that a container “own” its pointers so it’s responsible for cleanup. When you use new. those functions might throw exceptions. which indicates a programming error). If you must .Prefer compile-time errors to runtime errors. A function should not conditionally execute code based on the value of an argument. let classes and namespaces do the name scoping for you. and exit the program. In this case. then release system resources. If a destructor calls any functions. unless you have a lot of pre-existing global values. etc. try to drop the resulting pointer into a container.81 - . A destructor cannot throw an exception (this can result in a call to terminate( ). if you still want it to look like a pointer. Hide your pointers inside container classes. Create a user-defined terminate( ) (indicating a programmer error) to log the error that caused the exception. rethrow the exception. default or not. If you’re using exception specifications install your own unexpected( ) function using set_unexpected( ) . you will have a record of the culprit and can modify your calling code to handle the exception. Do what you can with the exception at the current level. so any destructor that calls functions must catch and manage its own exceptions. overload operator->and operator*. Your unexpected( ) should log the error and rethrow the current exception. That way. if that doesn’t solve the problem. if an existing function gets overridden and starts throwing exceptions. Catch any exceptions in the nearest handler that has enough information to deal with them. Even better.). otherwise. Try to handle an error as close to the point of its occurrence as possible. Prefer dealing with the error at that point to throwing an exception. wrap a pointer inside a class. Pointers have always been a major source of bugs. you should create two or more overloaded functions instead. Bring them out only when you are going to immediately perform operations on them.

consider the effect it could have on inheritors. don’t assume that you knowthe size of the object. . something only the creators of a project should control. but to zero if necessary. If you do anything special. always initialize it. preferably to an object address. Overloading the global versions affects the entire client programmer project. Use the provided argument. It virtually never makes sense to upcast an object by value. someone may be inheriting from you. put pure virtual functions in your base class. always do this on a class-by-class basis. To prevent upcasting by value.have a free-standing pointer. Set it to zero when you delete it to prevent accidental multiple deletions.82 - . Prevent object slicing. When overloading new and delete for classes. Don t overload global new and delete.

Include the necessary header files iostream. 6. cout<<"Enter the length of the rectangle : ". 4. 8. In main function declare necessary variables for length.h> inline float find_area(float length. area. Algorithm 1. wid. 7. cin>>len.Appendix C: Sample Programs Problem 1 : Write a C++ program to find the area of a rectangle using inline function. Get input from user for length and width. } int main() { float len. The inline function returns the multiplication of length and width.h 2. . Print the area of the rectangle returned by the inline function Program # include<iostream.83 - . float width) { return length * width. width and area for the given rectangle. Call the inline function find_area( ) with user specified length and width.h> # include<conio. 5. Aim To write a c++ program to find the area of a rectangle for its given length and width using inline function.h and conio. 3. Declare and define an inline function find_area( ) with two arguments length and width of float type. clrscr(). Also make the return type of that function as float.

cout<<"Area of rectangle = "<<area.1 Sample Output Area of rectangle = 52.2 Enter the width of the rectangle 5.wid). return 0. cin>>wid. getch(). area=find_area(len.cout<<"Enter the width of the rectangle: ". } Sample Input Enter the length of the rectangle 10. .02 Result Thus the c++ program to find the area of a rectangle using inline function is created and executed successfully.84 - .

income tax. Gross salary. 7.85 - . Member Functions: to read data. DA = 52 % of basic salary Gross Salary = basic+DA Income_tax(IT) = 30 % of gross salary Net salary = Gross_Sal-IT. In display member function. number and basic salary.h> class EMPLOYEE //implements the EMPLOYEE class { private: . 2. name and net salary detail. display the employee number. Net_Sal. Write a C++ program to read data on N employees and compute the Net_Sal of each employee (DA = 52% of Basic and Income Tax = 30% of the gross salary) Aim To develop a c++ program to represeant an employee details as a class and to calculate and display the salary details using member functions. to calculate and print Net_Sal. 4. Include the the necessary header file. Employee_Name. IT and Net salary as follows. basic pay. employee name .h> # include <conio. Alogirthm 1. DA. create and object for EMPLOYEE class and call all the member functions. 6. 3. and net salary. Basic. Also include three member function to read the data calculate net salary and to display data. read employee name. In calculate_net_salary function. dearness allowance. In the read member function. Create a class EMPLOYEE with data members employee no. IT. 5. Program # include <iostream.Problem 2: Given that an EMPLOYEE class contains the following members: Data Members: Employee_Number. In main function. calculate DA.

} int main() { int n. } void EMPLOYEE::Calculate_Net_Salary() { float Gross_Sal. cin >> basic.Display_Data(). cin >> employee_number >> employee_name.86 - . cout<<"Emp Number: " <<employee_number<<”\n". clrscr(). Emp. IT = (30*Gross_Sal)/100. name and basic void Calculate_Net_Salary(). cout << "Enter employee data" << endl.i. //calculates the net salary void Display_Data(). float basic. Emp.employee_name[10]. Emp. //Displays the data }.Calculate_Net_Salary(). } } . void EMPLOYEE::Read_Data() { cout << "Enter the Employee Number and Name : " << endl. cin >> n. cout << "Net Salary: " << net_sal << endl. } void EMPLOYEE::Display_Data() { cout << "Emp Name: " << employee_name << "\n". cout << endl. IT. EMPLOYEE Emp. net_sal = Gross_Sal-IT.char employee_number[10]. cout << "Enter the Basic Salary: " << endl. DA = (52*basic)/100. Gross_Sal = basic+DA.Read_Data(). //reads the employee_number. net_sal.DA. public: void Read_Data().

87 - . .Sample Input Enter the employee data Enter the Employee Number and Name: Ram Emp0010 Enter the Basic Salary: 8500 Sample Output Emp Name : Ram Emp Number: Emp0010 Net Salary: 9044 Result Thus the C++ program to find the employee salary details have been generated by using the concept of classes and executed successfully.

“C++ programming Language”. [8] http://www. Tata McgrawHill. “ Programming in C++”. Thomson Delmar Learning. 4th edition. “Thinking in C++”. 2nd edition.Somashekara. “ Object Oriented Programming with C++”. Deitel and Paul J.cplusplus. [2] Harvey M. [6] D. T.R.com/ [11] http://www.Malik.com [10] http://www. Simply C++ An Application Driven Tutorial Approach.T. 4th edition.learncpp. Prentice Hall.hyperformix.References [1] Goran Svenk (2002).88 - .Balagurusamy. Prentice Hall of India [5] K.Venugopal. July 2009. Object-oriented Programming using C++ for Engineering and Technology. Deitel (2004). “Mastering C++”. Tata McgrawHill.com/ .com [9] http://cpptips.Ravishankar (2009). [4] M.S.cpp4u. [7] Bruce Eckel (2000). Rajkumar. Cengage Learning. Prentice Hall. [3] E.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->