Anda di halaman 1dari 85

2

Biyani's Think Tank


Concept based notes

Object Oriented Technology Using C++


(M.Sc I.T 2nd Sem)

Mr. Dhanesh Gupta


Lecturer Deptt. of Information Technology Biyani Girls College, Jaipur

Object Oriented Technology using C++

Published by :

Think Tanks Biyani Group of Colleges

Concept & Copyright :

Biyani Shikshan Samiti


Sector-3, Vidhyadhar Nagar, Jaipur-302 023 (Rajasthan) Ph : 0141-2338371, 2338591-95 Fax : 0141-2338007 E-mail : acad@biyanicolleges.org Website :www.gurukpo.com; www.biyanicolleges.org

First Edition :

While every effort is taken to avoid errors or omissions in this Publication, any mistake or omission that may have crept in is not intentional. It may be taken note of that neither the publisher nor the author will be responsible for any damage or loss of any kind arising to anyone in any manner on account of such errors and omissions.

Leaser Type Setted by : Biyani College Printing Department

Preface

am glad to present this book, especially designed to serve the needs of

the students. The book has been written keeping in mind the general weakness in understanding the fundamental concepts of the topics. The book is selfexplanatory and adopts the Teach Yourself style. It is based on question answer pattern. The language of book is quite easy and understandable based on scientific approach. Any further improvement in the contents of the book by making corrections, omission and inclusion is keen to be achieved based on suggestions from the readers for which the author shall be obliged. I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay Biyani, Director (Acad.) Biyani Group of Colleges, who are the backbones and main concept provider and also have been constant source of motivation throughout this Endeavour. They played an active role in coordinating the various stages of this Endeavour and spearheaded the publishing work. I look forward to receiving valuable suggestions from professors of various educational institutions, other faculty members and students for improvement of the quality of the book. The reader may feel free to send in their comments and suggestions to the under mentioned address.

Author

Object Oriented Technology using C++

Syllabus
M.Sc I.T 2nd Sem.

Content
S.No. 1. 2. 3. 4. 5. 6 7 8 Name of Topic Object-oriented Language Class and Object Polymorphism Pointers and File Handling Program Keywords Objective Questions Bibliography Page No.

Object Oriented Technology using C++

Chapter -1

Object-Oriented Programming
Q.1. What is OOP? Explain Characteristics of an Object-oriented Language. Ans.: OOP stands for Object-Oriented Programming. Object oriented programming is combining the data and function in to a single unit , called object. The data of the object can be accessed by function associated with the object only . the function of one object cant access the data of other object. Characteristics of an Object-oriented Language. 1) Class Classes are the central feature of object-oriented programming and are often called user-defined types. A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class. 2) Object An object is an entity that has state, behavior and identity. A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. 3) Encapsulation Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. 4) Data Abstraction Data abstraction refers to, providing only essential information to the outside word and hiding their background details ie. to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. Example of a TV which you can turn on and off, change the channel, adjust the volume, and add external components such as

speakers, VCRs, and DVD players BUT you do not know it's internal detail that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. Thus we can say, a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having zero knowledge of its internals. 5) Inheritance One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. Polymorphism The word polymorphism is derived from two Greek words Poly which means many and morphos which means forms. So, polymorphism means the ability to take many forms. Polymorphism can be defined as the ability to use the same name for two or more related but technically different tasks. Overloading An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation). When we call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the

6)

Object Oriented Technology using C++

most appropriate overloaded function or operator is called overload resolution. 7) Dynamic Binding Binding refers to the linking of a function call to the code of function to be executed in response to the function call. Binding is of two types. Static or early binding Binding refers to the linking of a function call to the code of function to be executed in response to the function call is made at the compile time. Dynamic or late binding Dynamic Binding refers to linking a procedure call to the code that will be executed only at run time. The code associated with the procedure in not known until the program is executed, which is also known as late binding. Message passing Message Passing is nothing but sending and receiving of information by the objects. So this helps in building systems that simulate real life. Following are the basic steps in message passing. Creating classes that define objects and its behavior. Creating objects from class definitions Establishing communication among objects In OOPs, Message Passing involves specifying the name of objects, the name of the function, and the information to be sent. What are the differences between procedural languages and object oriented languages? Procedure Programming Divided Into Oriented Object Oriented Programming

8)

Q2 Ans

In POP, program is divided into In OOP, program is divided small parts called functions. into parts called objects. In POP,Importance is not given to data but to functions as well as sequence of actions to be done. POP follows approach. Top In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. Bottom Up

Importance

Approach Access

Down OOP follows approach. has

POP does not have any access OOP

access

specifiers

10

Specifiers

specifier.

named Public, Protected, etc.

Private,

In POP, Data can move freely In OOP, objects can move and Data Moving from function to function in the communicate with each other system. through member functions. Expansion To add new data and function OOP provides an easy way to in POP is not so easy. add new data and function. In OOP, data can not move In POP, Most function uses easily from function to Global data for sharing that can function,it can be kept public be accessed freely from function or private so we can control the to function in the system. access of data. POP does not have any proper OOP provides Data Hiding so way for hiding data so it is less provides more security. secure.

Data Access

Data Hiding

In OOP, overloading is In POP, Overloading is not possible in the form of Overloading possible. Function Overloading and Operator Overloading. Examples Example of POP are : C, VB, Example of OOP are : C++, FORTRAN, Pascal. JAVA, VB.NET, C#.NET.

Q.3. What are advantages Object-oriented Language. Ans The major advantages of OOPs are: 1. Simplicity: Software objects model real world objects, so the complexity is reduced and the program structure is very clear. 2. Modularity: Each object forms a separate entity whose internal workings are decoupled from other parts of the system. 3. Modifiability: It is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods. 4. Extensibility:

Object Oriented Technology using C++

11

Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones. 5. Maintainability: Objects can be maintained separately, making locating and fixing problems easier. 6. Re-usability: Objects can be reused in different programs. Q4 Ans What is the basic structure of C++? Basic Structure of C++ program: #include directive Global Declarations return-type main() { Statements } Include Directive: The "#include" directive is used to include the files specified inside the "<>" brackets. Mostly standard files or header files of C++ are included using this directive like iostream.h, math.h etc. Global Declarations: The variables and other elements that need to be used all over the program or rather globally should be declared after the include directive. main() Function: The main function is executed first in a C++ program. If a main() is supposed to return a integer value then the return type should be specified as "int main()". If no value is returned simply use the return-type as "void". The statements used inside the "main()" function can include the functions, classes used in C++ along with other statements. For Example: #include <iostream.h> void main() { cout << "Welcome"; }

12

Q 4. Ans

How do we define a character set? Any alphabet ,digit or symbols to represent information is called Character . The characters are grouped into following categories: 1 Letters 2 Digits 3 Special characters 4 White spaces The following are the valid alphabets, numbers and special symbols permitted in C. Digits: From 0 to 9 Letters: From a to z, A to Z. Special characters : , . ? / \ White space: Blank Spaces , Tab , New Line. What are Identifiers? Identifiers" are the names that we supply for variables, types, functions, and labels in our program. Identifier names must differ in spelling and case from any keywords. We cannot use keywords (either C or Microsoft) as identifiers; they are reserved for special use. We create an identifier by specifying it in the declaration of a variable, type, or function.

Q5 Ans

Q6 Ans

