QUESTIONS AND ANSWERS FOR OBJECT ORIENTED PROGRAMMING IN C

++

SARUMATHI PUBLICATIONS
No. 109, Pillayar Kovil Street, Periya Kalapet Pondicherry – 605014, India Phone: 0413 – 2656368 Mobile: 9786554175, 8940872274

QUESTIONS AND ANSWERS FOR OBJECT ORIENTED PROGRAMMING IN C++

G.Appasami, M.Sc., M.C.A., M.Phil., M.Tech., Assistant Professor Department of Computer Science and Engineering Dr. Pauls Engineering Collage Pauls Nagar, Villupuram Tamilnadu, India.

SARUMATHI PUBLICATIONS
No. 109, Pillayar Kovil Street, Periya Kalapet Pondicherry – 605014, India Phone: 0413 – 2656368 Mobile: 9786554175, 8940872274

First Edition: July 2010 Second Edition: July 2011

Published By

SARUMATHI PUBLICATIONS

© All rights reserved. No part of this publication can be reproduced or stored in any form or by means of photocopy, recording or otherwise without the prior written permission of the author.

Price Rs. 60/-

Copies can be had from SARUMATHI PUBLICATIONS No. 109, Pillayar Kovil Street, Periya Kalapet Pondicherry – 605014, India Phone: 0413 – 2656368 Mobile: 9786554175, 8940872274

Printed at Meenam Offset Pondicherry – 605014, India

OBJECT ORIENTED PROGRAMMING IN C++

QUESTIONS WITH SHORT ANSWERS

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

1

1. Who developed C++? C++ was developed at AT & T Bell laboratories in the early 1980s by Bjarne Stroustrup. The name C++ (pronounced as C plus plus) was coined by Rick Mascitti where “++” is the C increment operator. 2. Explain Basic Concepts of OOP ☺ 2. List out the Salient features of OOP 2. Write the characteristics of OOP 2. List out the elements of OOP The basic concepts of OOP are Class, object, Data abstraction, Encapsulation, Inheritance, Polymorphism, Dynamic binding and message passing. Concept Class Object Abstraction Encapsulation Meaning Class is a user defined data type Object is an run time entity of class The act of representing essential features without including the background details The wrapping up of the data and functions into a single unit (called class) is known as encapsulation The mechanism of deriving a new class from existing class is called inheritance The ability to take more than one form. More operations in same name. polymorphism means one name multiple forms The addresses of the functions are determined at run time rather than compile time (late binding). Linking of a procedure to execution code. Objects interaction by sending messages to each other

Inheritance Polymorphism

Dynamic binding

Message Communication

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

2

3. What are the Applications of OOP? ® • • • • • • • • Real time systems Simulation and modeling Object – Oriented Data bases Hypertext, hypermedia and expert text AI and Expert Systems Neural networks and expert systems Desition support and office automation systems CIM/CAD/CAM Systems

4. How does a C++ Class differ from a C++ structure? Structure Default access is public Data Default inheritance type is public 5. What is namespace? Namespace is a collection of classes arranged in a hierarchical order. If we include more header files, then there is a chance to have same classes in different files. This is a problem for compiler to select a class from which header file. This problem is solved by standard namespace. Ex.: using namespace std; 6. Write a simple C++ program to print a string on a screen #include<iostream.h> main() { cout<<”C++ is Super set of C”; } 7. Write a simple C++ program using class and objects #include<iostream.h> class person //New data type { char name[30]; //Data member int age; //Data member public: //Public access
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 3

Class Default access is private Data & functions Default is private inheritance

void getdata(void); void display(void);

//Function declaration

}; void person : : getdata(void) //Function definition { cout<< “Enter Name: ”; cin>>name; cout<< “Enter age: ”; cin>>age; } void person : : display(void) { cout<< “\n Name: ” << name; cout<< “\n Age: ” << age; } main() { person p; //Person object p.getdata(); p.display(); }

8. Explain Input and Output operators in C++ 8. Explain Extraction and Insertion operators in C++ The operator >> is known as extraction or get from operator. It extracts (takes or inputs) the value from the keyboard. eg: cin>>sum; The operator << is called the insertion or put to operator. It inserts (sends or outputs) the contents of variables or messages. eg: cout<<”SUM”<<sum; The Identifiers cin and cout are predefined objects. the operators << and >> can be overloaded.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

4

9. Write the structure of C++ program A typical C++ program would contain four sections as shown in the figure. Include files Class declaration Class function definitions Main function program 10. What stream class is required to create an output stream? ® Ostream classes is required to create an output stream. Note: istream class for input. Iostream for input & output 11. What are the uses of void? ® • To specify the return type of function when it is not returning any value. • To indicate an empty argument list to a function. 12. What variable? S 1 2 3 are the difference between normal variable and reference reference variable It holds address It is a pointer to another variable. It is a variable to store address of another variable in memory Ex.: int *ptr;

normal variable It holds data It is not a poiner It is a variable to store value in memory 4 Ex.: int x;

13. Write C++ character set Like the C language, C++ also comprises a character set from which the tokens (basic types of elements essential for programming coding) are constructed. The character set comprises of “A” .. “Z” , “a” .. “z”, 0 .. 9, +, -, /, *,\, (, ), [, ], {, }, =, !=, <, >, . , ’ “ ; : %, ! , &, ?, _, #, <=, >=, @, white space, horizontal tab, carriage return and other characters.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

5

14. What is a TOKEN? ® A token is the smallest individual unit in a program. Tokens are classified as shown in Figure.

15. List out few key words in C++.

16. Explain operator and operand. Operator specifies an operation to be performed that yields a value. An operand is an entity on which an operator acts. For example: RESULT = NUM1 + NUM2 NUM1 and NUM2 are operands. + is the additional operator, that performs the addition of the numbers. The result (value) generated is stored in the variable RESULT by virtue of “=” (Assignment) operator. Table shows the operators in C++. 17. List out the operators in C++

The following operators are specific to C++. :: .* ->* ::* new delete endl setw

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

6

18. List out the Advantages of new operator 1. New operator automatically computes the size of the data object. We need not use the size of operator. 2. It automatically returns the correct pointer type. So that there is no need to use a type cast. 3. It is possible to initialize the object while creating the memory space. 4. Like other operator, new and delete can be overloaded. 19. List out the Operators classification. Operators are classified as Arithmetic, Assignment, Component Selection,  Shift, Conditional Logical, Manipulator, Member dereferencing, Preprocessor, Relational, Scope Resolution, Type Cast Memory Management. etc Based on operand requirements, operators are also classified as Unary operators require one operand: &, !, *, ++, --, +, -, ~. Binary operator requires two operands: +, -, *, /, <, <=, <<, ==, +=, &, |, ^, ., ->, .*, ... Ternary operator requires three operands: ?: 20. What are all the operators that cannot be overloaded? ® Direct member access operator De-reference pointer to class member operator Scope resolution operator Conational operator Size of operator 21. What are the uses of scope resolution operators? ® • • • • It is used to define local or global of data and funs. It is used to qualify hidden names It is used to qualify class member names It is used to get or set the inner or outer variables.
7