Define Variables. A variable is a name given to the memory location for holding data. The name of the memory location i.e. the variable name, remain fixed during execution of the program but the data stored in that location may change from time to time. Eg. Marks1 , Marks2, abc , a , ab_1 , Rules for writing variable names 1. The first character of variable name must be an alphabetic. 2. Blank spaces are not allowed in a variable name. 3. Special characters such as arithmetic operators, #,^ can not be used in a variable. 4. Reserved words(Keywords) cannot be used as variable names. 5. The maximum length of a variable name depends upon the compiler (8). 6. A variable name declared for one data type cannot be used to declare another data type.

Object Oriented Technology using C++

13

Q7 Ans

What do you mean by constants? Constant is fixed value which can not be changed by the program during the execution. Eg. A=5 in this 5 is constant.

Q 8. How many types of constants ? Ans. There are mainly three types of constants namely: integer, real and character constants. 1. Integer Constants: (i) Decimal Integer Constant: 0 to 9 E.g: 49, 58, -62, (40000 cannot come bcoz it is > 32767) (ii) Octal Integer Constant: 0 to 7 Add 0 before the value. Eg.: 045, 056, 067 (iii) Hexadecimal Integer:0 to 9 and A to F Add 0x before the value E.g: 0x42, 0x56, 0x67 2. Real Constants: The real or floating point constants are in two forms namely fractional form and the exponential form. A real constant in fractional form must have a digit with a decimal part.Ex 456.78 In exponential form, the real constant is represented as two parts. The part lying before the e is the mantissa, and the one following e is the exponent. Ex: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4 3. Character Constants A character constant is an alphabet, a single digit or a single special symbol enclosed within inverted commas. Ex: B, l, # Q 9. What are key words? A.ns They are the reserved words that cannot be used for naming a variable. They perform fix tasks. Eg. int , char , for , if .

14

Q10 Ans

Discuss various operator in C++. An operator is a symbol that operates on a certain data type and produces the output as the result of the operation. Eg. expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Category of operators Unary Operators:-A unary operator is an operator, which operates on one operand. Binary:-A binary operator is an operator, which operates on two operands Ternary:-A ternary operator is an operator, which operates on three operands. C contains the following operator groups 1 Arithmetic Operator The arithmetic operator is a binary operator, which requires two operands to perform its operation of arithmetic. Following are the arithmetic operators that are available. Operator Description Eg. + Addition a+b Subtraction a-b / Division a/b * Multiplication a*b % Modulo or remainder a%b 2 Relational Operators Relational operators compare between two operands and return in terms of true or false i.e. 1 or 0. In C++ and many other languages a true value is denoted by the integer 1 and a false value is denoted by the integer 0. Relational operators are used in conjunction with logical operators and conditional & looping statements. < Less than > Greater than <= Less than or equal to >= Greater than or equal to != Not equal to == Equal to

Object Oriented Technology using C++

15

Logical Operators A logical operator is used to compare or evaluate logical and relational expressions. There are three logical operators available in the C++ language. && Logical AND || Logical OR ! Logical NOT Assignment operator An assignment operator (=) is used to assign a constant or a value of one variable to another. Example: a = 5; b = a; rate = 10.5 net = (a/b) * 100; There is always difference between the equality operator (==) and the assignment operator (=). Conditional or Ternary Operator A conditional operator checks for an expression, which returns either a true or a false value. If the condition evaluated is true, it returns the value of the true section of the operator, otherwise it returns the value of the false section of the operator. Its general structure is as follows: Expression1 ? expression 2 (True Section): expression3 (False Section) Example: a=3,b=5,c; c = (a>b) ? a+b : b-a; The variable c will have the value 2, because when the expression (a>b) is checked, it is evaluated as false. Now because the evaluation is false, the expression b-a is executed and the result is returned to c using the assignment operator. Bitwise Operators: These are used to perform bitwise operations such as testing the bits , shifting the bits to left or right , ones compliment of bits. This operator can be apply on only int and char data type. & AND

* 5

16

| Inclusive OR ^ Exclusive OR << Shift Left >> Shift Right ~ One's compliment ~A = 1100 0011 7 Increment and Decrement Operators These operators are unary operators . The increment and decrement operators are very useful in C++ language. They are extensively used in for and while loops. The syntax of these operators is given below. ++ -Comma operator ( , ):The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered. What are the ways to comment statement in C? Comments are non executable statement Most of C++ will support two types of comments: // Comment text goes here ( in line)

Q11 Ans

Q.12 Explain control structures available in C++. Ans C++ provides two styles of flow control: Branching Looping Branching or Decision : Branching or Decision is so called because the program chooses to follow one branch or another. if statement This is the most simple form of the branching statements.It takes an expression in parenthesis and an statement or block of statements. if the

Object Oriented Technology using C++

17

expression is true then the statement or block of statements gets executed otherwise these statements are skipped. Syntex:- if with single statement if (expression) statement; Syntex:- if with block statement if (expression) { Block of statements; } or Syntex:- if with else statement if (expression) { Block of statements; } else { Block of statements; } Or Syntex:- if with else if statement if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements;

18

} switch statement: The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read. switch( expression ) { case expression1: statements1; case expression2: statements2; case c-expression3: statements3; default : statements4; } Use of break Use If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using break keyword. Looping Loops provide a way to repeat commands and control how many times they are repeated. C++ provides a number of looping way. while loop The most basic loop in C++ is the while loop. Like an If statement, if the test condition is true, the statements get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false. syntax while ( expression ) { Single statement or Block of statements;

Object Oriented Technology using C++

19

} for loop for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers: syntax: for( expression1; expression2; expression3) { Single statement or Block of statements; } In the above syntax: expression1 - Initialisese variables. expression2 - Condtional expression, as long as this condition is true, loop will keep executing. expression3 - expression3 is the modifier which may be simple increment of a variable. do...while loop do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once. syntax do { Single statement or Block of statements; }while(expression); break and continue statements C provides two commands to control the loop: break -- exit form loop or switch. continue -- skip 1 iteration of loop. #include main() {

20

int i; int j = 10; for( i = 0; i <= j; i ++ ) { if( i == 5 ) { continue; } cout<<Hello <<i<<endl; } } Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 6 Hello 7 Hello 8 Hello 9 Hello 10 The goto statement (unconditional branching) goto allows to make an absolute jump to another point in the program. We should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). goto loop example #include <stdio.h> int main () { int n=10; loop: cout<< n; n--;

Object Oriented Technology using C++

21

if (n>0) goto loop; cout<< "FIRE; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! exit function exit is a function defined in the cstdlib library. The purpose of exit is to terminate the current program with a specific exit code. Its prototype is: exit() Q13 Ans What is a Function? The function is a self contained block of statements which performs a task of a same kind. C++ program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements. We call function whenever we want to process that functions statements i.e. more than 1 times. Any c++ program contains at least one function. Function is used to avoids rewriting the same code over and over. The following is its format: type name ( parameter1, parameter2, ...) { statements } where: type is the data type specifier of the data returned by the function. name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier. statements is the function's body. It is a block of statements surrounded by braces { }.

Eg. void add() { int a, b, c; clrscr(); cout<<\n<<" Enter Any 2 Numbers : "; cin>>&a>>&b;

22

c = a + b; cout<<\n<< Addition is :<<c); } void main() { void add(); add(); getch(); } Q14 Ans What are the types of functions ? There are 2(two) types of functions as: 1. Built in Functions 2. User Defined Functions Built in Functions : These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g. clrscr() strcpy() User Defined Functions : The functions which are created by user for program are known as 'User defined functions'. void add() { int a, b, c; clrscr(); cout<<\n<<" Enter Any 2 Numbers : "; cin>>&a>>&b; c = a + b; cout<<\n<< Addition is :<<c); } void main() { void add(); add(); getch();

1.

Object Oriented Technology using C++

23

} Q15. Define arrays. Ans. A collection of variables which are all of the same type. It is a data structure, which provides the facility to store a collection of data of same type under single variable name. Just like the ordinary variable, the array should also be declared properly. The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements. Examples: short val[ 200 ]; //declaration val[ 12 ] = 5; //assignment Q16. How is Array declared? Ans Declaration & Data Types Arrays have the same data types as variables, i.e., short, long, float etc.They are similar to variables: they can either be declared global or local.They are declared by the given syntax: Datatype array_name[dimensions]={element1,element2,.,element} Q.17 Explain String. Ans A group of characters stored in a character array. A string in C is a sequence of zero or more characters followed by a NULL '\0' character: String constants have double quote marks around them,. Alternatively, we assign a string constant to a char array - either with no size specified, or you can specify a size, but don't forget to leave a space for the null character!. Eg. char string_2[] = "Hello"; char string_3[6] = "Hello"; Q18 Explain structure and union in c++. Ans. Structures in C++ is a collection of variables. Structures in C++ can be declared even without the keyword "struct". By default all the members of a structure are "public", even "private" members can also be declared in a function. Syntax: type name1: length; type name2: length;

24

. . type nameN : length; }variable_list; Unions: Unions in C++ is a user defined data type that uses the same memory as other objects from a list of objects. At an instance it contains only a single object. Syntax: union union-type-name{ type member-name; type member-name; }union-variables

Multiple Choice Questions


Q.1 (A) (C) Q.2 The address of a variable temp of type float is *temp (B) &temp float& temp (D) float temp& What is the output of the following code char symbol[3]={a,b,c}; for (int index=0; index<3; index++) cout << symbol [index]; abc (B) abc abc (D) abc

Ans: B

(A) (C)

Ans: C

Q.3 (A) (B) (C) (D)

If the variable count exceeds 100, a single statement that prints Too many is if (count<100) cout << Too many; if (count>100) cout >> Too many; if (count>100) cout << Too many; None of these. Ans: C

Q4

In C++, the range of signed integer type variable is ________

Object Oriented Technology using C++

25

(A) (C) Q.5 (A) (C) Q.6 (A) (C) Q7. (a) (c)

0 to 216 -27 to 27 -1

(B) (D)

-215 to 215 -1 0 to 28

Ans: B

If X=5 , Y=2 then yx equals________. (where is a bitwise XOR operator) 00000111 (B) 10000010 10100000 (D) 11001000 Ans:A If an array is declared as int a[4] = {3, 0, 1, 2}, then values assigned toa[0] & a[4] will be ________ 3, 2 (B) 0, 2 3, 0 (D) 0, 4 Ans: C Which operator has the highest precedence? Unary (b) Ternary (d) Ans:A Switch statement is used for: Multiple selection three set selection

Binary all of the above

Q8. (a) (c) Q9. (a) (c)

(b) (d)

Two set selection none of the above

Ans:A

Which of the following operator takes only integer operands? + (b) X / (d) %

Ans:D

26

Chapter -2

Class and Objects


Q.1. What is Class and Object in C++? Ans.: Class:A class is a way to bind the data and function together in a single unit. When we define a class , we create a new abstract data type that can be treated like other build in data type. The variables of class are called objects or instance of a class. A class specification has two parts: i) Class Declaration ii) Class Function definitions A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example we defined the Box data type using the keyword class as follows: class Box { public: double length; double breadth; double height; double getVolume(void) { return length * breadth * height; } }; The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. A class member can be defined as public, private or protected. By default members would be assumed as private. A member function of a class is a function that has its

Object Oriented Technology using C++

27

definition or its prototype within the class definition like any other variable. Creating Objects:A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box: Box Box1; // Declare Box1 of type Box Box Box2;

A Class and Object Example


class Box { public: double length; double breadth; double height;

// Length of a box // Breadth of a box // Height of a box

// Member functions declaration double getVolume(void); void setLength( double len ); void setBreadth( double bre ); void setHeight( double hei ); }; // Member functions definitions double Box::getVolume(void) { return length * breadth * height; } void Box::setLength( double len ) { length = len; }

28

void Box::setBreadth( double bre ) { breadth = bre; } void Box::setHeight( double hei ) { height = hei; } // Main function for the program int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; return 0; } When the above code is compiled and executed, it produces following result:

Object Oriented Technology using C++

29

Volume of Box1 : 210 Volume of Box2 : 1560 Q2 What do you understand by class member function? Ans. The member functions are set of functions that are applied to objects of that class. A function as a member of a class is also called a Method. A member function is declared like any of the functions we have used so far; it could or could not return a value. When using functions on a class, the variables are used to hold or store values, called data, of the object, while member functions are used to perform assignments as related to the objects. One way you can control the data held by variables is to hide data from the external world. To achieve this, you should declare the member variables in the private section. After doing this, use the methods in the public section to help the class interact with the other objects or functions of the program. Q3 Ans What is an Array of Objects in C++? Arrays of variables of type "class" is known as "Array of objects". The "identifier" used to refer the array of objects is an user defined data type. #include <iostream.h> const int MAX =100; class Details { private: int salary; float roll; public: void getname( ) { cout << "\n Enter the Salary:"; cin >> salary; cout << "\n Enter the roll:"; cin >> roll; } void putname( ) { cout << "Employees" << salary <<

30

"and roll is" << roll << '\n'; } }; void main() { Details det[MAX]; int n=0; char ans; do{ cout << "Enter the Employee Number::" << n+1; det[n++].getname; cout << "Enter another (y/n)?: " ; cin >> ans; } while ( ans != 'n' ); for (int j=0; j<n; j++) { cout << "\nEmployee Number is:: " << j+1; det[j].putname( ); } } Result: Enter the Employee Number:: 1 Enter the Salary:20 Enter the roll:30 Enter another (y/n)?: y Enter the Employee Number:: 2 Enter the Salary:20 Enter the roll:30 Enter another (y/n)?: n In the above example an array of object "det" is defined using the user defined data type "Details". The class element "getname()" is used to get the input that is stored in this array of objects and putname() is used to display the information.

Object Oriented Technology using C++

31

Q4 Ans

What is Nested classes in C++? Nested class is a class defined inside a class, that can be used within the scope of the class in which it is defined. In C++ nested classes are not given importance because of the strong and flexible usage of inheritance. Its objects are accessed using "Nest::Display". #include <iostream.h> class Nest { public: class Display { private: int s; public: void sum( int a, int b) { s =a+b; } void show( ) { cout << "\nSum of a and b is:: " << s;} }; }; void main() { Nest::Display x; x.sum(12, 10); x.show(); } Result: Sum of a and b is::22 In the above example, the nested class "Display" is given as "public" member of the class "Nest". Q5 Ans what is inline function in c++ ? C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.

32

Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality. To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. Following is an example which makes use of inline function #include <iostream> inline int Max(int x, int y) { return (x > y)? x : y; } // Main function for the program main( ) { cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; } When the above code is compiled and executed, it produces following result: Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010 Q6 Ans What do you mean by friend function? A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function