. .* :: ?: Sizeof

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

22. Can the precedence order of an operator be altered? Yes, the precedence order of an operator can be altered by using parenthesis. 23. Give an example for type cast operation int avg, sum, num; avg = sum / float(num); Now num integer variable is promoted to float 24. Explain Expression with an example. An expression is a combination of operators, constants and variables arranged as per the rule of the language. It may also include function call with return call. An expression may consist of one or more operands and zero or more operators to produce value. Ex. A=(B/2)+(C*10.5) 25. What is an expression? An expression is a program construct or operation created by combination of operators and operands. Ex.: C = A+ B 26. Write the types of expressions There are four types of expressions. They are: Constant expressions consist of only constant values Ex.: 15 25+10/2.0 ‘M’ Integral expressions are those which produce integer results Ex.: m*n-5 m-‘x’ 5+int(2.7) Where m and n are integer variables Float expressions are those which produce floating-point results Ex.: x+y x*y/10 5+float(10) Where x and y are floating-point variables Pointer expressions produce address variables Ex.: &m *ptr ptr+1 Where m is a variable and ptr is a pointer

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

8

27. Write branching and looping statements? ® Branching (Selection ) if, if-else and switch Looping while, do-while and for 28. What is implicit conversion? 28. What is automatic conversion? ® Whenever data types are mixed in an expression, C++ performs the conversions automatically. This process is known as implicit or automatic conversion. Consider an expression with mixed data types like m=5+2.75 is a valid statement. 29. List out some basic data types in C++ Name char short int (short) int Range* signed: -128 to 127 Character or small integer. 1byte unsigned: 0 to 255 signed: -32768 to 32767 Short Integer. 2bytes unsigned: 0 to 65535 signed: -2147483648 to 2147483647 Integer. 4bytes unsigned: 0 to 4294967295 signed: -2147483648 to 2147483647 Long integer. 4bytes unsigned: 0 to 4294967295 Boolean value. It can take one of two values: true or 1byte true or false false. +/- 3.4e +/- 38 (~7 Floating point number. 4bytes digits) +/- 1.7e +/- 308 (~15 Double precision floating 8bytes digits) point number. +/- 1.7e +/- 308 (~15 Long double precision 8bytes digits) floating point number. 2 or 4 1 wide character Wide character. bytes Description Size*

long int (long)

bool float double long double wchar_t

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

9

30. Define widening conversion Converting from smaller data type to wider data type is called widening conversion. Conversion of a char or short int to int is called integer widening conversion. 31. Explain water fall model of type conversion ☺ Converting from smaller data type to wider data type is called widening conversion. Widening conversion is also called as water fall model of type conversion. The water fall model is shown in the below figure. Short char

int unsigned int long int unsigned long int float double long double 33. Explain function prototyping ® Function prototyping is a declaration statement in the calling program. The general form is as follows: Return-type function-name (argument-list); Example 1: float volume(int x, float y, float z); Example 1: float area(float, float );

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

10

33. What is call byValue? ® If a function called with actual value is called call by value. Ex. int swap (int a, int b) 34. What is call by reference? ☺ If a function called with reference variables is called call by reference. void swap (int &a, int &b) { int t =a; a=b; b=t; } swap (&x, &y); Because it works on original data. x and y value gets change permanently. 35. What is return by reference? A function returns a reference is known as return by reference int & max(int &a, int &b) { if (a>b) return a; else return b; } int * ptr = max(&x, &y) this function may return address of x or y to ptr. 36. What is function overloading? ☺ Family of functions with one function name but with different argument lists. Depending on the arguments correct function will be invoked. This process is known as function overloading. This is also known as function polymorphism (compile time polymorphism). EX: //declarations add(int, int) //prototype1 add(float,float) //prototype2
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 11

add(int, float) //function call cout<<add(10, 7.5); cout<<add(2.5, 7.5); cout<<add(10,20);

//prototype3 //uses prtotype3 //uses prtotype2 //uses prtotype1

40. What is inline function? ☺ An inline function is a function that is expanded in line when it is invoked. That is, The compiler replaces the function call with the corresponding function code. The inline function is defined as follows: Syntax: Inline fun_header { Function body } Example: inline float cube(float a) {return(a*a*a);) 37. Explain virtual function ☺ Same function name in both the base and derived classes, the function in the base class is declared as virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather then the type of the pointer. Thus by making the base pointer to point to different objects, we can execute different versions of virtual function virtual void show() { cout<< “\n show base”;} 38. Explain pure virtual function ® if zero is assigned to a virtual function , then the virtual function is called as pure virtual function. Example: Class A { virtual void show()=0; }
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 12

39. What is friend function? ☺ The non member function is defined elsewhere in the program like a normal C++ function. The function definition doest use either the key word friend or the scope operator ::. The functions that are declared with the keyword friend are known as friend function. Ex: class A { Int a[20]; Public: getdata(); {for (int i=0;i<20;i++) cin>>a[i];} showdata(); {for (int i=0;i<20;i++) cout <<a[i];} friend sum(int *s); }; //a non member function of class A sum( int *s) { int a; for (int i=0;i<20;i++) a=a+s[i]; return a; } 41. What is the advantage of using inline function? ® An inline keyword before a function suggests the compiler to insert the complete body of the function wherever that function is invoked. Inline function is typically used to eliminate the inherent cost involved in calling a function. It is typically used or functions that need quick execution. Some times compiler may ignore inline expansion. 42. What is default argument? ® An argument value that is specified in the function declaration is used for corresponding omitted argument while calling the function. Ex. float intamout (float p, int t, float r=0.15) r=0.15 is the default argument.
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 13

43. What is constant argument? ® If function arguments are declared as const. they the arguments are called comstant argument. The function arguments should not modified in some cases like interest rate. float intamout (float p, int t, const float r=0.15) This is important only when we pass arguments by reference or pointer. 44. State the properties of static function? ® A member function that is declared static has the following properties: • A static function can have access to only other static members (variables and functions) declared in the same class. • A static member function can be called using the class name (instead of its objects) as follows: Calss_name :: function_name; 45. Explain array of objects. ☺ Set of objects of same class with the same name and stored in continuous memory locations Array of objects are collection of objects of same class that are referred by a common name. Ex; class stack { Int top, a[20]; Public: Push(); Pop(); } Main() { Stack s[5]; --}

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

14

46. State the properties of static member functions Static member functions can also be defined in the private region of a class. Private Static member functions can access only Static data member and can invoke Static member functions . 47. What is abstract data type? ☺ An abstraction that describes a set of objects in terms of an encapsulated or hidden data and operations on that data is called abstract data type. 48. What is abstract data type? Abstract collection of data elements and their accessing functions. Classes use the concept of abstraction and are defined as a list of attributes and functions to operate on these attributes. They encapsulate all the essential properties of the objects. Since the classes use the concept of data abstraction, they are known as abstract data types. Ex: class stack { Int top, a[20]; Public: Push(); Pop(); }