Object Oriented Technology using C++

33

must have the class to which it is declared as friend passed to it in argument. Example to understand the friend function #include <iostream> using namespace std; class fri { private: int a,b; public: void test() { a=100; b=200; } friend int compute(fri e1); //Friend Function Declaration with keyword friend and with the object of class fri to which it is friend passed to it }; int compute(fri e1) { //Friend Function Definition which has access to private data return int(e1.a+e1.b)-5; } void main() { fri e; e.test(); cout << "The result is:" << compute(e); //Calling of Friend Function with object as argument. }

34

Q7 Ans

What do you mean by static member function. The keyword static is used to precede the member function to make a member function static. The static member function has following properties: 1) A static function have access to only static member declared in the class. 2) A static member function can be called using the class names as : Classname : : functionname; 3) A static member function acts as global for the data member of its class without affecting the rest of the program. What do you mean by Dynamic Memory Allocation? Allocating memory There are two ways that memory gets allocated for data storage: Compile Time (or static) Allocation Memory for named variables is allocated by the compiler. Exact size and type of storage must be known at compile time For standard array declarations, this is why the size has to be constant Dynamic Memory Allocation Memory allocated "on the fly" during run time dynamically allocated space usually placed in a program segment known as the heap or the free store Exact amount of space or number of items does not have to be known by the compiler in advance. For dynamic memory allocation, pointers are crucial Dynamic Memory Allocation We can dynamically allocate storage space while the program is running, but we cannot create new variable names "on the fly" For this reason, dynamic allocation requires two steps: a) Creating the dynamic space. b) Storing its address in a pointer (so that the space can be accesed) To dynamically allocate memory in C++, we use the new operator. De-allocation: Deallocation is the "clean-up" of space being used for variables or other data storage

Q8 Ans

Object Oriented Technology using C++

35

Compile time variables are automatically deallocated based on their known extent (this is the same as scope for "automatic" variables) It is the programmer's job to deallocate dynamically created space To de-allocate dynamic memory, we use the delete operator Q.9. What is constructor and Destructor in C++? Explain. Ans.: Constructor A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables. Types of Constructor Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor. student :: student() { rollno=0; marks=0.0; } Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor. student :: student(int r) { rollno=r; } Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object. student :: student(student &t) { rollno = t.rollno; }

36

Destructor A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an objects scope is over. ~student() { } Example : In the following program constructors, destructor and other member functions are defined inside class definitions. #include<iostream> class CAdd { public: int one; CAdd(int two) { cout << "A constructor is called" << endl; one=two; } CAdd() { cout << "A default constructor is called " << endl; } ~CAdd() { cout << "Destructing " << one << endl; } int add() { return(one+one); } }; main() { CAdd myobj1(4); CAdd myobj2;

Object Oriented Technology using C++

37

cout << myobj1.one << endl; cout << "Enter a number : " ; cin >> myobj2.one; cout << myobj2.add() << endl; return(0); } Q10 Ans (1) What are the special characteristic of constructors and destructors in c++? Characteristic of constructors and destructors Constructors (i) Constructor has the same name as that of the class it belongs. (ii) Constructor is executed when an object is declared. (iii) Constructors have neither return value nor void. (iv) The main function of constructor is to initialize objects and allocate appropriate memory to objects. (v) Though constructors are executed implicitly, they can be invoked explicitly. (vi) Constructor can have default and can be overloaded. (vii) The constructor without arguments is called as default constructor. Destructors (i) Destructor has the same name as that of the class it belongs to and preceded by ~ (tilde). (ii) Like constructor, the destructor does not have return type and not even void.

(2)

Q.11. What is inheritance? Ans.: Inheritance:-Inheritance means using the Pre-defined Code This is very Main Feature of OOP. With the help of inheritance we uses the code that is previously defined but always Remember, We are only using that code but not changing that code. With the Advent of inheritance we are able to use pre-defined code and also able to add new code. All the pre-defined code is reside into the form of classes if we want to use that code then we have to inherit or extend that class.

38

The Class that is Pre-defined is called as Base or super Class and the class which uses the Existing Code is known as derived or sub class The Various Types of Inheritance those are provided by C++ are as followings: 1. Single Inheritance 2. Multilevel Inheritance 3. Multiple Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance Q12 Ans 1) What are the types of Inheritance ? In Single Inheritance there is only one Super Class and Only one Sub Class Means they have one to one Communication between them

2)

In Multilevel Inheritance a Derived class can also inherited by another class Means in this When a Derived Class again will be inherited by another Class then it creates a Multiple Levels.

3)

Multiple Inheritances is that in which a Class inherits the features from two Base Classes When a Derived Class takes Features from two Base Classes.

4)

Hierarchical Inheritance is that in which a Base Class has Many Sub Classes or When a Base Class is used or inherited by many Sub Classes.

Object Oriented Technology using C++

39

5)

Hybrid Inheritance: - This is a Mixture of two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance in Single Code.

Q13 What is a virtual base class? Ans When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class name with the word virtual. Consider following example: class A { public: int i; }; class B : virtual public A { public: int j; }; class C: virtual public A { public: int k; }; class D: public B, public C {

40

public: int sum; }; main() { D ob; ob.i = 10; //unambiguous since only one copy of i is inherited. ob.j = 20; ob.k = 30; ob.sum = ob.i + ob.j + ob.k; cout << Value of i is : << ob.i<<\n; cout << Value of j is : << ob.j<<\n; cout << Value of k is :<< ob.k<<\n; cout << Sum is : << ob.sum <<\n; return 0; }. Q14 What are the types to access member? Ans. Access Control A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class. We can summarize the different access types according to who can access them in the following way: Access public protected private Same class yes yes yes Derived classes yes yes no Outside classes yes no no A derived class inherits all base class methods with the following exceptions: Constructors, destructors and copy constructors of the base class. Overloaded operators of the base class. The friend functions of the base class.

Object Oriented Technology using C++

41

Q.1 (A) (C) Q.2 (A) (B) (C) (D) Q.3 (A) (C) (D) Q4 (a) (c) Q5 (a) (c) Q6. (a) (c) Q7. (a) (c) Q8. (a) (c) Q9.

The process of building new classes from existing one is called ______. Polymorphism (B) Structure Inheritance (D) Cascading Ans: C If a class C is derived from class B, which is derived from class A, all through public inheritance, then a class C member function can access protected and public data only in C and B. protected and public data only in C. rivate data in A and B. protected data in A and B. Ans:D Usually a pure virtual function has complete function body. will be called only to delete an object. is defined only in derived class.

(B)

will never be called. Ans:D

Number of constructor in a class can be: minimum one (b) zero two (d) as many as required Name of a constructor is: user defined same as program file name Constructor is involved : when class object is created through an explicit call

Ans:d

(b) (d)

same as class name none of the above

Ans:b

(b) (d)

when class object is initialized none of the above Ans:a

The number of copies created for a static data member of a class, when 10 class object are created would be: 0 (b) 1 2 (d) 4 Ans:B A destructor : has a return type has same name of class A constructor:

(b) (d)

may take parameters both b and a

Ans:C

42

(a) (c)

has a return type has same name as class

(b) (d)

may take parameter both b and c

Ans:D

Q10. The member of a class by default are: (a) Private (b) (c) Public (d) Q11 (a) (c) Q12 (a) (c)

Protected no default exists

Ans:A

A new class can be derived from an existing class. This concept is called us: inheritance (b) polymorphism overloading (d) dynamic binding Ans:A A C + + Class can hold? only data both data and function Ans:C

(b)

only function (d) none of the above

Q13 (a) (c)

Among the following, which one is the scope resolution operator? * (b) :: (d) ! Ans:C

Q14. Cout is: (a) a key word (c) a library function

(b) (d)

an obect a variable

Ans:B

Q15. The pure virtual functions are defined in: (a) base class (b) drived class (c) main program (d) both a and b Ans:B Q16. (a) (b) (c) (d) Inheritance is a way to: make new classes pass arguments of objects of class add feature to existing classes without rewriting them Improve to existing classes without rewriting them Ans:C

Q17. By default, a class members are:

Object Oriented Technology using C++

43

(a) (c)

Public Protected

(b) (d)

Private Any of the above

Ans:B

Q18. Friend keyword can be used for : (a) a function (b) (c) both function and class (d) Q19 (a) (c) Inline functions ..call overload: Increase (b) Depends on situation

a class a data member

Ans:C

Reduce (d) None

Ans:B

44

Chapter -3

Polymorphism
Q1 What is function overloading in C++?

Ans. Function overloading: A feature in C++ that enables several functions of the same name can be defined with different types of parameters or different number of parameters. This feature is called function overloading. The appropriate function will be identified by the compiler by examining the number or the types of parameters / arguments in the overloaded function. Function overloading reduces the investment of different function names and used to perform similar functionality by more than one function. Consider a function print, which displays an int. As shown in the following example, you can overload the function print to display other types, for example, double and char*. You can have three functions with the same name, each performing a similar operation on a different data type: #include <iostream> using namespace std; void print(int i) { cout << " Here is int " << i << endl; } void print(double f) { cout << " Here is float " << f << endl; } void print(char* c) { cout << " Here is char* " << c << endl; } int main() { print(10); print(10.10); print("ten");

Object Oriented Technology using C++

45

} Result is Here is int 10 Here is float 10.1 Here is char* ten

Q2
Ans

What is operator overloading in C++?


In C++ the overloading principle applies not only to functions, but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. // This example illustrates overloading the plus (+) operator. #include <iostream> using namespace std; class complx { double real, imag; public: complx( double real = 0., double imag = 0.); // constructor complx operator+(const complx&) const; // operator+() }; // define constructor complx::complx( double r, double i ) { real = r; imag = i; } // define overloaded + (plus) operator complx complx::operator+ (const complx& c) const { complx result;

46

result.real = (this->real + c.real); result.imag = (this->imag + c.imag); return result; } int main() { complx x(4,4); complx y(6,6); complx z = x + y; // calls complx::operator+() Q3 What do you mean by early binding and late binding? Ans. Early Binding: Events occurring at compile time are known as early binding. In the process of early binding all info which is required for a function call is known at compile time. Early binding is a fast and efficient process. Examples of early binding: function calls, overloaded function calls, and overloaded operators. Late Binding: In this process all info which is required for a function call is not known at compile time. Hence, objects and functions are not linked at run time. Late Binding is a slow process. However, it provides flexibility to the code. Example of Late Binding: Virtual functions. Q4 What do you mean by Virtual Function: Ans A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. Q5 What do you mean by Pure Virtual Functions: Ans. It's possible that you'd want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. We can change the virtual function area() in the base class to the following: class Shape { protected: int width, height;

Object Oriented Technology using C++

47

public: Shape( int a=0, int b=0) { width = a; height = b; } // pure virtual function virtual int area() = 0; }; The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function. Q6 Ans Explain Unary and binary operator overloading. The unary operators operate on a single operand and following are the examples of Uninary operators: The increment (++) and decrement (--) operators. The unary minus (-) operator. The logical not (!) operator. The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--. Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage. #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f;

48

inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } }; int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); // display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; } When the above code is compiled and executed, it produces following result: F: -11 I:-10 F: 5 I:-11 Hope above example makes your concept clear and you can apply similar concept to overload Logical Not Operators (!). Binary operators The Binary operators take two arguments and following are the examples of Binary operators. You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator. Following example explain how addition (+) operator can be overloaded. Similar way you can overload subtraction (-) and division (/) operators. #include <iostream> using namespace std;

Object Oriented Technology using C++

49

class Box { double length; double breadth; double height; public:

// Length of a box // Breadth of a box // Height of a box

double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } }; // Main function for the program int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box

50

double volume = 0.0; // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0);

// Store the volume of a box here

// volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; } When the above code is compiled and executed, it produces following result: Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400 Q7 What is assignment operator overloading ? Ans. We can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. Following example explain how an assignment operator can be overloaded.

Object Oriented Technology using C++

51

#include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } void operator=(const Distance &D ) { feet = D.feet; inches = D.inches; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches << endl; } }; int main() { Distance D1(11, 10), D2(5, 11); cout << "First Distance : "; D1.displayDistance(); cout << "Second Distance :"; D2.displayDistance(); // use assignment operator D1 = D2; cout << "First Distance :";

52

D1.displayDistance(); return 0; } When the above code is compiled and executed, it produces following result: First Distance : F: 11 I:10 Second Distance :F: 5 I:11 First Distance :F: 5 I:11 Q8 What is free store in C++? Ans. The free store is one of the two dynamic memory areas, allocated/freed by new/delete. Object lifetime can be less than the time the storage is allocated; that is, free store objects can have memory allocated without being immediately initialized, and can be destroyed without the memory being immediately deallocated. During the period when the storage is allocated but outside the object's lifetime, the storage may be accessed and manipulated through a void* but none of the protoobject's nonstatic members or member functions may be accessed, have their addresses taken, or be otherwise manipulated. Q9 Ans Explain Abstract classes. Abstract classes An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration. The following is an example of an abstract class: class AB { public: virtual void f() = 0; }; Function AB::f is a pure virtual function. A function declaration cannot have both a pure specifier and a definition. For example, the compiler will not allow the following: struct A { virtual void g() { } = 0; };

Object Oriented Technology using C++

53

You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class. You can, however, declare pointers and references to an abstract class. The following example demonstrates this: struct A { virtual void f() = 0; }; struct B : A { virtual void f() { } }; // Error: // Class A is an abstract class // A g(); // Error: // Class A is an abstract class // void h(A); A& i(A&); int main() { // Error: // Class A is an abstract class // A a; A* pa; B b; // Error: // Class A is an abstract class // static_cast<A>(b); } Class A is an abstract class. The compiler would not allow the function declarations A g() or void h(A), declaration of object a, nor the static cast of b to type A.

54

Virtual member functions are inherited. A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class. For example: class AB { public: virtual void f() = 0; }; class D2 : public AB { void g(); }; int main() { D2 d; } The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f()from AB. The compiler will allow the declaration of object d if you define function D2::g(). Note that you can derive an abstract class from a nonabstract class, and you can override a non-pure virtual function with a pure virtual function. You can call member functions from a constructor or destructor of an abstract class. However, the results of calling (directly or indirectly) a pure virtual function from its constructor are undefined. The following example demonstrates this: struct A { A() { direct(); indirect(); } virtual void direct() = 0; virtual void indirect() { direct(); } }; The default constructor of A calls the pure virtual function direct() both directly and indirectly (through indirect()). The compiler issues a warning for the direct call to the pure virtual function, but not for the indirect call.