49. What are the different types of access specifiers? ☺ Class members can have the following access specifiers Private is the default access and private members are accessible only from the member functions of the same class and/or from their friend class. Protected members are accessible from member function of the same class and/or friend classes, and also from members of their immediate derived class Public members are accessible from anywhere the class is visible.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

15

50. What is data abstraction? Data abstraction refers to the act of representing essential features without including the background details or explanations. 51. Explain encapsulation ® The wrapping up of data and functions into a single unit (called class) is known as encapsulation. The mechanism by which the data and functions are bound together with in an object definition is called encapsulation. 52. What is a class? ☺ A class is a user defined data type. It is a blue print, which defines the variable and methods common to all objects of a certain kind. 53. What is a class? A group of objects that share common properties and relationships is called class. In C++, A class is a new data type that contains member variables and member functions that operate on the variables. A class is defined with a keyword class. 54. What is an abstract class? ® A class that serves only as abase class from which classes are derived is called abstract class. No objects are created for abstract class. A class contains a pure virtual functions is an abstract class. 55. What is a container class? ® A class that contains objects of other classes is called container class 56. What is an object? ☺ A variable whose type is a class is called an object. An instance of a class is known as an object. objects are Run time entities in object oriented programming

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

16

57. What is an instance? An instance is an object of a particular class. The term instance and objects are interchangeable. An object has state, behavior and identity, State defines the attribute (data member) of an object. Behavior defines method or function used to modify the state of an object. Identity is name of an object. 58. What is Call by reference? ☺ A function call mechanism that passes arguments to a function by passing the address of the arguments. 59. What is Call by value? ☺ A function call mechanism that passes arguments to a function by passing a copy of the values of the arguments. 60. Explain constructor with example ☺ A constructor is a special function whose task is to initialize the objects of its class. It is special because its name is the same as the class. Class stack { int top; Public: stack() {top =0;} --} 61. Explain destructor with example ☺ Destructor is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is same as the class name but it is preceded by tilde. ~stack(){} 62. What are the main function return types? ® void and integer
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 17

63. How constructors differ from normal functions? ® A constructor is a member function of a class that is used to create objects or initialize objects of that class. It has the same name as the class itself, has no return type and is invoked while creating the objects. A method is an ordinary function of a class. it has its own name, a return type and is invoked explicitly using the dot operator. 64. List out the properties of constructors 1. Constructors should be declared in public section. 2. They are invoked automatically when objects are created 3. They do not have return type. 4. They must use name of the class. 65. What are the difference between default and parameterized constructors? ® The constructors which does not take arguments explicitly is called default constructor. Constructors with arguments are called parameterized constructors. 66. What are all the operators that cannot be overloaded? ☺ Direct member access operator De-reference pointer to class member operator Scope resolution operator Conational operator Size of operator 67. Explain type conversion ® Converting data from one type to another type is called type conversion. Three types of data type conversions are A. Conversion from built-in type to class type. B. Conversion from class type to built-in type. C. Conversion from one class type to another class type. . .* :: ?: Sizeof

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

18

68. What is the use of virtual base class? ® The duplication of inherited members due to multi paths can be avoided by making the common base class (ancestor class). 69. What is the use of public access mode? Public accessible members can be accessed from outside the class. 70. What is the default access mode in a class? ® Private is the default access mode in a class 71. What are the functions supported by file stream class for performing I/O operations? ® Put() get() open() close() read() write()

72. What are the file ptr functions available in C++ ® what are the functions for manipulation of file pointers? seekg() -> indicates the file pointer position moved by the get pointer seekp() -> indicates the file pointer position moved by the put pointer tellg() -> tells the file position moved by get pointer tellp() -> tells the file position moved by put pointer 73. What are the file stream classes available in C++? fstream, ifstream, ofstream, fstreambase and filebuf 74. What is an I/O stream? ® A stream is a sequence of bytes. The source stream that supplies data to the program is called input stream and the destination stream that receives data from the program is called output stream. 75. What is dynamic initialization? ® C++ permits initialization of variables at run time. This is referred as dynamic initialization.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

19

OBJECT ORIENTED PROGRAMMING IN C++

QUESTIONS WITH DESCRIPTIVE ANSWERS

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

20

1. Explain the basic concepts of OOP The basic concepts of OOP are Class, object, Data abstraction, Encapsulation, Inheritance, Polymorphism, Dynamic binding and message passing. A. Class A group of objects that share common properties and relationships is called class. A class is a new data type that contains member variables and member functions that operate on the variables. A class is defined with a keyword class. A class is a user defined data type. It is a blue print for objects, which defines the variable and methods common to all objects of a certain kind. Example: person class: class person { char name[30]; int age; public: void getdata(void); void display(void); }; //New data type class person //Data member //Data member //Public access //Function declaration

B. Objects The class variables are known as objects. An instance of a class is known as an object. Objects are Run time entities in object oriented programming Example: person object p: main() { person p; p.getdata(); p.display(); }

//Person object

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

21

C. Data abstraction The act of representing essential features without including the background details or explanations is known as data abstraction. Class uses the concept of abstraction. Since class uses the concept of data abstraction, they are known as Abstract Data Types. D. Encapsulation The wrapping up of the data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. these functions provide the interface between the object’s data and the program. This insulation of the data from direct access by the program is called data hiding. E. Inheritance The mechanism of deriving a new class from existing class is called inheritance. There are different kinds of inheritance namely single, multiple, multilevel inheritance, Hierarchical and Hybrid Ex.: Single Inheritance A derived class with only one base class is called Single Inheritance

Parent

Child Class Child : public Parent F. Polymorphism The ability to take more than one form is called polymorphism. That is, more operations in same name. Polymorphism means one name with multiple forms. Run time polymorphism and compile time polymorphism are the two kinds of polymorphism.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

22

Polymorphism

Compile time Polymorphism

Run time Polymorphism

Function overloading

Operator overloading

Virtual functions

G. Dynamic binding The addresses of the functions are determined at run time rather than compile time (late binding). Linking of a procedure to execution code is done at run time is called dynamic binding. H. Message Communication Objects communicate with one another by sending and receiving information. A message for an object is a request for execution of procedure. Message passing involves specifying the name of the object, the name of the function (message) and information to be sent. Example is given below :

employee . salary (name);

object

message

Information object

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

23