Object Oriented Technology using C++

55

Q.1 (A) (B) (C) (D)

Overloading the function operator requires a class with an overloaded operator. requires a class with an overloaded [ ] operator. allows you to create objects that act syntactically like functions. usually make use of a constructor that takes arguments.

Ans:A

Q2. (a) (c) Q3. (a) (c) (d) Q4. (a) (c) Q5. (a) (c) Q6. (a) (c) Q7 (a) (c)

For operator overloading the operands should be of type: Minimum one (b) zero user defined (d) any type

Ans:c

The word which makes the name of tan operator overloading function is: the operator symbol (b) the key word operator the keyboard operator followed by the operator symbol user defined Ans:C The operator over loading function can be : member function only (b) non member function only both a or b (d) none of the above Ans.C Templates can be used: Functions only functions and classes both

(b) (d)

classes only none of the above

Ans:C

Which of the following operators can be over-loaded? (b) ?: both a and b (d) no such operator exists Ability to take many forms is.. Polymorphism (b) Encapsulation Member function (d) Inheritance

Ans:A

Ans:A

56

Chapter -4

Pointers & File Handling


Q.1. What is pointers ? Ans.: A pointer is a variable whose value is the address of another variable. Like any variable or constant, we must declare a pointer before we can work with it. The general form of a pointer variable declaration is: type *var-name; Here, type is the pointer's base type; it must be a valid C++ type and varname is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration: int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character Q2 What are the arithmetic operators used on pointers ? Ans There are four arithmetic operators that can be used on pointers: ++, --, +, Incrementing a Pointer: We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array: #include <iostream> const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer.

Object Oriented Technology using C++

57

ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the next location ptr++; } return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200 Decrementing a Pointer: The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below: #include <iostream> const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have address of the last element in pointer. ptr = &var[MAX-1]; for (int i = MAX; i > 0; i--) {

58

cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the previous location ptr--; } return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var[3] = 0xbfdb70f8 Value of var[3] = 200 Address of var[2] = 0xbfdb70f4 Value of var[2] = 100 Address of var[1] = 0xbfdb70f0 Value of var[1] = 10 Pointer Comparisons Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared. The following program modifies the previous example one by incrementing the variable pointer so long as the address to which it points is either less than or equal to the address of the last element of the array, which is &var[MAX - 1]: #include <iostream> const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have address of the first element in pointer. ptr = var; int i = 0;

Object Oriented Technology using C++

59

while ( ptr <= &var[MAX - 1] ) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the previous location ptr++; i++; } return 0; } When the above code is compiled and executed, it produces result something as follows: Address of var[0] = 0xbfce42d0 Value of var[0] = 10 Address of var[1] = 0xbfce42d4 Value of var[1] = 100 Address of var[2] = 0xbfce42d8 Value of var[2] = 200 Q.3. What is Arrays ? How to Initializing Arrays? Ans.: An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays: To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows: type arrayName [ arraySize ]; This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type.

60

For example, to declare a 10-element array called balance of type double, use this statement: double balance[10]; Initializing Arrays: We can initialize C++ array elements either one by one or using a single statement as follows: double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array: If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write: double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; You will create exactly the same array as you did in the previous example. balance[4] = 50.0; The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th ie. last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above:

#include <iostream> #include <iomanip> main () { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) { n[ i ] = i + 100; // set element at location i to i + 100 } cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; j++ )

Object Oriented Technology using C++

61

{ cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } return 0; } Pointer to an array We can generate a pointer to the first element of an array by simply specifying the array name, without any index. An array name is a constant pointer to the first element of the array. Therefore, in the declaration: double balance[50]; balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance: double *p; double balance[10]; p = balance; It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]. Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Q4 What is an array of Pointers? Ans The concept of array is very much bound to the one of pointer. In fact, the identifier of an array is equivalent to the address of its first element, as a pointer is equivalent to the address of the first element that it points to, so in fact they are the same concept. For example, supposing these two declarations: int numbers [20]; int * p; The following assignment operation would be valid: p = numbers; After that, p and numbers would be equivalent and would have the same properties. The only difference is that we could change the value of pointer p by another one, whereas numbers will always point to the first

62

Q5 Ans

of the 20 elements of type int with which it was defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an array can be considered a constant pointer. Therefore, the following allocation would not be valid: numbers = p; Because numbers is an array, so it operates as a constant pointer, and we cannot assign values to constants. What do you mean by Pointer to function? C++ allows operations with pointers to functions. The typical use of this is for passing a function as an argument to another function, since these cannot be passed dereferenced. In order to declare a pointer to a function we have to declare it like the prototype of the function except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name: #include <iostream> int addition (int a, int b) { return (a+b); } int subtraction (int a, int b) { return (a-b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return (g); } int main () { int m,n; int (*minus)(int,int) = subtraction; m = operation (7, 5, addition); n = operation (20, m, minus); cout <<n; return 0; }

Object Oriented Technology using C++

63

In the example, minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line: int (* minus)(int,int) = subtraction; Q6 A1 Explain Data File Handling in C++. File A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. Essentially there are two kinds of files that programmers deal with text files and binary files. Text files A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Binary files A binary file is no different to a text file. It is a collection of bytes. In C++ Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. C++ Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer. Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. Q7 What are the classes for file stream operation? Ans. Classes for file stream operation 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. Q8 How to open and close a file? Ans Opening a file

64

OPENING FILE USING CONSTRUCTOR ofstream fout(results); //output only ifstream fin(data); //input only OPENING FILE USING open() Stream-object.open(filename, mode) ofstream ofile; ofile.open(data1); ifstream ifile; ifile.open(data2); File mode parameter ios::app ios::ate ios::binary ios::in ios::out ios::nocreate ios::noreplace

Meaning

Append to end of file go to end of file on opening file open in binary mode open file for reading only open file for writing only open fails if the file does not exist open fails if the file already exist delete the contents of the file if it ios::trunc exist All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open(): fstream file; file.open ("example.bin", ios::out | ios::app | ios::binary); Closing File fout.close(); fin.close(); INPUT AND OUTPUT OPERATION put() and get() function the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream. example : file.get(ch); file.put(ch);

Object Oriented Technology using C++

65

write() and read() function write() and read() functions write and read blocks of binary data. example: file.read((char *)&obj, sizeof(obj)); file.write((char *)&obj, sizeof(obj)); ERROR HANDLING FUNCTION FUNCTION RETURN VALUE AND MEANING returns true (non zero) if end of file is eof() encountered while reading; otherwise return false(zero) return true when an input or output fail() operation has failed returns true if an invalid operation is bad() attempted or any unrecoverable error has occurred. good() returns true if no error has occurred. File Pointers And Their Manipulation All i/o streams objects have, at least, one internal stream pointer: ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation. ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written. Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream). These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions: moves get pointer(input) to a specified seekg() location moves put pointer (output) to a specified seekp() location tellg() gives the current position of the get pointer tellp() gives the current position of the put pointer The other prototype for these functions is: seekg(offset, refposition ); seekp(offset, refposition );

66

The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class. ios::beg start of the file ios::cur current position of the pointer ios::end end of the file example: file.seekg(-10, ios::cur); Q9. What is Exception Handling in C++? Ans. Exception Handling provides a mechanism to detect and report an exceptional circumstance, so that corrective action can be taken to set right the error occurred. Error Handler in C++ consists of three major keywords namely try, throw and catch. Throwing Exceptions: Exceptions can be thrown anywhere within a code block using throw statements. The operand of the throw statements determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown. Following is an example of throwing an exception when dividing by zero condition occurs: double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } Catching Exceptions: The catch block following the try block catches any exception. We can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch. try { // protected code }catch( ExceptionName e )

Object Oriented Technology using C++

67

{ // code to handle ExceptionName exception } Above code will catch an exception of ExceptionName type. If we want to specify that a catch block should handle any type of exception that is thrown in a try block, we must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows: try { // protected code }catch(...) { // code to handle any exception } The following is an example which throws a division by zero exception and we catch it in catch block. #include <iostream> using namespace std; double division(int a, int b) { if( b == 0 ) { throw "Division by zero condition!"; } return (a/b); } int main () { int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; }catch (const char* msg) {

68

cerr << msg << endl; } return 0; } Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block. If we compile and run above code, this would produce following result: Division by zero condition!

Multiple Choice Questions:


Q.1 (a) (b) (c) (d) Q2. (a) (b) (c) (d) Q3. (a) (c) Q4 (a) (c) Q5 (a) (b) (c) (d) Q6. To perform stream I/O with disk files in C++, you should open and close files as in procedural languages. use classes derived from ios. use C language library functions to read and write data. include the IOSTREAM.H header file. A pointer is: Address of a variable An indication of a variable to be accessed next A variable for storing address None of the above A data file must be closed using: Library function fpirint Exit function File *fp: Disk data file to be opened Both a and b

Ans: B

Ans:C

(b) (d)

Library function fclose None of the above

Ans:B

(b) (d)

Structure file None of the above

Ans:C

f close ( ) is a function: The values of its entire member only values of one member can be stored Only according to the size of its member None of the above

Ans:C

To read a single character from a file, we use the member function

Object Oriented Technology using C++

69

(a) (c) Q7.. (a) (c) Q8. (a) (c)

input put Ferror ( ) function is used for: return 1 if error return 0 if no error The purpose of a file buffer is: use memory to speed up arithmetic operations

(b) (d)

get read

Ans:B

(b) (d)

return 0 if error None of the above

Ans:C

(b) (d)

to speed up input/output to protect data

Ans:A

Q9. (a) (c) Q10. (a) (c)

If a file is opened in read mode, and it does not exist: There will be compile error (b) File will get created Link array of pointers (d) none of the above Int * arr [3]; this declares: A pointer to an array An array of pointers

Ans:C

(b) (d)

A pointer to an integer None of the above Ans:C

70

Program of C++
Q1 This program find the absolute value of an integer without using a function

#include <iostream> using namespace std; int main() { int number; int abs_number; // Ask for input cout << "This program finds the absolute value of an integer." << endl; cout << "Enter an integer (positive or negative): "; cin >> number; // Find the absolute value if(number >= 0) { abs_number = number; } else abs_number = -number; // Print out output cout << "The absolute value of " << number << " is " << abs_number; cout << endl; return 0; } Q2 This program finds the absolute value of an integer using a function int Abs(int i); // Function prototype int main() {

Object Oriented Technology using C++

71

int number; int abs_number; cout << "This program finds the absolute value of an integer." << endl; cout << "Enter an integer (positive or negative): "; cin >> number; // Calling the function Abs() abs_number = Abs(number); cout << "The absolute value of " << number << " is " << abs_number; cout << endl; return 0; } // Function definition int Abs(int i) { if( i >= 0) return i; else return -i; } Q3 Ttwo dimentional integer array to store integers from 1 to 10 and their squares. Ask user for a number, then look up this number in the array and then print out its corresponding square. #include <iostream> using namespace std; int main() { int sqrs[10][2] = { {1, 1}, {2, 4}, // The square of 2 is 4,and so on {3, 9}, {4, 16}, {5, 25}, {6, 36},

72

{7, 49}, {8, 64}, {9, 81}, {10, 100} }; int i, j; cout << "Enter a number between 1 and 10: "; cin >> i; // look up i for(j = 0; j < 10; j++) if(sqrs[j][0] == i) break; // break from loop if i is found cout << "The square of " << i << " is " ; cout << sqrs[j][1] << endl; return 0; }

Q4

A simple program demonstrating the use of reference #include <iostream> using namespace std; int main() { int Len, Wid;

// declare int variables

// Create references to int variables. // Now rLen and Len are aliases to each other, // and rWid and Wid are also aliases to each other. int &rLen = Len; int &rWid = Wid; // Initialized the two int variables

Object Oriented Technology using C++

73

Len = 10; Wid = 20;

// rLen is also initialized to be 10 // rWid is also initialized to be 20

// Printing out the values for int and int references cout << "Len is: " << Len << ", and Wid is: " << Wid << endl; cout << "rLen is: " << rLen << ", and rWid is: " << rWid << endl; cout << endl; // Printing out the address of int and references to int cout << "Address of Len is: " << &Len << endl; cout << "Address of rLen is: " << &rLen << endl; if(&Len == &rLen) { cout << "Address of Len is equal to address of rLen!" << endl; } cout << "Address of Wid is: " << &Wid << endl; cout << "Address of rWid is: " << &rWid << endl; if(&Wid == &Wid) { cout << "Address of Wid is equal to address of rWid!" << endl; } return 0; }

Q5

A simple program showing inheritance #include <iostream> using namespace std; class base { int i, j; public: void set(int a, int b) { i = a; j = b; } void show() { cout << i << " " << j << "\n"; }

74

}; // inheritance class derived : public base { int k; public: derived(int x) { k = x; } void showk() { cout << k << "\n"; } }; int main() { derived ob(3); ob.set(1, 2); // access member of base ob.show(); // access member of base ob.showk(); // uses member of derived class return 0; }

Q6

Inherite protected members of the base class #include <iostream> using namespace std; class base { protected: int i, j; // private to base, but accessible to derived public: void set(int a, int b) { i = a; j = b; } void show() { cout << i << " " << j << "\n"; } }; class derived : public base {

Object Oriented Technology using C++

75

int k; public: // derived may access base's i and j void setk() { k = i*j; } void showk() { cout << k << "\n"; } }; int main() { derived ob; ob.set(2, 3); // OK, known to derived ob.show(); // OK, known to derived ob.setk(); ob.showk(); return 0; } Q7 An example of multiple base classes. #include <iostream> using namespace std; class base1 { protected: int x; public: void showx() { cout << x << "\n"; } }; class base2 { protected: int y; public:

76

void showy() { cout << y << "\n"; } }; // Inherit multiple base classes. class derived: public base1, public base2 { public: void set(int i, int j) { x = i; y = j; } }; int main() { derived ob; ob.set(10, 20); // provided by derived ob.showx(); // from base1 ob.showy(); // from base2 return 0; }

Q8

Using base pointers on derived class objects. #include <iostream> #include <cstring> using namespace std; class B_class { char author[80]; public: void put_author(char *s) { strcpy(author, s); } void show_author() { cout << author << "\n"; } }; class D_class : public B_class { char title[80]; public:

Object Oriented Technology using C++

77