2. What are the Principal Advantages of OOP? ☺ 2. What are the merits of OOP Methodology? 2. What are the Benefits of OOP/OOM? OOP offers several befits to both the program designer and the user. The principal advantages are: • Through inheritance, we can eliminate redundant code and extend the use of existing classes • We can build programs from the standard working modules (Reusability of code by Inheritance). • The principle of Data hiding (encapsulation) helps programmer to build secure program. • Program developed by modules through classes • It is possible to have multiple instances of class – objects to coexist without any interface. • It is possible to map objects in the problem domain to those objects in the program. • It is easy to Portion the work based on objects • Data centered and Bottom-Up design approach. • Object oriented systems can be easily upgraded from small to large systems. • Message passing technique for communication between objects. • Software complexity can be easily managed. 3. Explain object oriented programming paradigm ® 3. Explain object oriented programming approach 3. Explain object oriented programming Methodology Object oriented programming approach provides solution to some of flaws encountered in procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operates on it and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these entities. The organization of data and functions in OOP is shown in the figure given below:

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

24

Object A Data Functions

Object B Data Functions

Object C Data Functions

The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the function of other objects. Some of the striking features of OOP are: • Emphasis is on data rather than procedure. • Programs are divided into elements called objects. • Data structures are designed such that they characterize the objects (Abstraction). • Functions and data tied together into a single unit called encapsulation. • Data is hidden (private data) and cannot be accessed by external functions. • Objects may communicate with each other through functions. • New data and functions can be easily added whenever necessary (inheritance). • Bottom-up approach in program design. OOP is the most recent concept among programming paradigms. Class and objects are the building blocks in OOP. An object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

25

4. Write the difference between C & C++. ☺ C: C is a Procedural Programming. It was developed at AT & T Bell laboratories in 1972 by Dennies Ritchie From the language B. C++: C++ is an Object Oriented Programming. It was developed at AT & T Bell laboratories in the early 1980s by Bjarne Stroustrup.from the languages C and Simula67. C C is a subset of C++ Procedure Oriented Programming (POP) Top down approach Structured Programming Importance in given for program Does not support objects C provides Action/Structure/function oriented programming C is not a strong type checking language C does not supports error handling Function overloading and function overriding are not availed in C C does not supports Templates Scanf & printf functions for getting and showing values Input and out put format like %d, %f, %c… are required in I/O process C++ C++ is super set Object Oriented Programming (OOP) Bottom up approach Modular Programming Importance is given for data Supports objects C++ provides Object Oriented Programming with features like Abstraction, Encapsulation, Inheritance and polymorphism C++ is a strong type checking language C++ supports sophisticated error handling using the Exception Handling Function overloading and function overriding can be done in C++ C++ supports Templates Cin and cout stream operators for getting and showing values No format is required in c++ in I/O process

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

26

5. Explain Data Types in C++ ☺ Data Types are the kind of data that variables hold in a programming language. The ability to divide data into different types in C++ enables one to work easily with complex objects.

C++ Basic Data Types and their size in bytes Type char, unsigned char and signed char int, unsigned int, signed int and short int long int, unsigned long int and signed long int float double long double char and signed char value varies from -128 to 127 unsigned char value varies from 0 to 255 int and signed int value varies from -32768 to 32767 unsigned int value varies from 0 to 65535

Bytes 1 2 4 4 8 10

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

27

6. Explain Storage Class / Storage Specifiers Storage Class is another qualifier (like long or unsigned) that can be added to a variable declaration. The four storage specifiers are auto, static, extern and register. static and register variables are automatically initialized to zero when they are declared. Auto variables are not initialized with appropriate values based on their data type. These variables get undefined values known as garbage. Storage auto Meaning Example

Defines local variable known to void main() the block in which they are { autofloat ratio; defined. By default the local int kount; variables are auto hence rarely } used. Global scope but one time void fun() initialization { static int x; x++; } Global variable known to all extern int filemode; functions in the current extern void factorial(); program. These variables are defined in another program. The modifier register instructs void fun() the compiler to store the {register int I;} variable in the CPU register to optimize access.

static

extern

register

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

28

7. What are the difference between break and continue? Break statement tells to compiler that to exit from a loop or switch case. If loops are nested, the break would only exit from the loop containing it. That is, break will exit only a single loop. Break statement at the end of the switch case causes an exit from the switch statement.
while(test-con) { --------if(cond) break; -------} switch(expresion) { case 1: block1 break; case 2: }

The continue statement tells to compiler that to skip the remaining statements and continue with next iteration.
while(test-con) { --------if(cond) continue; -------} for(ini;test;inc) { --------if(cond) continue; -------}

Break Continue Break will exit only from a single Continue will skip remaining lines loop for one iteration. Used in loop and branch control Loop is terminated Used only in loop control Loop is continued

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

29

8. Explain Control Structures in C++ ® Statements in a program need not necessarily be executed in a sequential order. Some segments in a program are executed based on a condition. In such situations the flow of control jumps from one part of the program to another. Program statements that cause such jumps are called as control statements or control structures.

Control structure

Selection

Sequence

Loop structure

if ,if else

switch

do-while

while, for

Control structures

Sequence

Selection (Decision making & Branching)

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

30

Loop IF (Branch) if (expression is true) { action 1; } action 2; action 3;

If(age>60) { Int_rate=Int_rate+0.5; } Interest=P*y*Int_rate; Cout<<Interest;

If condition is true then it will execute action 1 otherwise it would not execute action 1. IF – ELSE (Two – way branch) if (expression is true) { action 1; } else { action 2; } action 3; If(mark>=50) { Result=”Pass”; } else { Result=”Fail”; } Cout<<Result;

If condition is true then it will execute action 1 otherwise action 2 will be executed.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

31

SWITCH (Multiple branches) switch (expression ) { case 1: { action 1; } case 2: { action 2; } case 3: { action 3; } default: { action 4; } } action 5; Switch(option) { case 1: { Push(); } case 2: { Pop(); } case 3: { Display(); } default: { Cout<<”No”; } } Cout<<”Switch over”;

This is a multiple-branch statement. Based on expression control is transferred to one of the many possible points.

DO – WHILE (exit controlled loop) do Int n=100,sum=0, i=0; { do action 1; { sum=sum + i; i++ } } while(condition is while(i<n); true); Cout<<sum; action 2;

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

32

The do-while is an exit-controlled loop. Based on the true condition, the control is transferred to back to loop.

WHILE (entry controlled loop) while(condition true) { action 1; } action 2; is Int n=100,sum=0, i=0; while(i<n) { sum=sum + i; i++ } Cout<<sum;

Similar to do-while loop, but it is an entry controlled one.

FOR(entry controlled loop) for (initial condition; test; increment) { action 1; } action 2; Int n=100,sum=0 for (i=0; i<n; i++) { sum=sum + i; } Cout<<sum;

The for loop is an entry-controlled loop and is used when an action is to be repeated for a predetermined number of times.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

33