void put_title(char *num) { strcpy(title, num); } void show_title() { cout << "Title: "; cout << title << "\n"; } }; int main() { B_class *p; B_class B_ob; D_class *dp; D_class D_ob; p = &B_ob; // address of base // Access B_class via pointer. p->put_author("Tom Clancy"); // Access D_class via base pointer. p = &D_ob; p->put_author("William Shakespeare"); // Show that each author went into proper object. B_ob.show_author(); D_ob.show_author(); cout << "\n"; /* Since put_title() and show_title() are not part of the base class, they are not accessible via the base pointer p and must be accessed either directly, or, as shown here, through a pointer to the derived type. */ dp = &D_ob;

78

dp->put_title("The Tempest"); p->show_author(); // either p or dp can be used here. dp->show_title( ); return 0; }

Q9

Vitual function and polymorphism #include <iostream> using namespace std; class figure { protected: double x, y; public: void set_dim(double i, double j=0) { x = i; y = j; } virtual void show_area() { cout << "No area computation defined "; cout << "for this class.\n"; } }; class triangle : public figure { public: void show_area() { cout << "Triangle with height "; cout << x << " and base " << y; cout << " has an area of "; cout << x * 0.5 * y << ".\n"; } };

Object Oriented Technology using C++

79

class square : public figure { public: void show_area() { cout << "Square with dimensions "; cout << x << "x" << y; cout << " has an area of "; cout << x * y << ".\n"; } }; class circle : public figure { public: void show_area() { cout << "Circle with radius "; cout << x; cout << " has an area of "; cout << 3.14 * x * x << ".\n"; } }; int main() { figure *p; // create a pointer to base type triangle t; // create objects of derived types square s; circle c; p = &t; p->set_dim(10.0, 5.0); p->show_area(); p = &s; p->set_dim(10.0, 5.0); p->show_area(); p = &c; p->set_dim(9.0);

80

p->show_area(); return 0; }

Object Oriented Technology using C++

81

Keywords
Abstract class A class defining an interface only; used as a base class. Declaring a member function pure virtual makes its class abstract and prevents creation of objects of the abstract class. Base class A class from which another more specialized class is derived, which defines a portion of the interface and/or implementation of the derived class. See also derived class. Binary operator An operator such as + or = which takes two arguments, which appear on either side of the operator. Apart from the syntax, a binary operator is exactly equivalent to a function taking two arguments. A binary operator can be defined either as a global function, or as a member function of its first (left side) argument. bool (C++ intrinsic type) bool is a C++ intrinsic type used to represent Boolean (true/false) values. Class One of the key concepts in object-oriented programming, a class is the most general kind of user-defined type, defining both the state information used by objects of the class (data members) and their behavior (member functions). Classes may be related to one another via inheritance relationships, wherein base classes define portions of the interface and/or implementation of derived classes. Constructor A special member function of a class, used to create and initialize objects of that class. cpp file (for a system class) A C++ source code file sometimes used to store the functions defining the behavior of a system class, named the same as the system class, but with the extension ".cpp". A .cpp file is used only in cases where the .h file has been modified by hand, and only when the system class designer chooses to do so, in order to permit separate compilation. Data member An object (or variable) that constitutes part of the state information for a given class. A class may have any number of data members, each with its

82

own unique name, and each may be of any legal C++ type. Ordinary (nonstatic) data members are used to store data related to one specific object of the class, and are accessed using a dotted" notation, as shown: myObject.myDataMember. Static data members are used to store data shared among all objects of the class, and are accessed using the class name followed by a double colon, as follows: MyClass::myStaticDataMember. Derived class A class that is derived from another less specialized class, its base class, which defines a portion of the interface and/or implementation of the derived class. See also derived class. Destructor A special member function for a class, called when an object of that class is to be removed from memory, and typically used to perform any necessary cleanup, such as freeing dynamically allocated memory. For-loop A loop that repeats the same sequence of comands until a specified condition is met. Typically a for-loop has a loop variable, and integer variable which starts at zero and increments with each iteration of the loop, and exit condition is met when that counter reaches a specified number. Header file A source code file, typically with the extension ".h", intended to be included into other source code files, both .h and .cpp. One common use is define constants used in multiple places; another is to define the interface for one or more classes and/or global functions, but often not the actual implementation, which instead is put into a separate .cpp file, so that it may be compiled separately. Inheritance One of the key concepts of object-oriented programming (OOP), inheritance is the mechanism by which one class, a derived class, can derive part of its interface and/or implementation from another, its base class. The derived class inherits all the data members and member functions of its base class, and may add its own. Also, a base class may define virtual methods, used to provide a common external interface to all derived classes, while permitting their specific behaviors to differ. Instance (of a class) Generally, the term "instance" refers to a specific object of the class, resident in memory. Sometimes the term is also used to refer to a specific

Object Oriented Technology using C++

83

variable of the class type, such as a data member of a class, even when that same variable may represent multiple actual objects. For each (non-static) data member of a class, there are as many actual objects as there were instances of the class. We sometimes refer to the latter case as a usage instance, to distinguish it from the first. Loop variable An integer variable, used in conjunction with a for-loop, which starts at zero and increments with each iteration of the loop, and exit condition is met when that counter reaches a specified number. Member function A function associated with a particular class that defines part of the interface and behavior of that class. Ordinary (non-static) member functions define operations that effect one specific object of the class, and are invoked using a dotted" notation, as shown: myObject.myMemberFunction(). Static member functions define operations not necessarily related to any specific object of the class, such as operations that involve static data members of the class, and are invoked using the class name followed by a double colon, as follows: MyClass::myStaticMemberFunction() Object One of the key concepts of object-oriented programming (OOP), an OOP object is analogous to a real world object, in that objects can be created and destroyed, and each object has its own state information, which can evolve over time, in accordance with specified behavioral rules. In C++ each object is an instance of some class, and it is the class that defines the nature of the state information, in the form of data members, and behavior, in the form of member functions. Object-oriented programming A programming paradigm based on the concepts of objects and classes, as opposed to procedures. Many developers find that object-oriented programming, or OOP, conforms much more closely to the way they naturally think about problem solving and design. Pointer A simple object that records the address of some other object, of some specified type. Pointers can be used to access the pointed-to object by means of the dereference operator (*) and the member dereference operator (->)

84

Template Templates are the C++ version of generic types, used to define classes and functions that can be used with typed objects, where the type matters, but where at least part of the desired behavior can be defined independent of the specific type. Typical examples include multi-object container classes, such as lists, and proxy objects. A template class or function is defined in terms of one or more template arguments, used to represent the unspecified type or types. Template class A class defined in terms of one or more template arguments. Template function A function defined in terms of one or more template arguments. Virtual member function A member function of a class designed for use as a base class, used to define a common interface to all derived classes, while allowing the behaviors of derived classes to differ. The base class may define a default behavior (implementation of the function), which the designer of a derived class may choose to override. If the base class does not provide a default the function is called a "pure virtual function", and each derived class must provide its own implementation. Void A C++ keyword used in place of the return type to indicate that a function does not have a return value, and also used in place of the referent type when declaring pointers to objects of unspecified type.

Object Oriented Technology using C++

85

Bibliography
Books ReferredThe C++ Programming Language by Bjarne Stroustrup, Complete Reference by Herberld Sheild, C++ programming by E.Balaguruswami.

Websites ReferredWikipedia, www.c++programming.com www2.imperial.ac.uk www.cplusplus.com, www.tutorialspoint.com/cplusplus www.mycplus.com

Anda mungkin juga menyukai