9. Explain Classes and objects with example ☺ Class The most important feature of C++ is the “Class”. Its significance is highlighted by the fact that Bjarne Stroustrup initially gave the name ‘C with Classes ‘. A class is a new way of creating and implementing a user defined data type. A group of objects that share common properties and relationships is called class. In C++, A class is a new data type that contains member variables and member functions that operate on the variables. A class is defined with a keyword class. A class is a user defined data type. It is a blue print for objects, which defines the variable and methods common to all objects of a certain kind. Characteristics of a class: • • • • • The keyword class specifies user defined data type class name The body of a class is enclosed within braces and is terminated by a semicolon The class body contains the declaration of variables and functions The class body has three access specifiers ( visibility labels) viz., private , public and protected Specifying private visibility label is optional. By default the members will be treated as private if a visibility label is not mentioned The members that have been declared as private, can be accessed only from within the class The members that have been declared as protected can be accessed from within the class, and the members of the inherited classes. The members that have been declared as public can be accessed from outside the class also

• •

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

34

Structure of a class class class_name { private: variable declarations; Data Declaration Function Declaration Function Definition }; function definitions function declarations; public: variable declarations; function declarations;

Class Name

#include<iostream.h> class item //class declaration { int number; //private data member float cost; //private data member public: void getdata (void);//prototype declaration void putdata(void); //function defined here }; void item :: getdata (void) //function definition { cout<<”\nEnter an Item Number\n” cin>>number; cout<<”\nEnter the Item Cost\n” cin>>cost; } void item :: putdata (void) //function definition { cout<<”number : ”<< number<<”\n”; cout<<”cost : “<<cost<<”\n”; }
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 35

main() { item x; //create object cout<<”\n Object x”; x.getdata(); //call member function x.putdata(); } Output: In this example, item is a new data type created using the keyword ‘class’. the item class consists of private data members and public functions. Objects In C++, the class variables are known as objects. An instance of a class is known as an object. Objects are Run time entities in object oriented programming main() { item x; x.getdata(); x.putdata(); } Here we created an object ‘x’ of type item class. The member functions are called using (.) Dot operator. Consider the line given below: //create object //call member function //call member function

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

36

Array of objects item x[100]; The above line will create 100 arrays of objects of type item. The below lines will collects data for 100 objects. for(int i=0;i<100;i++) x[i].getdata(); Similarly, The below lines will display data for 100 objects. for(int i=0;i<100;i++) x[i].putdata();

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

37

10. Explain constructor and destructor with suitable example ☺ Constructor A constructor is a special function whose task is to initialize the objects of its class. It is special because its name is the same as the class. Class stack Class stack { Int top; Public: stack(); ~ stack(); push(); pop(); disp(); ---}; Example: Constructor stack ::stack() { top=0; } Special characteristics of constructors: • They should be declared in public section. • They are invoked automatically when the objects are created. • They do not have return types. So they cannot return values. • They cannot be inherited. • Like other C++ functions, they can have default arguments. • Constructors cannot be virtual. • We cannot refer to their addresses. Types of Constructors 1. Parameterized constructors The constructors that can take arguments are called parameterized constructors.

//constructor //destructor

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

38

class integer { int m,n; public: integer(int x, int y) //parameterized constructor ….. } 2. Default constructors A constructor that accepts no parameter is called default constructor. the default constructor for a class A is: A::A(). 3. Multiple constructors More than one constructor with different arguments is called multiple constructors. class integer { int m,n; public: integer() {m=0; n=0;} // constructor1 integer(int x, int y) // constructor2 {m=a;n=b;} integer(integer &i) // constructor3 {m=i.m;n=i.n;} ….. } 4. Default arguments constructors A constructor with default argument is called default argument constructor. class complex { float real, imag; public: complex(float real, float imag=0); ….
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 39

} complex c(5.0) real variable gets 5.0 and imag variable get 0 (by default) 5. Dynamic initialization of objects the class objects can be initialized dynamically too. that is, the initial value of an object may be provided during run time. stack ::stack() { top=0; } 6. Copy constructor A constructor can accept a reference to its own class as a parameter. that is, Class A { …. public: A(A &); } A copy constructor is used to declare and initialize an object from another object. 7. Dynamic constructors Allocation of memory to objects at the time of their construction is known as dynamic construction for objects. The memory is allocated with the help of the new operator. Destructor

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

40

A Destructor is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is same as the class name but it is preceded by tilde. Example: Destructor ~stack() { delete st; cout<<”Object deleted”; }

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

41

11. Compare and contrast between constructor and destructor? ☺ Constructor and destructor Constructor

Destructor

Similarities Constructors does not have a return Destructor also does not have a type return type Constructor is a member function to Destructor is also a member a class function to a class Constructor uses class name as their names Destructor also uses class name as their with ~ .

Differences Provided to a class to initialize an Cleans up or de-initializes each object object before object is destroyed It has same name as its class Constructors can have arguments Multiple constructors can exists Constructors can be overloaded It has same name as its class with prefixed ~ (tilde) Destructor has no arguments Multiple destructors can not exists Destructors can not be overloaded

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

42

12. What is function overloading? ☺ Many functions with same name created to perform different tasks. Family of functions with one function name but with different argument lists. Depending on the arguments correct function will be invoked. This process is known as function overloading. This is also known as function polymorphism (compile time polymorphism). #include<iostream.h> class sample { public: int add(int, int); //prototype1 float add(float,float); //prototype2 add(int, float); //prototype3 }; int sample :: add (int x, int y) { return (x+y);} float sample :: add (float x, float y) { return (x+y);} float sample :: add (int x, float y) { return (x+y);} main() { sample s; //function call cout<<s.add(10, 7.5); //uses prtotype3 cout<<s.add(2.5, 7.5); //uses prtotype2 cout<<s.add(10,20); //uses prtotype1 }

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

43

13. Explain Operator overloading with an example ☺ C++ permits us to add two variables of user-defined types with the same syntax that is applied to the basic types. this means that C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such a special meanings to an operator is known as operator overloading. Operator overloading can be done with the help of a special function is called operator function. The general form of operator function is given below:
returntype classname :: operator op (arg-list) { Function body //task defined }

Where returntype is the type of value retuned by the specified operation and op is the operator being overloaded. the op is proceeded by he keyword operator. Operator op is the function name. Operator function must be either member functions (non static) or friend function. List of operators that cannot be overloaded are: Direct member access operator De-reference pointer to class member operator Scope resolution operator Conational operator Size of operator

. .* :: ?: Sizeof

List of friend function cannot be used are: Assignment operator = Function call operator () Subscripting operator [] Class member access operator -> . Operator functions are declared as follows: vector operator + (vector); // vector addition vector operator - (); // unary minus friend vector operator + (vector, vector); // vector addition friend vector operator - (vector); // unary minus
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 44

int operator == (vector) friend int operator == (vector, vector)

//comparison //comparison

Rules for overloading operators: Although it looks simple to redefine the operators, there are some restrictions and limitations in operator overloading. Some of them are listed below: 1. Only existing operators can be overloaded. New operators cannot be created. 2. The overloaded operator must have at least one operand that is of user defined type. 3. We cannot change the basic meaning of the operator. 4. Overloaded operators must follow the rules of the original operators. 5. There are some operators that cannot be overloaded. 6. We cannot use friend functions to overload certain operators. 7. Unary operators are overloaded by means of a member function with out argument. 8. Binary operators are overloaded through a member function with one argument and a fiend function with two arguments. 9. The left-hand operand must be an object for binary operator overloading. 10. Binary arithmetic operators such as + - * and / must return a value. Example1: Program for unary operator overloading The unary operator – is overloaded with single operand. The unary operator – is used to change the negative value of the operand. Overloading unary operators #include<iostream.h> class point { int x; int y; public: void getdata(int a , int b); void display(void); void operator - (); //// unary minus
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 45

}; void point :: getdata(int a, int b) { x=a; y=b; } void point :: display(void) { cout<<”Point (x,y) = ”<<x<<”,”<< y; } void point :: operator – () { x = - x; y = - y; } main() { point p; p.getdata(10, -20); p.display(); -p; p.display(); } Output: Point (x,y) = 10, -20 Point (x,y) = -10, 20 Example2: Program for Binary operator overloading The binary operator + and * are overloaded with two operands. The binary operator + is overloaded for complex numbers addition and the binary operator * is overloaded for complex numbers multiplication. Overloading binay operators for complex numbers #include<iostream.h> class complex { float x; float y;

//real part //imaginay part
46

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

public: complex(){ } //constructor1 complex(float real, float imag) //constructor2 { x=real; y=imag; } complex operator+(complex); complex operator*(complex); void display(void); }; complex complex :: operator+(complex c) { complex temp; //temprary temp.x=x+c.x; //real part addition temp.y=y+c.y; //imaginary part addition return temp; } complex complex :: operator*(complex c) { complex temp; //temprary temp.x=(x*c.x)-(y*c.y); //real part multiplication temp.y=(x*c.y)+(y*c.x); //imaginary part multiplication return temp; } void complex :: display(void) { cout<<x<<" +i " <<y<<"\n" ; } main() { complex c1,c2,c3,c4,c5; //invoke costructor 1 c1 = complex(2.5, 3.5); //invoke costructor 2 c2 = complex(1.6, 2.7); //invoke costructor 2 c3=c1+c2; //invoke operator+()
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 47

c4=c1*c2; //invoke operator*() cout<<"C1= " ; c1.display(); cout<<"C2= " ; c2.display(); cout<<"Addition: C3= " ; c3.display(); cout<<"Multiplication: C4= " ; c4.display(); } Output C1 = 2.5 +i 3.5 C2 = 1.6 +i 2.7 Addition: C3= 4.1 +i 6.2 Multiplication: C4=-5.45+i 12.35

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

48

14. Explain type conversion with example ® Converting data from one type to another type is called type conversion. Three types of data type conversions are A. Conversion from built-in type to class type. B. Conversion from class type to built-in type. C. Conversion from one class type to another class type. Conversion required Basic Class Class Basic Class Class Conversion takes place in Source class Destination class -> Not Constructor applicable -> Casting Not operator applicable -> Casting Constructor operator

A. Basic to Class Type The conversion from basic type to class type is easy to accomplish. We can use constructor to build a string type object from a char* type variable. This is an example for defacto type conversion. Class String constructor: string :: string(char *a) { length = strlen(a); P = new char[length + 1]; strcpy(P,a); } The string constructor builds a string type object from char* type variable a. The variables length and p are data members of the class string. This constructor is used for conversation from basic data type char * to string type.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

49

Example: string s1,s2; char * name1 = “Dr Pauls”; char * name2 = “Engineering College”; s1=string(name1); //calls constructor s2=name2; //implicitly calls constructor

The last statements are used to converts data from char * type to string type. B. Class to Basic Type C++ allows us to define a overload a casting operator that could be used to convert a class type to a basic type. The general form of an overloaded casting operator function, usually referred to as a conversion function, is: operator typename() { ……… ………(Function staetments ) } Example: Converstion from class type string to basic type char * as follows: string : : operator char*() { return(p); } string s3=”Dr Pauls Engineering College” char * name3=char* (s3); or char * name3=s3; C. One Class to Another Class We have seen data conversion technique from a basic to class type and a class to basic type. But there are situations where we would like to convert one class type data to another class type. Example:
objX = objY; //objects of different types

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

50

Where objX is an object of class X and objY is an object of class Y. The class Y type data is converted to the class X type data and the converted value is assigned to the objX. Since the conversion takes place from class Y to class X, Class Y is Known as source Class and Class X is known as the destination Class. Such conversions between objects of different classes can be carried out by either a constructor or a conversion function. //polar to cartesian.cpp #include<iostream.h> #include<math.h> #include<conio.h> class polar { public: float r; float a; polar(float i=0, float j=0) //constructor { r=i; a=j; } }; class cartesian { public: float x; float y; cartesian(float m=0, float n=0) //constructor { x=m; y=n; } cartesian(polar p) //type conversion { x=p.r*cos(p.a); y=p.r*sin(p.a); } void show() { cout<<"("<<x<<" , "<< y <<")\n"; } };
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 51

void main() { polar ppoint(4.25,0.785); //angle PI/4=0.785 cartesian cpoint; cpoint=ppoint; //Polar object is assigned cpoint.show(); getch(); } Output ( 3.0005, 3.0004 )

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

52

15. Explain inheritance / Extending Classes ☺ The mechanism of deriving a new class from existing class is called inheritance. The existing class is known as base class, super class or parent class; the new class is known as sub class, derived class or child class. Defining derived classes A derived class is defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is: class derived_clas_name : visibility_mode base_class_name { ……//members of derived classes } Types of Inheritance There are different kinds of inheritance namely single, multiple, multilevel inheritance, Hierarchical and Hybrid Single Inheritance means a class derived from only one of existing class. (A derived class with only one base class is called Single Inheritance)
Parent

Child

Class Child : public Parent { . . .}; Multilevel Inheritance means a class derived from only one of existing class.
Parent

Derived1

Derived2

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

53

Class Derived1 : public Parent { . . .}; Class Derived2 : public Derived1 { . . .}; Multiplelevel Inheritance means a class derived from more than one of existing classes.
Parent1 Parent2

Derived1

Class Derived1 : public Parent1, public Parent2 { . . .}; Hierarchical Inheritance means a class my be inherited by more than one classes.
Parent1

Derived1

Derived2

Derived3

Class Derived1 : public Parent1 { . . .}; Class Derived2 : public Parent1 { . . .}; Class Derived3 : public Parent1 { . . .}; Hybrid Inheritance means combinations of the above inheritance.
GrandParent1

Parent1

Parent2

Derived3

Class Parent1 : public GrandParent1 { . . .}; Class Parent2 : public GrandParent1
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 54

{ . . .}; Class Derived3 : public Parent1, public Parent12 { . . .}; Multi path inheritance / Virtual base classes
Grand Parent

Derived1

Derived2

Child

The child has two direct base classes parent1 and parent2 which themselves have a common base class Grandparent. The child inherits the traits of Grandparent via two separate paths. It can also inherit directly as shown by a broken line. The Grandparent is sometimes referred to as indirect base class. Inheritance by the child as shown in the above figure might pose some problems. All the public and protected members of Grandparent are inherited into child twice, first via parent1 and again via parent2. This means child would have duplicate sets of the members inherited from grandparent. This introduces ambiguity and should be avoided. The duplication of inherited members due to this multiple paths can be avoided by making the common base class (ancestor class ) as virtual base class while declaring the direct or intermediate base classes as shown below: Class A // Grandparent {……}; Class B1: virtual public A //parent1 {……}; Class B2: public virtual A //parent2 {……}; Class C: public B1, public B2 //child { ……//only one copy of a will be inherited };

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

55

Access mode in inheritance With in With class derived class Private Yes No Protected Public Yes Yes Yes Yes

Main / other class No No Yes

Private and public inheritance Data public protected derived derived class class Private not not accessible accessible Protected protected protected Public public protected

Private derived class not accessible Private Private

Sample program for hybrid inheritance

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

56

16. Explain pointers in C++ Pointers Pointers data type is one of the strengths of the C++ language. A pointer is a variable which holds the memory address of another variable. The advantages of pointers • Pointer allows passing variables, arrays, functions, strings and structures as function arguments. • Pointer facilitates functions to modify calling arguments • Pointer supports dynamic allocation and de allocation of memory segments. • It allows to establish links between data elements such as linked lists, stacks, queues, trees and graphs. Initialization and declaration of pointers int *ip; //integer pointer declaration ip = & x; //address of x assigned to ip *ip =50 //50 assigned to x through indirection Constant pointer char * const ptr1 = “GOOD”; // constant pointer we cannot modify the address of ptr1 Pointer to a constant int const * ptr =&m; // Pointer to a constant ptr2 can point to any variable, but the contents of what it points to cannot be changed.

Pointers to objects #include<iostream.h> Class Base { public: void display() { cout<< “\n display base”;} virtual void show() { cout<< “\n show base”;} };

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

57

main() { Base B; Base *ptr; //declarations cout<< “\n Ptr points to base\n”; ptr=&B; ptr->display() //calls Base version ptr->show() //calls Base version }

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

58

17. Explain virtual function Same function name in both the base and derived classes, the function in the base class is declared as virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather then the type of the pointer. Thus by making the base pointer to point to different objects, we can execute different versions of virtual function It is used for late binding. That is, for run time polymorphism. Example #include<iostream.h> Class Base { public: void display() { cout<< “\n display base”;} virtual void show() { cout<< “\n show base”;} }; Class Derived { public: void display() { cout<< “\n display derived”;} void show() { cout<< “”\n show derived; }; main() { Base B; Derived D; Base *ptr; //declarations cout<< “\n Ptr points to base\n”; ptr=&B; ptr->display() //calls Base version ptr->show() //calls Base version cout<< “\n Ptr points to derived\n”; ptr=&D; ptr->display() //calls Base version ptr->show() //calls Derived version }

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

59

Output Ptr points to base display base show base Ptr points to derived display base show derived Ptr is always point to base object. but run time polymorphism is achieved by adding a key word ‘virtual’ to show() function in base class.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

60

18. Explain virtual functions with a program (16) Run time polymorphism is achieved by the concept of virtual functions. Run time polymorphism refers to the property by which Objects belonging to different classes are able to respond to the same function in different forms. An essential requirement of polymorphism is the ability to refer to objects without any regard to their class. This necessitates the use of a single pointer variable to refer to the objects of different classes. Here we use the pointer to base class to refer to all the derived objects. But we just discovered that a base pointer, even when it is made to contain the address of a derived class, always executes the function in the base class. The compiler simply ignores the contents of the pointer and chooses the member function that matches the type of the pointer. How do we then achieve polymorphism? It is achieved using what is known as virtual function. Same function name in both the base and derived classes, the function in the base class is declared as virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather then the type of the pointer. Thus by making the base pointer to point to different objects, we can execute different versions of virtual function It is used for late binding. That is, for run time polymorphism. run time polymorphism is achieved only when a virtual function is accessed through a pointer to the base class. Example: Consider a book shop which sells both books and video-tapes. We can create a class known as media that stores the title and price of a publication. We can then create two derived classes, one for storing the number of pages in a book and another for storing the playing time of a tape. The following figure shows class hierarchy for the book shop
media
virtual void display()

book

tape

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

61

//run time polymorphism-virtual functions #include<iostream.h> #include<string.h> class media { protected: char title[50]; float price; public: media(char *s, float a) { strcpy(title,s); price=a; } virtual void display() { } //empty virtual function }; class book : public media { int pages; public: book (char * s, float a, int p) :media(s,a) { pages = p; } void display() { cout << "\n Title: " << title; cout << "\n Pages: " << pages; cout << "\n Price: " << price; } }; class tape : public media { float time; public: tape (char * s, float a, float t) :media(s,a) { time = t; } void display() { cout << "\n Title: " << title; cout << "\n Play time:" << time ; cout << "\n Price: " << price; } };
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 62

main() { char *title; float price, time; int pages; cout << "\n Enter Book Details\n"; cout << "\n Title: " ;cin >> title; cout << "\n Pages: " ;cin >> pages ; cout << "\n Price: " ;cin >> price; book b1(title, price,pages); cout << "\n Enter Tape Details\n"; cout << "\n Title : "; cin >> title; cout << "\n Play time: "; cin >> time ; cout << "\n Price : "; cin >> price; tape t1(title, price,time); media* m1; media *m2; m1=&b1; m2=&t1; cout <<"\n\nMEDIA DETAILS"; cout <<"\n...........BOOK.........."; m1 -> display(); //display book cout <<"\n...........TAPE.........."; m2 -> display(); //display tape }

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

63

19. Explain polymorphism The ability to take more than one form is called polymorphism. That is, more operations in same name. Polymorphism means one name with multiple forms. The concept of polymorphism is implemented using the overloaded functions and operators. Polymorphism can be divided into Run time polymorphism and compile time polymorphism.
Polymorphism

Compile time Polymorphism

Run time Polymorphism

Function overloading

Operator overloading

Virtual functions

Compile time polymorphism The overloaded member functions are ‘selected’ for invoking by matching arguments by number of arguments and its type. This information is known to the compiler at the compile time and, therefore, compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism. Early binding simply means that an object is bound to its function at compile time. Run time polymorphism Consider the base and derived class with same function name and prototype in both classes. class A { int x; public: void show() {…} //show() in base class }; class B : public A { int y; public:

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

64

void show() {…} //show() in derived class }; Here the same show() function is available in both classes. That is, function overloading is not possible. Therefore static binding fails. In fact, the compiler does not know which function to chose. The process of selecting the appropriate member function at run time is called run time poly morphism. It can be achieved using virtual functions. It is also called as late binding or dynamic binding Thus, Run time polymorphism refers to the property by which Objects belonging to different classes are able to respond to the same function in different forms. Dynamic binding is the one of the powerful features of C++. This requires the use of pointers to objects. NOTE: for 16 mark write function overloading, operator overloading and virtual functions.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

65

20. Explain file handling Introduction External memory
Data Files read data (from files)

write data (to files)

Internal memory
Program + Data

Prog-file interaction

get data (from key board) cin>>

Screen

put data to screen cout<<

Console Program interaction

Keyboard

File input and output streams The I/O system of C++ handles file operations which are very much similar to the console input and out put operations. It uses file stream (sequence of bits or bytes) as an interface between the programs and the files. The stream that supplies data to the program is known as input stream and the one that receives data from the program is known as output stream.

Read Data

Data Input Disk files Program Data Output

Write Data

Stream classes for file operations

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

66

ios

iostream.h file ostream

istream

streambuf iostream

ifstream

fstream fstream base

ofstream

filebuf

fstream.h file

Details of stream classes Class Contents filebuf fstreambase ifstream ofstream fstream Its purpose is to set the file buffers to read and write. Provides operations common to the file streams. Provides input operations Provides output operations Provides support for simultaneous input and output operations

//writing and reading objects in a file #include<fstream.h> #include<iomanip.h> class inventory { char name[10]; int code; float cost; public: void readdata (void); void writedata(void); };
OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC. 67

void inventory :: readdata (void) { cout<<"Enter name: "; cin>>name; cout<<"Enter code: "; cin>>code; cout<<"Enter cost: "; cin>>cost; } void inventory :: writedata (void) { cout<<setiosflags(ios::left) << setw(10) <<name; cout<<setiosflags(ios::right)<< setw(10) <<code; cout<<setprecision(2) << setw(10) <<cost; cout<<endl; } main() { inventory item[3]; //array of 5 objects fstream myfile; //input and output file myfile.open("stock.txt", ios::in | ios::out); cout<<"\nEnter details for inventory\n"; for (int i=0; i<3; i++) { item[i].readdata(); myfile.write((char *) & item[i], sizeof(item[i])); } myfile.seekg(0); //reset to start position cout<<"\n File Output\n\n"; for(i=0;i<3;i++) { myfile.read((char *) & item[i], sizeof(item[i])); item[i].writedata(); } myfile.close(); }

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

68

File mode parameters No. Mode: parameters 1 ios :: in 2 ios :: out 3 ios :: app 4 ios :: ate 5 ios :: binary 6 ios :: nocreate 7 8 ios :: noreplace ios :: trunc Meanings Open file for reading only Open file for writing only Append to end-of-file Go to end-of-file on opening Open as binary file Open fails if the file does not exists Open fails if the file already exists Delete the contents of the file if it exists

ERROR HANDLING DURING FILE OPERATIONS We may get Errors when one of the following occurs: • A file which we are attempting to open for reading does not exist. • The file name used for a new file may already exist. • We may attempt an invalid operation such as reading after end-of –file. • There may not be any space in the disk for storing more data. • We may use an invalid file name. • We may attempt to perform an operation when file is not opened for that purpose. ERROR HANDLING FUNCTIONS Function Return value and meanings eof() Returns true (non-zero value) if end-of –file is encountered while reading; otherwise returns false (zero). fail() Returns true when input or output failed. bad() Returns true when invalid operation or unrecoverable error has occurred. if it is false, then it may be possible to recover from error Returns true if no error has occurred

good()

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

69

21. Explain class and function templates Single function or class for which a family of similar functions or class in a generic manner is called templates. Class template A single generic class for set of multi class with similar objective is called class template Example Template <class T> T sum (T *arr, int n) { T temp=0; for( int i=0;i<n;i++) temp = temp + arr[i]); return temp; } main() { float a[10]; int b[10]; cout<<sum(A,10); cout<<sum(B,10); } A generic function for multipurpose is called function template

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

70

6. Explain Exception handling. Exceptions are run time anomalies or unusual events like divide by zero, out of range, index overflowing, running out of memory or disk space error etc.
Normal code yes

code that cause exception no

exception handler

Normal code

C++ supports exception handling mechanism to detect and manage runtime errors.
Exceptions

Synchronous Exceptions

Asynchronous Exceptions

Exceptions are classified into two major types. They are: 1. Synchronous Error such as out of range, index overflowing, running out of memory or disk space are called as synchronous type of exceptions. 2. Asynchronous Events that are passed beyond the control of program such as keyboard interrupts are called as Asynchronous. Note: C+ supports Synchronous exceptions only. There are two basic blocks to handle exceptions. They are 1. Try -> to throw the exception 2. Catch -> to catch exception

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

71

Syntax for Try block try { ……. throw(exception) } Syntax for catch block catch(argument type) { ……. } Steps involved in handling exceptions are: 1. Fix the problem 2. Inform that Error is occurred 3. Receive error information 4. Take corrective action Purpose of exception handling is to detect and report exception circumstances, so that appropriate action can be taken. The mechanism used in C++ to handle exception is throwing and catching exceptions.

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

72

22. Explain String manipulation in detail STRINGS: A string is a sequence of characters. C++ does not support string data type. But C++ provides a library header file for string manipulation is called string.h. Using string.h we can easily perform string operations like copy, finding string length, finding substring, etc. The string class is a very large and includes many constructors, member functions and operators. We may use these constructors, member functions and operators to achive the following. • Creating String objects • Reading String objects • Displaying String objects to the screen • Finding a sub-string from a String • modifying String objects • Comparing String objects • Adding String objects • Accessing character in a string • Obtaining the size of the string Constructors String() String(const char *str)

//create empty string //creating a String objects from a nullterminated string String(const string &str) //creating a String objects from a nullterminated string Functions append() at() compare() begin() end() erase() find() insert() length() substr() Operators +, =, +=, ==, 1=, <, <=, >, >= Examples String s1 (“Dr Pauls”); String s2; s2=s1; s2=s1+”Engineering College”

OBJECT ORIENTED PROGRAMMING IN C++, DEPT. OF CSE, DRPEC.

73

Biography

Mr. G. Appasami was born in Pondicherry, India in 1980. He received his Master of Science degree in Mathematics, Master of Computer Applications degree and Master of Technology degree in Computer Science and Engineering from Pondicherry University, Pondicherry, India. He received his Master of Philosophy in Computer Science from Alagappa University, Karaikudi, India. Currently he is faculty in Dr. Pauls Engineering College, Villupuram and affiliated to Anna University Chennai, Tamil Nadu, India. He is a life member of Indian Society for Technical Education, Computer Society of India, International Association of Computer Science and Information Technology (Singapore) and International Association of Engineers. He also qualified Gate Exam. His Area of interests includes Network Security, image processing and web technology. He has published more papers in national & international journals and conference proceedings. Email: appas_5g@yahoo.com Website: www.appas.110mb.com

Sign up to vote on this title
UsefulNot useful