object oriented programming in c++ 10cs36 · object oriented programming in c++ 10cs36 unit -1:...

74
Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and object oriented programming. (06 marks) Procedure oriented programming divides the code into functions Data is not secure. It can be manipulated by any procedure. Compilers also do not prevent unauthorized functions from accessing/ manipulating structure variable. The code design is centered around procedures. OOPs ensure security of data. Interfaces perfectly manipulate the internal parts of the objects, with exclusive rights. Functions logically related to data can only access the data, others can be prevented from accessing the data members of the variables of this structure. This is achieved with the help of Data encapsulation in classes. Compile time errors against pieces of code are thrown which access unauthorized data. Data can be grouped either as private or public data. 1b. Why should default values be given to function arguments in function prototyping and not in function definition? Write a program to add three numbers using function which has one or more default arguments. (09 marks) C++ allows a function to assign a parameter a default value when no argument corresponding to that parameter is specified in a call to that function. The default value is specified in a manner syntactically similar to a variable initialization. For example, this declares myfunc() as taking one double argument with a default value of 0.0: void myfunc(double d = 0.0) { // ... } Now, myfunc() can be called one of two ways, as the following examples show: myfunc(198.234); // pass an explicit value myfunc(); // let function use default When you are creating functions that have default arguments, it is important to remember that the default values must be specified only once, and this must be the first time the function is declared within the file. If you try to specify new (or even the same) default values in function definition, Dept of CSE, SJBIT 2

Upload: truongnhan

Post on 13-May-2018

226 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming in C++ 10CS36

UNIT -1: Introduction to C++

JUNE-JULY 2009

1a. Differentiate between procedure oriented and object oriented programming.(06 marks)

Procedure oriented programming divides the code into functions Data is not secure. It can be manipulated by any procedure. Compilers also do not prevent unauthorized functions from accessing/

manipulating structure variable. The code design is centered around procedures. OOPs ensure security of data. Interfaces perfectly manipulate the internal parts of the objects, with exclusive

rights. Functions logically related to data can only access the data, others can be

prevented from accessing the data members of the variables of this structure. This is achieved with the help of Data encapsulation in classes. Compile time errors against pieces of code are thrown which access unauthorized

data. Data can be grouped either as private or public data.

1b. Why should default values be given to function arguments in functionprototyping and not in function definition? Write a program to add three numbersusing function which has one or more default arguments. (09 marks)

C++ allows a function to assign a parameter a default value when no argumentcorresponding to that parameter is specified in a call to that function. The default value isspecified in a manner syntactically similar to a variable initialization. For example, thisdeclares myfunc() as taking one double argument with a default value of 0.0:void myfunc(double d =0.0){// ...}Now, myfunc() can be called one of two ways, as the following examplesshow:myfunc(198.234); // pass an explicitvalue myfunc(); // let function usedefault

When you are creating functions that have default arguments, it is important to rememberthat the default values must be specified only once, and this must be the first time thefunction is declared within the file. If you try to specify new (or even the same) defaultvalues in function definition,

Dept of CSE, SJBIT 2

Page 2: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming in C++ 10CS36

Dept of CSE, SJBIT 3

the compiler will display an error and not compile your program. Even though defaultarguments for the same function cannot be redefined, you can specify different defaultarguments for each version of an overloaded function

#include <iostream>class example{int x, y, z;public:example(int i=0, int j=0, int k=0) {x=i;y=j;z=k;}Example(int i=10,int j=20){y=I;z=j;}Example(int i=1){z=I;}

int add() {return x+y+z;}};int main(){example a(2,3,4), b(2),c(2,3);cout << a.add() << endl;cout << b.add();cout<< c.add();return 0;

}1c. What is data abstraction. How it is implemented in C++. Explain with an example

(05 marks)Data abstraction refers to, providing only essential features byhiding its background details.example:class result{int marks;float percentage;char name[20]; voidinput();void output();}

Page 3: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming in C++ 10CS36

Dept of CSE, SJBIT 4

main(){bank b1;b1.input();b1.output();}

in the above example, b1 is an object calling input and output memberfunctions, but that code is invisible to the object b1.

Page 4: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming in C++ 10CS36

Dept of CSE, SJBIT 5

MAY/JUNE 2010

1a Explain the various features of object oriented programming (10 marks)Essential features of object oriented programming

Encapsulation Inheritance Polymorphism

Encapsulation in OOP-terminology means that an object has something like a shellaround it protecting the attributes or status variables from being accessed from outs ide ofthe object. The belong to the object and to nobody else. Only the methods of the objecthave access to them, can read and modify their values. The methods, providing theservices of the object, are the interface to the outside world.

Inheritance means that a derived class inherits all attributes and methods from its superclass, the class from which it is derived. This feature alleviates programmers from havingto start always from scratch when writing an object-oriented applications. Many times itwill be possible to design and implement a class that can be derived from existing ones insome sort of class library, which one has either written oneself or that can be obtainedfrom another source.

Polymorphism in OOP-Terminology means that a certain message may be implementedby different objects in different ways. A good example is the `display'-message sent to anumber, a string of characters or a list. It is always the message 'display yourself!'. Theobject must know itself what has to be done and how, nobody cares as long as the objectappears on the screen.

1b. Discuss function prototyping, with an example. Also write its advantage (05marks)In C++ all functions must be declared before they are used. This is normallyaccomplished using a function prototype. The use of parameter names is optional.However, they enable the compiler to identify any type mismatches by name when anerror occurs, so it is a good idea to include them. It produces anThe function prototypingtells the number of arguments,type of arguments and type of the return type to thecompiler.The function prototyping is a declaration statement in the calling program.

General Format:

returnType methodName(Argument List);

*Where Argument List specify the type and name of the arguments.

Page 5: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 6

Object Oriented Programming with C++

/* This program uses a function prototype to enforce strong type checking. */void sqr_it(int *i); /* prototype */

int main(void) {

int x;x = 10; sqr_it(x); /* type mismatch */return 0; }void sqr_it(int *i) {

*i = *i * *i; }

It produces an error message because it contains an attempt to call sqr_it() with aninteger argument instead of the integer pointer required. (It is illegal to convert an integerinto a pointer.)Function prototypes help you trap bugs before they occur. In addition, theyhelp verify that your program is working correctly by not allowing functions to be calledwith mismatched arguments. If the function is defined before the function call , then itacts as function prototype.

1c. Define the ‘this’ pointer, with an example, indicate the steps involved in referringto members of the invoking object. (05 marks)

When a member function is called, it is automatically passed an implicit argument that isa pointer to the invoking object (that is, the object on which the function is called) . Thispointer is called this.#include <iostream> using namespace std;class pwr { double b;int e; double val;public: pwr(double base, int exp);double get_pwr() { return val; } };pwr::pwr(double base, int exp){this->b = base; this->e = exp;// this pointer points to the object calling the functionthis->val = 1; if(exp==0) return;for( ; exp>0; exp--) this->val = this->val * this->b;}int main() {pwr x(4.0, 2), y(2.5, 1), z(5.7, 0);cout << x.get_pwr() << " "; cout << y.get_pwr() << " "; cout << z.get_pwr() << "\n";return 0; }

Dec 2008 -2009

1a) Discuss the issues of procedure oriented systems with respect to object orientedsystems? (8 marks)

Page 6: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 7

Object Oriented Programming with C++

Procedure Oriented Programming1.Prime focus is on functions and procedures that operate on data2.Large programs are divided into smaller program units called functions3.Data and the functions that act upon it are treated as separate entities.4.Data move freely around the systems from one function to another.5.Program design follows “Top Down Approach”.--------------------------------------…Object Oriented Programming1.Here more emphasis is laid on the data that is being operated and not the functions orprocedures2.Programs are divided into what are called objects.3.Both data and functions are treated together as an integral entity.4.Data is hidden and cannot be accessed by external functions.5.Program design follows “Bottom UP Approach”.

b) Why c++ introduced reference variable ? (8 marks )

Declaring a variable as a reference rather than a normal variable simply entails appendingan ampersand to the type name, such as this "reference to an int"int& foo = ....;When a reference is created, you must tell it which variable it will become an alias for.After you create the reference, whenever you use the variable, you can just treat it asthough it were a regular integer variable. But when you create it, you must initialize itwith another variable, whose address it will keep around behind the scenes to allow youto use it to modify that variable.

In a way, this is similar to having a pointer that always points to the same thing. One keydifference is that references do not require dereferencing in the same way that pointersdo; you just treat them as normal variables. A second difference is that when you create areference to a variable, you need not do anything special to get the memory address. Thecompiler figures this out for you:Here's a simple example of setting up a function to take an argument "by reference",implementing the swap function:void swap (int& first, int& second){

int temp = first;first = second;second = temp;

}references should always be valid because you must always initialize a reference. Thismeans that barring some bizarre circumstances (see below), you can be certain that usinga reference is just like using a plain old non-reference variable. You don't need to checkto make sure that a reference isn't pointing to NULL, and you won't get bitten by anuninitialized reference that you forgot to allocate memory for.c)explain inline functions?(4)

Page 7: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 8

Object Oriented Programming with C++

The inline directive can be included before a function declaration to specify that thefunctionmust be compiled as code at the same point where it is called. This is equivalentto declaring a macro. Its advantage is only appreciated in very short functions, in whichthe resulting code from compiling the program may be faster if the overhead of calling afunction (stacking of arguments) is avoided.The format for its declaration is:inline type name ( arguments ... ) { instructions ... }and the call is just like the call to any other function. It is not necessary to include theinline keyword before each call, only in the declaration

JUNE/JULY 2011

1 a Give the comparision of C and C++ with examples (6 marks)

1. C follows the procedural programming paradigm while C++ is a multi-paradigmlanguage(procedural as well as object oriented)

In case of C, importance is given to the steps or procedure of the program while C++focuses on the data rather than the process.Also, it is easier to implement/edit the code in case of C++ for the same reason.

2. In case of C, the data is not secured while the data is secured(hidden) in C++

This difference is due to specific OOP features like Data Hiding which are not present in C.

3. C is a low-level language while C++ is a middle-level language (Relatively, Please seethe discussion at the end of the post)

C is regarded as a low-level language(difficult interpretation & less user friendly) whileC++ has features of both low-level(concentration on whats going on in the machinehardware) & high-level languages(concentration on the program itself) & hence is regardedas a middle-level language.

4. C uses the top-down approach while C++ uses the bottom-up approach

In case of C, the program is formulated step by step, each step is processed into detail whilein C++, the base elements are first formulated which then are linked together to give rise tolarger systems.

5. C is function-driven while C++ is object-driven

Functions are the building blocks of a C program while objects are building blocks of aC++ program.

6. C++ supports function overloading while C does not

Overloading means two functions having the same name in the same program. This can bedone only in C++ with the help of Polymorphism(an OOP feature)

Page 8: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 9

Object Oriented Programming with C++

7. We can use functions inside structures in C++ but not in C.

In case of C++, functions can be used inside a structure while structures cannot containfunctions in C.

b. What is function overloading give example ( 6 marks)

It is a classification of static polymorphism in which a function call is resolved using the'best match technique ', i.e., the function is resolved depending upon the argument list.Method overloading is usually associated with statically-typed programming languageswhich enforce type checking in function calls. When overloading a method, you are reallyjust making a number of different methods that happen to have the same name. It isresolved at compile time which of these methods are used.

Method overloading should not be confused with forms of polymorphism where the correctmethod is chosen at runtime, e.g. through virtual functions, instead of statically.

Example: function overloading in c++main(){

cout<<volume(10);cout<<volume(2.5,8);cout<<volume(100,75,15);

}

// volume of a cubeint volume(int s){

return(s*s*s);}

// volume of a cylinderdouble volume(double r,int h){

return(3.14*r*r*h);}

// volume of a cuboidlong volume(long l,int b,int h){

return(l*b*h);}

c. Define a class design Flower and display the names of the flowers.( 8 marks)

Page 9: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 10

Object Oriented Programming with C++

#include <iostream>using namespace std;

class Flower {int x;

public:void set_values (string);int display() {return x;}

};

void Flower::set_values (int a) {x = a;

}

int main () {Flower f;f.set_values (“ROSE”);f.set_values (“JASMINE”);cout << "flowers name: " << f.diaplay() << endl;cout << "flowers name: " << f.diaplay() << endl;return 0;

}

JUN/JUL 12

1 a Describe the following characteristics of OOPi Encapsulation

Encapsulation is the word which came from the word "CAPSULE" which to put something in a kind of shell. In OOP we are capsuling our code not in a shell but in "Objects" &"Classes". So it means to hide the information into objects and classes is calledEncapsulation.

class cat

{

public void eat()

{

console.writeline("cat eats mouse");

}

Page 10: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 11

Object Oriented Programming with C++

public void walk()

{

console.writeline("It walks slowly...");

}

}

Here we have defined a class and in 'class cat' " public void eat() " and " public void walk()" are methods.now we make an object in main class and call these methods...

static void main ()

{

cat mycat = new cat();

mycat.eat();

mycat.walk();

console.readline();

}

ii Polymorphism

Polymorphism is the ability to use an operator or method in different ways. Polymorphismgives different meanings or functions to the operators or methods. Poly, referring to many,signifies the many uses of these operators and methods. A single method usage or anoperator functioning in many ways can be called polymorphism. Polymorphism refers tocodes, operations or objects that behave differently in different contexts.

Below is a simple example of the above concept of polymorphism:

6 + 10

The above refers to integer addition.

The same + operator can be used with different meanings with strings:

"Exforsys" + "Training"

The same + operator can also be used for floating point addition:

7.15 + 3.78

Page 11: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 12

Object Oriented Programming with C++

iii Inheritance

The Inheritance is one of the main concepts of oop.Inheritance is just to adobe thefunctionality (methods & properties) of one class to another. This simple term is known asInheritance.

Lets have a look of codepublic class cat{

public void eat(){

console.writeline("cat can eat");}public void walk(){console.writeline("cat can walk");}

}

now we make another class of another cat and we inherit the methods of the first class tothe new class.Do remember in programming we inherit one class to another by coding " : "colon between the parent and child class.

Lets have a look..

public class EgyptianCat : cat{public void jump(){

console.writeline("Egyptian cat can jump");}

public void bite(){console.writeline("Egyptian cat can not bite");}

}

static void main()

{

cat mycat=new cat();

mycat.eat();

Page 12: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 13

Object Oriented Programming with C++

mycat.walk();

EgyptianCat yourcat=new EgyptianCat();

yourcat.eat();

yourcat.walk();

yourcat.jump();

yourcat.bite();

console.readline();

}

this is the code in main class in which we are inheriting the class EgyptianCat to the classcat, so that the new class becomes the child class of the first class which is now called theparent class.

b Write the general form of function. Explain the different types of argument passingtechniques with example

A function is a group of statements that is executed when it is called from some point of theprogram. 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 specifierfollowed by an identifier, like any regular variable declaration (for example: int x)and which acts within the function as a regular local variable. They allow to passarguments to the function when it is called. The different parameters are separatedby commas.

statements is the function's body. It is a block of statements surrounded by braces {}.

Here you have the first function example:

1 // function example2 #include <iostream>3 using namespace std;

The result is 8

Page 13: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 14

Object Oriented Programming with C++

45 int addition (int a, int b)6 {7 int r;8 r=a+b;9 return (r);10 }1112 int main ()13 {1415161718 }

int z;z = addition (5,3);cout << "The result is " << z;return 0;

In order to examine this code, first of all remember something said at the beginning of thistutorial: a C++ program always begins its execution by the main function. So we will beginthere.

We can see how the main function begins by declaring the variable z of type int. Right afterthat, we see a call to a function called addition. Paying attention we will be able to see thesimilarity between the structure of the call to the function and the declaration of thefunction itself some code lines above:

The parameters and arguments have a clear correspondence. Within the main function wecalled to addition passing two values: 5 and 3, that correspond to the int a and int bparameters declared for function addition.

At the point at which the function is called from within main, the control is lost by mainand passed to function addition. The value of both arguments passed in the call (5 and 3)are copied to the local variables int a and int b within the function.

Function addition declares another local variable (int r), and by means of the expressionr=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and bare 5 and 3 respectively, the result is 8.

The following line of code:

return (r);

Page 14: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 15

Object Oriented Programming with C++

finalizes function addition, and returns the control back to the function that called it in thefirst place (in this case, main). At this moment the program follows its regular course fromthe same point at which it was interrupted by the call to addition. But additionally, becausethe return statement in function addition specified a value: the content of variable r (return(r);), which at that moment had a value of 8. This value becomes the value of evaluating thefunction call.

So being the value returned by a function the value given to the function call itself when itis evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. Toexplain it another way, you can imagine that the call to a function (addition (5,3)) isliterally replaced by the value it returns (8).

The following line of code in main is:

cout << "The result is " << z;

That, as you may already expect, produces the printing of the result on the screen.

c What are pointers explain with an example.

A pointer is a variable which stores the address of another variable. There are twoimportant operators when working with pointers in C++: the address of (&) operator andthe value of (*) operator. They have been overloaded in C++ so they may have differentuses in different contexts.

How much storage space does a pointer consume? Use sizeof(ptr) without the '*' operatorto determine the memory utilised on your system. Irrespective of datatype or whether thepointer points to a single variable or array, as a general rule, pointers must use the sameamount of memory space.

Page 15: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 16

Object Oriented Programming with C++

The & operator gives us the address of a variable and * gives us the value of a variable at aspecified address. For example,

Page 16: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 17

Object Oriented Programming with C++

UNIT-II Classes& Objects

2a. What is nested classes. What is its use. Give an example and explain (08marks)

A nested class is declared within the scope of another class. The name of a nested class islocal to its enclosing class. Unless you use explicit pointers, references, or object names,declarations in a nested class can only use visible constructs, including type names, staticmembers, and enumerators from the enclosing class and global variables.

Member functions of a nested class follow regular access rules and have no special accessprivileges to members of their enclosing classes. Member functions of the enclosing classhave no special access to members of a nested class.

The following example demonstratesthis:

class A {int x;

class B { };

class C {

// The compiler cannot allow the following// declaration because A::B is private:// B b;

int y;void f(A* p, int i) {

// The compiler cannot allow the following// statement because A::x is private:// p->x = i;

}};

void g(C* p) {

// The compiler cannot allow the following// statement because C::y is private:// int z = p->y;

}

Page 17: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Dept of CSE, SJBIT 18

Object Oriented Programming with C++

main() { }

The compiler would not allow the declaration of object b because class A::B is private.The compiler would not allow the statement p->x = i because A::x is private. Thecompiler would not allow the statement int z = p->y because C::y is private.

2b. What are the points to remember about friend function. Write program tomultiply two matrices using friend function devise a class Matrix with a constructormethod to read and display. (12 marks)

A friend function is used for accessing the non-public members of a class. A class canallow non-member functions and other classes to access its own private data, by makingthem friends. Thus, a friend function is an ordinary function or a member of anotherclass.

Some important points to note while using friend functions in C++:

The keyword friend is placed only in the function declaration of the friendfunction and not in the function definition.

It is possible to declare a function as friend in any number of classes.

When a class is declared as a friend, the friend class has access to the private dataof the class that made this a friend.

A friend function, even though it is not a member function, would have the rightsto access the private members of the class.

It is possible to declare the friend function as either private or public.

The function can be invoked without the use of an object. The friend functionhas its argument as objects, seen in example below.

MAY/JUNE 2010

2a What are friend non-member functions and friend member functions. Explainwith suitable example (08 marks)

A friend function has access to all private and protected members of the class for which itis a friend.Friend non-member functions is a function which can be used for multiple class.Iit ispossible to check the status of each object by calling only this one function.Thus, in

Page 18: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 33

situations like this, a friend function allows you to generate more efficient code. Thefollowing program illustrates this concept#include <iostream> using namespace std; const intIDLE = 0; const int INUSE = 1; class C2; // forwarddeclarationclass C1 { int status; // IDLE if off, INUSE if on screen// ... public:};void set_status(int state); friend int idle(C1 a, C2 b); class C2 { int status; //IDLE if off, INUSE if on screen public: void set_status(int state);friend int idle(C1 a, C2 b); }; voidC1::set_status(int state) { status = state; }void C2::set_status(int state) {status = state; }int idle(C1 a, C2 b) {}if(a.status || b.status) return 0; else return 1;int main() { C1x; C2 y;x.set_status(IDLE); y.set_status(IDLE);if(idle(x, y)) cout << "Screen can be used.\n"; else cout << "In use.\n";x.set_status(INUSE);if(idle(x, y)) cout << "Screen can be used.\n"; else cout << "In use.\n";return 0; }

Friend member function: A friend of one class may be a member of another.#include <iostream> using namespace std;const int IDLE = 0; const int INUSE = 1;class C2; // forward declarationclass C1 { int status; // IDLE if off, INUSE if on screen // ... public: voidset_status(int state);int idle(C2 b); // now a member of C1 };class C2 { int status; // IDLE if off, INUSE if on screen// ... public:};void set_status(int state); friend int C1::idle(C2 b);void C1::set_status(int state) {status = state; }void C2::set_status(int state) {status = state; }/ idle() is member of C1, but friend of C2 int C1::idle(C2 b) {}if(status || b.status) return 0; else return 1;int main() {C1 x; C2 y;x.set_status(IDLE); y.set_status(IDLE);if(x.idle(y)) cout << "Screen can be used.\n"; else cout << "In use.\n";

Page 19: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 34

x.set_status(INUSE);if(x.idle(y)) cout << "Screen can be used.\n"; else cout << "In use.\n";

return 0; }2b. Write a C++ program to count the number of objects of a certain class (06marks)

#include <iostream> using namespace std;static int count;Counter() { count++; }

~Counter() { count--; }};int Counter::count;void f();int main(void) {Counter o1; cout << "Objects in existence: ";cout << Counter::count << "\n";Counter o2; cout << "Objects in existence: "; cout << Counter::count <<"\n"f(); cout << "Objects in existence: ";cout << Counter::count << "\n";return 0; }void f() {

Counter temp; cout << "Objects in existence:";cout << Counter::count << "\n"; // temp is destroyed when f() returns}

2c. Write a note on namespaces. (06 marks)

Namespaces allow to group entities like classes, objects and functions under a name. Thisway the global scope can be divided in "sub-scopes", each one with its own name.The format of namespaces is:

namespace identifier { entities }

Where identifier is any valid identifier and entities is the set of classes, objects andfunctions that are included within the namespace. For example:

namespace myNamespace { int a, b; }

In this case, the variables a and b are normal variables declared within a namespacecalled myNamespace. In order to access these variables from outside the myNamespacenamespace we have to use the scope operator ::. For example, to access the previousvariables from outside myNamespace we can write:

Page 20: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 35

myNamespace::a myNamespace::bThe functionality of namespaces is especially useful in the case that there is a possibilitythat a global object or function uses the same identifier as another one, causingredefinition errors. For example:// namespaces#include <iostream>using namespace std;namespace first { int var = 5; }namespace second { double var = 3.1416; }

JUNE/JULY 11

2a Explain member function overloading with examples (6 marks)A member function named f in a class A will hide all other members named f in the baseclasses of A, regardless of return types or arguments. The following example demonstratesthis:struct A {void f() { }

};

struct B : A {void f(int) { }

};

int main() {B obj_B;obj_B.f(3);

// obj_B.f();}The compiler would not allow the function call obj_B.f() because the declaration of voidB::f(int) has hidden A::f().

To overload, rather than hide, a function of a base class A in a derived class B, youintroduce the name of the function into the scope of B with a using declaration. Thefollowing example is the same as the previous example except for the using declarationusing A::f:struct A {void f() { }

};

struct B : A {

Page 21: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 36

using A::f;void f(int) { }

};

int main() {B obj_B;obj_B.f(3);obj_B.f();

}Because of the using declaration in class B, the name f is overloaded with two functions.The compiler will now allow the function call obj_B.f().

You can overload virtual functions in the same way. The following example demonstratesthis:#include <iostream>using namespace std;

struct A {virtual void f() { cout << "void A::f()" << endl; }virtual void f(int) { cout << "void A::f(int)" << endl; }

};

struct B : A {using A::f;void f(int) { cout << "void B::f(int)" << endl; }

};

int main() {B obj_B;B* pb = &obj_B;pb->f(3);pb->f();

}The following is the output of the above example:void B::f(int)void A::f()Suppose that you introduce a function f from a base class A a derived class B with a usingdeclaration, and there exists a function named B::f that has the same parameter types asA::f. Function B::f will hide, rather than conflict with, function A::f. The following exampledemonstrates this:#include <iostream>using namespace std;

struct A {

Page 22: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 37

void f() { }void f(int) { cout << "void A::f(int)" << endl; }

};

struct B : A {using A::f;void f(int) { cout << "void B::f(int)" << endl; }

};

int main() {B obj_B;obj_B.f(3);

}The following is the output of the above example:void B::f(int)

b How can yo make member functions inline . Give examples (6 marks)

Inline functions are functions where the call is made to inline functions. The actual codethen gets placed in the calling program.The general format of inline function is as follows:

inline datatype function_name(arguments)

The keyword inline specified in the above example, designates the function as inlinefunction. For example, if a programmer wishes to have a function named exforsys withreturn value as integer and with no arguments as inline it is written as follows:

inline int exforsys( )Example:

The concept of inline functions:

Sample Code

#include <iostream>using namespace std;int exforsys(int);void main( ){

int x;cout << "n Enter the Input Value: ";cin>>x;cout << "n The Output is: " << exforsys(x);

}

Page 23: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 38

inline int exforsys(int x1){

return 5*x1;}

c Write a c++ program to sort numbers.(8 marks)

#include<iostream.h>#include<conio.h>

void main(){clrscr();int a[50],n,i,j,temp,small,pos;cout<<"How many elements of Array you want to create?";cin>>n;cout<<"Enter elements of Array ";for(i=0;i<n;++i)cin>>a[i];

for(i=0;i<n;++i){ small=a[i];for(j=i+1;j<n;++j){if(a[j]<small){small=a[j];pos=j;}} temp=a[i];a[i]=a[pos];a[pos]=temp;}cout<<"\nArray after sorting is ";for(i=0;i<n;++i)cout<<a[i]<<" ";getch();}

JUN/JUL 12

Page 24: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 39

2a What is a class? How is it created ? Write an example class ( 10 marks)

A class is a mechanism for creating user-defined data types. It is similar to the C languagestructure data type. In C, a structure is composed of a set of data members. In C++, a classtype is like a C structure, except that a class is composed of a set of data members and a setof operations that can be performed on the class.

In C++, a class type can be declared with the keywords union, struct, or class. A unionobject can hold any one of a set of named members. Structure and class objects hold acomplete set of members. Each class type represents a unique set of class membersincluding data members, member functions, and other type names. The default access formembers depends on the class key:

The members of a class declared with the keyword class are private by default. Aclass is inherited privately by default.

The members of a class declared with the keyword struct are public by default. Astructure is inherited publicly by default.

The members of a union (declared with the keyword union) are public by default. Aunion cannot be used as a base class in derivation.

Once you create a class type, you can declare one or more objects of that class type. Forexample:class X{

/* define class members here */};int main(){

X xobject1; // create an object of class type XX xobject2; // create another object of class type X

}You may have polymorphic classes in C++. Polymorphism is the ability to use a functionname that appears in different classes (related by inheritance), without knowing exactly theclass the function belongs to at compile time.

C++ allows you to redefine standard operators and functions through the concept ofoverloading. Operator overloading facilitates data abstraction by allowing you to useclasses as easily as built-in types.

b What are constructors? How are they different from member functions?

A constructor is similar to a function, but with the following differences.

Page 25: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 40

No return type.

No return statement.Example [extracts from three different files].//=== point/point.h =================================================#ifndef POINT_H#define POINT_Hclass Point {

public:Point(); // parameterless default constructorPoint(int new_x, int new_y); // constructor with parametersint getX();int getY();

private:int x;int y;

};#endifHere is part of the implementation file.//=== point/point.cpp ==============================================. . .Point::Point() { // default constructor

x = 0;y = 0;

}

Point::Point(int new_x, int new_y) { // constructorx = new_x;y = new_y;

}. . .And here is part of a file that uses the Point class.//=== point/main.cpp ==============================================

. . .Point p; // calls our default constructorPoint q(10,20); // calls constructor with parametersPoint* r = new Point(); // calls default constructorPoint s = p; // our default constructor not called.

c What is data hiding ? explain with an example

Data Hiding is also known as Encapsulation.

Page 26: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 41

Encapsulation is the process of combining data and function into a single unit calledclass.

Data Hiding is the mechanism where the details of the class are hidden from theuser.

The user can perform only a restricted set of operations in the hidden member of theclass.

Encapsulation is a powerful feature that leads to information hiding,abstract datatype and friend function.

They encapsulate all the essential properties of the object that are to be created. Using the method of encapsulation the programmer cannot directly access the class.

Access Specifier:There are three types of access specifier.They are

Private :Within the block. Public:Whole over the class. Protected:Act as a public and then act as a private.

Within a class members can be declared as either public protected or private in order toexplicitly enforce encapsulation.The elements placed after the public keyword is accessible to all the user of the class.The elements placed after the protected keyword is accessible only to the methods of theclass.The elements placed after the private keyword are accessible only to the methods of theclass.The data is hidden inside the class by declaring it as private inside the class. Thus privatedata cannot be directly accessed by the object.

For example,In order to make the design and maintenance of a car reasonable the complex of equipmentis divided into modules with particular interfaces hiding design decisions.

General Form:class class name{ private:datatype data;public:Member functions;};

main()

Page 27: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 42

{classname objectname1,objectname2……………;}

Example:class Square{ private:int Num;

public:void Get() {

cout<<"Enter Number:";cin>>Num;

}void Display() {

cout<<"Square Is:"<<Num*Num;}};

void main(){Square Obj;Obj.Get();Obj.Display();getch()

3a. What is dynamic memory management. Write a c++ program demonstrating theusage of new and delete operators for a single variable as well as for an array (10marks)

C++ provides two dynamic allocation operators: new and delete. These operators areused to allocate and free memory at run time. Dynamic allocation is an important part ofalmost all real-world programs.Operators new and new[]In order to request dynamic memory we use the operator new. new is followed by a datatype specifier and -if a sequence of more than one element is required- the number ofthese within brackets []. It returns a pointer to the beginning of the new block of memoryallocated. Its form is:pointer = new type pointer = new type [number_of_elements]

Page 28: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 43

The first expression is used to allocate memory to contain one single element of typetype. The second one is used to assign a block (an array) of elements of type type, wherenumber_of_elements is an integer value representing the amount of these.

Operators delete and delete[]Since the necessity of dynamic memory is usually limited to specific moments within aprogram, once it is no longer needed it should be freed so that the memory becomesavailable again for other requests of dynamic memory. This is the purpose of the operatordelete, whose format is:delete pointer; delete [] pointer;The first expression should be used to delete memory allocated for a single element, andthe second one for memory allocated for arrays of elements.

#include <iostream> #include <new>using namespace std;int main() { int*p,*q, i; try {q=new int(100);p = new int [10]; // allocate 10 integer array} catch (bad_alloc xa) { cout << "Allocation Failure\n";return 1; }for(i=0; i<10; i++ ) p[i] = i;for(i=0; i<10; i++) cout << p[i] << " ";cout<< *q;delete [] p; // release the array deleteq;return 0; }

Dec/Jan 2008- 2009

2 a)Compare struct and classes in c ++?(2)particular functionality. But C++ extended the structure to contain functions also. Themajor difference is that all declarations inside a structure are by default public.Class: Class is a successor of Structure. By default all the members inside the class areprivate.

b)explain the need of friend function in c++? (6)

#include <iostream>using namespace std;class myclass {int a, b;public:friend int sum(myclass x);void set_ab(int i, int j);};

Page 29: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 44

void myclass::set_ab(int i, int j){a = i;b = j;}int sum(myclass x){return x.a + x.b;}int main(){myclass n;n.set_ab(3, 4);cout << sum(n);return 0;

c) explain the namespace and namespace pollution in c++(4)Namespaces allow to group entities like classes, objects and functions under a name. Thisway the global scope can be divided in "sub-scopes", each one with its own name.

The format of namespaces is:

namespace identifier{entities}

Where identifier is any valid identifier and entities is the set of classes, objects andfunctions that are included within the namespace. For example:

namespace myNamespace{int a, b;}

namespace pollution :naming collision is a circumstance where two or more identifiers in a given namespace ora given scope cannot be unambiguously resolved, and such unambiguous resolution is arequirement of the underlying system.d)explain with an example , keywords namespaces and "using" ?(8)

The functionality of namespaces is especially useful in the case that there is a possibilitythat a global object or function uses the same identifier as another one, causingredefinition errors.The keyword usingis used to introduce a name from a namespace into the current

Page 30: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 45

declarative region. For example:using #include <iostream>using namespace std;namespace first{ int x = 5; int y = 10; }namespace second{ double x = 3.1416; double y = 2.7183; }int main (){using first::x;using second::y;cout << x << endl; cout << y << endl;cout << first::y << endl; cout << second::x << endl; return 0;}

Page 31: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 46

UNIT-3

Classes & Objects II

JUNE/JULY 09

3a. What are constructors. When are they called. What is their use. Define a suitableparameterized constructor with default values for the class TIME with data memberhr, min,sec. (07marks)

Constructors and destructors are special member functions of classes that are used toconstruct and destroy class objects. Construction may involve memory allocation andinitialization for objects.

The following restrictions apply to constructors anddestructors:

Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors

because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual. Constructors and destructors cannot be declared static, const, or volatile. Unions cannot contain class objects that have constructors or destructors.

The compiler automatically calls constructors when defining class objects and callsdestructors when class objects go out of scope. A constructor does not allocate memoryfor the class object its thispointer refers to, but may allocate storage for more objects thanits class object refers to. If memory allocation is required for objects, constructors canexplicitly call the newoperator.

ClassTIME

{

Private: inthr,min,sec;

Public: TIME(){hr=0;min=0;sec=0;}

TIME(int a, int b, int c) { hr=a; min=b;sec=c;}

Page 32: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 47

Void display() {cout<<hr<<”:”<<min<<”:”<<sec<<endl;

}

Intmain()

{

TIMEt,t1(10,20,30);

Page 33: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 48

t.display();

t1.display();

}

3b. What is the drawback of static memory allocation. How is it overcome.How is it achieved in c++. Explain with an example.(06 marks)

In Static memory allocation the size of all itmes to be determined in the source code,before the execution of the program. But, what if we need a variable amount of memorythat can only be determined during runtime? For example, in the case that we need someuser input to determine the necessary amount of memory space.

The answer is dynamic memory, for which C++ integrates the operators new anddelete. The dynamic memory requested by our program is allocated by the system fromthe memory heap

Operators new andnew[]In order to request dynamic memory we use the operator new. new is followed by adata type specifier and -if a sequence of more than one element is required- thenumber of these withinbrackets []. It returns a pointer to the beginning of the new block of memory allocated. Itsform is:pointer = new type pointer = new type[number_of_elements]The first expression is used to allocate memory to contain one single element of typetype. The second one is used to assign a block (an array) of elements oftype type, wherenumber_of_elements is an integer value representing the amount of these. Forexample:

int * bobby; bobby = new int[5];

Operators delete anddelete[]Since the necessity of dynamic memory is usually limited to specific moments within aprogram, once it is no longer needed it should be freed so that the memory becomesavailable again forother requests of dynamic memory. This is the purpose of the operator delete, whoseformat is:delete pointer; delete []pointer;

Page 34: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 49

The first expression should be used to delete memory allocated for a single element,and the second one for memory allocated for arrays of elements.

The value passed as argument to delete must be either a pointer to a memory blockpreviously allocated with new, or a null pointer (in the case of a null pointer, deleteproduces no effect).

3c. Write program to add and multiply two complex numbers. Initialize the variablesthrough constructors. Implement add and multiply using overloaded “+” and “*:”operators. (10marks)

classCOMPLEX{floatreal,imag;public:voidread(){cout<<"Enter real and imaginary part"<<"\n";

Page 35: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 50

cin>>real>>imag;}friend COMPLEX operator + (COMPLEX C1,COMPLEX C2){COMPLEX temp;temp.real=C1.real+C2.real;temp.imag=C1.imag+C2.imag; return temp;}Friend COMPLEX operator * (COMPLEX C1,COMPLEX C2){COMPLEX temp;temp.real=c1.real*C2.real;temp.imag=c1.imag*c2.imag; return temp;}void print(){if(imag<0)cout<<real<<"-i"<<(-imag)<<endl; elsecout<<real<<"+i"<<imag<<endl;}};

void main(){COMPLEX C1,C2,C3,C4;int rpt=1,ch,a;clrscr();while(rpt){cout<<"1.Addition of two complex numbers"<<"\n";cout<<"2.Multiplication of two complex number"<<"\n";cout<<"3.Exit"<<"\n";cout<<"Enter yourchoice"<<"\n"; cin>>ch;switch(ch){

case 1:C1.read();C2.read();C3=c1+c2;C3.print();break;

case 2:C1.read();

Page 36: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 51

c2.read();c3=c1*c2;C3.print();break;

case 3:exit(0);break;

}cout<<"Do you want to continue(1/0)"<<"\n";cin>>rpt;}getch();}

MAY/JUNE 2010

3b. What are constructors and destructors. Explain the different types ofconstructors in c++ with examples. (10 marks)

A constructor is a member function with the same name as its class. For example:

class X {public:X(); // constructor for class X

};

Constructors are used to create, and can initialize, objects of their class type.You cannot declare a constructor as virtual or static, nor can you declare a

constructor as const, volatile, or const volatile.You do not specify a return type for a constructor. A return statement in the bodyof a constructor cannot have a return value.Similarly, a function to which the destructorattribute has been applied is calledautomatically after calling exitor upon completion of main.

Types of constructors:

A default constructor is a constructor that either has no parameters, or if it hasparameters, all the parameters have default values.

If no user-defined constructor exists for a class A and one is needed, the compilerimplicitly declares a default parameterless constructor A::A(). This constructor is aninline public member of its class. The compiler will implicitly define A::A() when thecompiler uses this constructor to create an object of type A. The constructor will have noconstructor initializer and a null body.

Page 37: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 52

Parameterized Constructors :It is possible to pass arguments to constructor functions.Typically, these arguments help initialize an object when it is created. To create aparameterized constructor, simply add parameters to it the way you would to any other

Page 38: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 53

function. When you define the constructor's body, use the parameters to initialize theobject

A copy constructor for a class Ais a constructor whose first parameter is of type A&,const A&, volatile A&, or const volatile A&. Copy constructors are used to make acopy of one class object from another class object of the same class type. You cannot usea copy constructor with an argument of the same type as its class; you must use areference. You can provide copy constructors with additional parameters as long as theyall have default arguments. If a user-defined copy constructor does not exist for a classand one is needed, the compiler implicitly creates a copy constructor, with public access,for that class. A copy constructor is not created for a class if any of its members or baseclasses have an inaccessible copy constructor.

Jan 2008- 2009

3) a) explain the features of new and delete?(4)

C++ provides two dynamic allocation operators: new and delete. Theseoperators are used to allocate and free memory at run time. Dynamicallocation is an important partof almost all real-world programs.

C++ also supportsdynamic memory allocation functions, called malloc() andfree(). These are included for the sake of compatibility with C. However, forC++ code, you should use the new and delete operators because they haveseveral advantages.

The new operator allocates memory and returns a pointer to the start of it.Thedelete operator frees memory previously allocated using new. Thegeneral forms of new and delete are shown here:

p_var = new type;delete p_var;Here, p_var is a pointer variable that receives a pointer to memory that is large enough tohold an item of type type.

Since the heap is finite, it can become exhausted. If there is insufficientavailable memory to fill an allocation request, then new will fail and abad_alloc exception will be generated. This exception is defined in theheader <new>.

program should handle this exception and take appropriate action if a failureoccurs. Initializing Allocated Memory . we can initialize allocated memoryto some known value by putting an initializer after the type name in the newstatement.

b)explain with example , Setnewhandler() in c++?(10)

Function Sets new_p as the new handler function.

Page 39: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

Object Oriented Programming with C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 54

The new handler function is the function that is called by functions operator new oroperator new[] when they are not successful in an attempt to allocate memory.

The new handler function can make more storage available for a new attempt to allocatethe storage. If, and only if, the function succeeds in making more storage avaible, it mayreturn. Otherwise it shall either throw a bad_alloc exception (or a derived class) orterminate the program with cstdlib's abort or exit functions.include <iostream>#include <cstdlib>#include <new>using namespace std;

void no_memory () {cout << "Failed to allocate memory!\n";exit (1);

}

int main () {set_new_handler(no_memory);cout << "Attempting to allocate 1 GiB...";char* p = new char [1024*1024*1024];cout << "Ok\n";delete[] p;return 0;

}

c) what is the benefit of copy constructor? Explain the necessity of defining yourown copy constructor? (8)

The "default copy constructor" only exists if you do not provide one. It is"default" because the compiler automatically generates a copy constructor foryou if you don't. For the example above, the copy constructor is definedexactly as the compiler would have done it.

One of the more important forms of an overloaded constructor is the copyconstructor. Defining a copy constructor can help you prevent problems thatmight occur when one object is used to initialize another.

By default, when one object is used to initialize another, C++ performs abitwise copy. That is, an identical copy of the initializing object is created inthe target object.

Although this is perfectly adequate for many cases—and generally exactlywhat you want to happen—there are situations in which a bitwise copyshould not be used. One of the most common is when an object allocatesmemory when it is created.

Page 40: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 44

For example, assume a class called MyClass that allocates memory for eachobject when it is created, and an object A of that class. This means that A hasalready allocated its memory. Further, assume that A is used to initialize B, asshown here:

MyClass B= A;If a bitwise copy is performed, then B will be an exact copy of A. This meansthat B will be using the same piece of allocated memory that A is using,instead of allocating its own. .

For example, if MyClass includes a destructor that frees the memory, thenthe same piece of memory will be freed twice when A and B are destroyed!C++ allows you to create a copyconstructor, which the compiler uses whenone object initializes another.

When a copy constructor exists, the default, bitwise copy is bypassed. Themost common generalform of a copy constructor is

classname (const classname &o) {// body of constructor

}Here, o is a reference to the object on the right side of the initialization. It ispermissible for a copy constructor to have additional parameters as long asthey have default arguments defined for them.

C++ defines two distinct types of situations in which the value of one objectis given to another. The first is assignment. The second is initialization,which can occur any of three ways:

When one object explicitly initializes another, such as in adeclaration

JUNE/JULY 2012

3a What is a friend function? Why is it required? Explain with an example (10marks)

A friend function is a function that is not a member of a class but has access to the class'sprivate and protected members. Friend functions are not considered class members; theyare normal external functions that are given special access privileges. Friends are not in theclass's scope, and they are not called using the member-selection operators (. and –>) unlessthey are members of another class. A friend function is declared by the class that isgranting access. The friend declaration can be placed anywhere in the class declaration. Itis not affected by the access control keywords.

The following example shows a Point class and a friend function, ChangePrivate. Thefriend function has access to the private data member of the Point object it receives as aparameter.

Page 41: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 45

Example

// friend_functions.cpp// compile with: /EHsc#include <iostream>

using namespace std;class Point{

friend void ChangePrivate( Point & );public:

Point( void ) : m_i(0) {}void PrintPrivate( void ){cout << m_i << endl; }

private:int m_i;

};

void ChangePrivate ( Point &i ) { i.m_i++; }

int main(){

Point sPoint;sPoint.PrintPrivate();ChangePrivate(sPoint);sPoint.PrintPrivate();

}Output01

b What is the use of operator overloading ? Write a program to over load post andpre increment operators.(10 marks)

C++ incorporates the option to use standard operators to perform operations with classes inaddition to with fundamental types. For example:

1 int a, b, c;2 a = b + c;

Page 42: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 46

This is obviously valid code in C++, since the different variables of the addition are allfundamental types. Nevertheless, it is not so obvious that we could perform an operationsimilar to the following one:

1 struct {2 string product;3 float price;4 } a, b, c;5 a = b + c;

In fact, this will cause a compilation error, since we have not defined the behavior our classshould have with addition operations. However, thanks to the C++ feature to overloadoperators, we can design classes able to perform operations using standard operators. Hereis a list of all the operators that can be overloaded:

Overloadable operators+ - * / = < > += -= *= /= << >><<= >>= == != <= >= ++ -- % & ^ ! |~ &= ^= |= && || %= [] () , ->* -> newdelete new[] delete[]

To overload an operator in order to use it with classes we declare operator functions, whichare regular functions whose names are the operator keyword followed by the operator signthat we want to overload. The format is:

type operator sign (parameters) { /*...*/ }

Here you have an example that overloads the addition operator (+). We are going to createa class to store bidimensional vectors and then we are going to add two of them: a(3,1) andb(1,2). The addition of two bidimensional vectors is an operation as simple as adding thetwo x coordinates to obtain the resulting x coordinate and adding the two y coordinates toobtain the resulting y. In this case the result will be (3+1,1+2) = (4,3).

1 // vectors: overloading operators example2 #include <iostream>3 using namespace std;45 class CVector {6 public:7 int x,y;8 CVector () {};9 CVector (int,int);10 CVector operator + (CVector);11 };

Page 43: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 47

1213 CVector::CVector (int a, int b) {141516 }17

x = a;y = b;

18 CVector CVector::operator+ (CVector param) {1920212223 }24

CVector temp;temp.x = x + param.x;temp.y = y + param.y;return (temp);

25 int main () {26272829303132 }

CVector a (3,1);CVector b (1,2);CVector c;c = a + b;cout << c.x << "," << c.y;return 0;

Page 44: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 48

UNIT-4

Inheritance

4a. Explain different types of inheritance with block diagram and an example foreach (10 marks)

Types of inheritance:

Single Inheritance :One class inherit from another base class is called single inheritance

Multiple Inheritance: Number of classes inherit from one class is called Multipleinheritance.

Multi - level Inheritance: Inheritance is based on a Number of levels is called multi-levelinheritance.see diagram

Page 45: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 49

Hierarchical Inheritance: This type of inheritance helps us to create a baseless fornumber of classes and those numbers of classes can have further their branches ofnumber of class

Hybrid Inheritance:

In this type of inheritance, we can have mixture of number of inheritances but this cangenerate an error of using same name function from no of classes, which will bother thecompiler to how to use the functions. Therefore, it will generate errors in the program.This has known as ambiguity or duplicity.[

4b. What are the benefits of inheritance. Can a friendship be inherited. (04 marks)

Inheritance is a mechanism of reusing and extending existing classes without modifyingthem, thus producing hierarchical relationships between them.

Inheritance lets you include the names and definitions of another class's members as partof a new class. The class whose members you want to include in your new class iscalled a base class. Your new class is derived from the base class. The new classcontains a subobject of the type of the base class. The following example is the same asthe previous example except it uses the inheritance mechanism to give class B access tothe members of class A:

#include <iostream>using namespace std;

Page 46: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 50

class A {int data;

public:void f(int arg) { data = arg; }int g() { return data; }

};

class B : public A { };

int main(){ B obj;obj.f(20);cout << obj.g() << endl;

}

Friends of a base class are not inherited by any classes derived from that base class.The following example demonstrates this:

class A {friend class B;int a;

};

class B { };

class C : public B {void f(A* p) {

// p->a = 2;}

};

The compiler would not allow the statement p->a = 2because class Cis not a friend ofclass A, although Cinherits from a friend of A.

Class A is a base class of class B. The names and definitions of the members of class Aare included in the definition of class B; class B inherits the members of class A. Class Bis derived from class A. Class B contains a subobject of type A.

4c. What is the ambiguity that arises in multiple inheritance. How it can beovervcome. Explain with example. (06 marks)

In object-oriented programming languages with multiple inheritance and knowledgeorganization, the diamond problem is an ambiguity that arises when two classes B and Cinherit from A, and class D inherits from both B and C. If a method in D calls a methoddefined in A (and does not override the method), and B and C have overridden thatmethod differently, then from which class does it inherit: B, or C?

Page 47: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 51

MAY/JUNE 2010

4a. Discuss with examples, the implications of deriving a class from an existing classby the ‘public’ and ‘protected’ access specifiers. (08 marks)

If the base class is inherited as public, then the base class' protected members becomeprotected members of the derived class and are, therefore, accessible by the derived class.By using protected, you can create class members that are private to their class but thatcan still be inherited and accessed by a derived class. Here is an example#include <iostream> using namespace std;class base { protected: int i, j; // private to base, butaccessible by derivedpublic: void set(int a, int b) { i=a; j=b; }void show() { cout << i << " " << j << "\n"; } };class derived : public base { 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 derivedob.setk(); ob.showk();return 0; }In this example, because base is inherited by derived as public and because i and j aredeclared as protected, derived's function setk() may access them. If i and j hadbeen declared as private by base, then derived would not have access to them, and theprogram would not compile.

Protected Base-Class InheritanceIt is possible to inherit a base class as protected. When this is done, all public andprotected members of the base class become protected members of the derived class. Forexample,#include <iostream> using namespace std;class base { protected:int i, j; // private to base, but accessible by derived public:};void setij(int a, int b) { i=a; j=b; } void showij() { cout << i << " "<< j << "\n"; }// Inherit base as protected. class derived : protected base{int k; public:};// derived may access base's i and j and setij(). void setk() {setij(10, 12); k = i*j; }// may access showij() here void showall() { cout << k << " ";showij(); Intmain(){ derived ob;// ob.setij(2, 3); // illegal, setij() is //

Page 48: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 52

protected member of derivedob.setk(); // OK, public member of derived ob.showall(); // OK, public member ofderived// ob.showij(); // illegal, showij() is protected //member of derivedreturn 0; }As you can see by reading the comments, even though setij() and showij() are publicmembers of base, they become protected members of derived when it is inherited usingthe protected access specifier. This means that they will not be accessible inside main().

4c. Write a c++ program to initialize base class members through a derived classconstructor (06 marks)

#include <iostream> using namespace std;class base { protected:int i; public:};base(int x) { i=x; cout << "Constructing base\n"; } ~base() { cout << "Destructingbase\n"; }class derived: public base { int j;public: // derived uses x; y is passed along to base. derived(int x, int y): base(y)};{ j=x; cout << "Constructing derived\n"; }~derived() { cout << "Destructing derived\n"; } void show() { cout << i<< " " << j << "\n"; }int main() {derived ob(3, 4); ob.show(); //displays 4 3 return 0; }

Jan 2008- 2009

4a) What is diamond shaped –inheritance?explain with an example?(6)

This occurs when a class multiply inherits from two classes which each inherit from asingle base class. This leads to a diamond shaped inheritance pattern.class PoweredDevice

{};

class Scanner: public PoweredDevice{

};

class Printer: public PoweredDevice

Page 49: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 53

{};

class Copier: public Scanner, public Printer{

};

b) Explain the order of invocation of constructors and destructors?(14)

an object's constructor is called when the object comes into existence, and anobject's destructor is called when the object is destroyed. A local object'sconstructor function is executed when the object's declaration statement isencountered.

The destructor functions for local objects are executed in the reverse order ofthe constructor functions. Global objects have their constructor functionsexecute before main() begins execution.

Global constructors are executed in order of their declaration, within the same file.

class myclass {public: int who;myclass(int id);~myclass();} glob_ob1(1), glob_ob2(2);myclass::myclass(int id){cout << "Initializing " << id << "\n";who = id;}myclass::~myclass(){cout << "Destructing " << who << "\n";}int main(){myclass local_ob1(3);cout << "This will not be first line displayed.\n";myclass local_ob2(4);return 0;}It displays this output:Initializing 1Initializing 2Initializing 3This will not be first line displayed.Initializing 4

Page 50: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 54

Destructing 4Destructing 3Destructing 2Destructing 1

JUNE JULY 2012

4a What is inheritance? How to inherit a base class as protected? Explain it inmultiple base classes?( 6 marks)

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 tocreate and maintain an application. This also provides an opportunity to reuse the codefunctionality and fast implementation time.

When creating a class, instead of writing completely new data members and memberfunctions, the programmer can designate that the new class should inherit the members ofan existing class. This existing class is called the base class, and the new class is referred toas the derived class.

The idea of inheritance implements the is a relationship. For example, mammal IS-Aanimal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base & Derived Classes:

A class can be derived from more than one classes, which means it can inherit data andfunctions from multiple base classes. To define a derived class, we use a class derivationlist to specify the base class(es). A class derivation list names one or more base classes andhas the form:

class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private, and base-class is the name ofa previously defined class. If the access-specifier is not used, then it is private by default.

Consider a base class Shape and its derived class Rectangle as follows:

#include <iostream>

using namespace std;

// Base classclass Shape{

public:void setWidth(int w){

width = w;}void setHeight(int h)

Page 51: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 55

{height = h;

}protected:

int width;int height;

};

// Derived classclass Rectangle: public Shape{

public:int getArea(){

return (width * height);}

};

int main(void){

Rectangle Rect;

Rect.setWidth(5);Rect.setHeight(7);

// Print the area of the object.cout << "Total area: " << Rect.getArea() << endl;

return 0;}

b With an example explain ,multiple base class inheritance?( 6 marks)

Multiple inheritance (C++ only)

You can derive a class from any number of base classes. Deriving a class from more thanone direct base class is called multiple inheritance.

In the following example, classes A, B, and C are direct base classes for the derived classX:class A { /* ... */ };class B { /* ... */ };class C { /* ... */ };class X : public A, private B, public C { /* ... */ };

Page 52: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 56

The following inheritance graph describes the inheritance relationships of the aboveexample. An arrow points to the direct base class of the class at the tail of the arrow:

The order of derivation is relevant only to determine the order of default initialization byconstructors and cleanup by destructors.

A direct base class cannot appear in the base list of a derived class more than once:class B1 { /* ... */ }; // direct base classclass D : public B1, private B1 { /* ... */ }; // errorHowever, a derived class can inherit an indirect base class more than once, as shown in thefollowing example:

class L { /* ... */ }; // indirect base classclass B2 : public L { /* ... */ };class B3 : public L { /* ... */ };class D : public B2, public B3 { /* ... */ }; // validIn the above example, class D inherits the indirect base class L once through class B2 andonce through class B3. However, this may lead to ambiguities because two subobjects ofclass L exist, and both are accessible through class D. You can avoid this ambiguity byreferring to class L using a qualified class name. For example:B2::LorB3::L.

c Explain with an example base class access control? ( 8 marks)

A derived class can access all the non-private members of its base class. Thus base-classmembers that should not be accessible to the member functions of derived classes should bedeclared private in the base class.

Page 53: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 57

We can summarize the different access types according to who can access them in thefollowing 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.

Page 54: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 58

UNIT-5Inheritance II

JUNE/JULY 2009

5a. What are virtual functions. What is their use. Give an example. How compilersresolve a function call.(06 marks)

Virtual member functions are declared with the keyword virtual. They allow dynamicbinding of member functions. Because all virtual functions must be member functions,virtual member functions are simply called virtual functions.

If the definition of a virtual function is replaced by a pure specifier in the declaration ofthe function, the function is said to be declared pure. A class that has at least one purevirtual function is called an abstract class.

#include <iostream>using namespace std;

struct A {virtual void f() { cout << "Class A" << endl; }

};

struct B: A {void f() { cout << "Class B" << endl; }

};

void g(A& arg) {arg.f();

}

int main() { Bx;g(x);

}

The following is the output of the above example:

Class B

The virtualkeyword indicates to the compiler that it should choose the appropriatedefinition of f()not by the type of reference, but by the type of object that the reference refers to.

5b. Describe briefly with a figure, class hierarchy provided by c++ for streamhandling. (08 marks)

Page 55: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 59

5A. Define and give the syntax for the following (06 marks)a) Virtual functionb) Pure Virtual functionc) Abstract Base Class

A virtual function is a member function that is declared within a base class and redefinedby a derived class. To create a virtual function, precede the function's declaration in thebase class with the keyword virtual.Eg: class base { public:virtual void vfunc() { cout << "This is base's vfunc().\n";} };class derived1 : public base { public:void vfunc() { cout << "This is derived1's vfunc().\n";}

A pure virtual function is a virtual function that has no definition within the base class.To declare a pure virtual function, use this general form:

virtual type func-name(parameter-list)=0;When a virtual function is made pure, any derived class must provide its own definition.If the derived class fails to override the pure virtual function, a compile-time error willresult.

Abstract ClassesA class that contains at least one pure virtual function is said to be abstract. Because anabstract class contains one or more functions for which there is no definition (that is, apure virtual function), no objects of an abstract class may be created. Instead, an abstractclass constitutes an incomplete type that is used as a foundation for derived classes.

Page 56: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 60

MAY/JUNE 2010

5b. What is a virtual table. How does it help in implementing dynamicpolymorphism. Explain with an example. (08 marks)

A virtual table, or "vtable", is a mechanism used in Programming languages to supportdynamic polymorphism, i.e., run-time method binding.

Each function has an address in memory somewhere. Function names are just pretty waysof referring to a position in memory. When a program is linked (after the compiler isfinished compiling) all those names are replaced with hardcoded memory addresses

.For example in C++:

class Foobar{

public:

int i;Foobar() {i = -1;}virtual void FuncA() {i = 0;}void FuncB() {i = 10;}

};

class Foo: public Foobar{

public:

virtual void FuncA() {i = 1;}void FuncB() {i = 11;}

};

class Bar: public Foobar{

public:

virtual void FuncA() {i = 2;}void FuncB() {i = 12;}

Page 57: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 61

};

void FoobarFunc(Foobar* fb){

cout << fb->i << endl;fb->FuncA();cout << fb->i << endl;fb->FuncB();cout << fb->i << endl << endl;

}

void FooFunc(Foo* f){

cout << f->i << endl;f->FuncA();cout << f->i << endl;f->FuncB();cout << f->i << endl << endl;

}

int main(){

Foobar fb;Foo f;Bar b;Foo OtherFoo;

FoobarFunc(&fb);FoobarFunc(&f);FoobarFunc(&b);

FooFunc(&OtherFoo);

return 0;

}

In this excerpt, both Foo and Bar inherit from Foobar. FuncA is a virtual function whileFuncB is not. The integer i is being set to see the results of our actions.

Notice how in FoobarFunc, you are unable to tell beforehand what address to replace

Page 58: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 62

FuncA and FuncB with! In order to solve this, virtual tables are created.

Normally, functions are not stored with the data of the class at all. So in our very firstFoobar example with no inheritance, the class would only be 4 bytes long (excluding anycompiler magic). However, when you declare something virtual, you're actually declaringa pointer to a function so each virtual function you have will increase the class size by thesize of a pointer. The pointers will be populated by the constructors under the hood whichis one reason why you cannot have virtual constructors. If you have many virtualfunctions, you end up with many pointers, which are organized into a table... the v-table.Each class will have its own unique v-table.

Jan 2008- 2009

5a) what is the need of virtual function ? with an example , explain overriding ofmember function of base in derived class? (8)

The concept of virtual function is the same as a function, but it does not reallyexist although it appears in needed places in a program.

The object-oriented programming language C++ implements the concept ofvirtual function as a simple member function, like all member functions of theclass.

when a function is declared as virtual by a base class, it may be overridden by aderived class. However, the function does not have to be overridden.

When a derived class fails to override a virtual function, then when an object ofthat derived class accesses that function, the function defined by the base class isused.

#include <iostream>using namespace std;class base {public:virtual void vfunc() {cout << "This is base's vfunc().\n";}};class derived1 : public base {public:void vfunc() {cout << "This is derived1's vfunc().\n";}};class derived2 : public base {public:

Page 59: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 63

};Because derived2 does not override vfunc() , the function defined by base is used whenvfunc() is referenced relative to objects of type derived2. when a derived class fails tooverride a virtual function, the first redefinition found in reverse order of derivation isused.

b) what is the virtual destructor? (6)

Virtual destructor : By making the Base class Destructor virtual, both the destructorswill be called in order. The following is the corrected sample.

#include <iostream.h>class Base{

public:Base(){ cout<<"Constructor: Base"<<endl;}virtual ~Base(){ cout<<"Destructor : Base"<<endl;}

};class Derived: public Base{

//Doing a lot of jobs by extending the functionalitypublic:

Derived(){ cout<<"Constructor: Derived"<<endl;}~Derived(){ cout<<"Destructor : Derived"<<endl;}

};void main(){

Base *Var = new Derived();delete Var;

}

c) list the library classes that handle streams in c++(6)

The class hierarchy that you will most commonly be working with is derivedfrom basic_ios. This is a high-level I/O class that provides formatting, error-checking, and status information related to stream I/O.

basic_ios is used as a base for several derived classes, includingbasic_istream, basic_ostream, and basic_iostream. These classes are usedto create streams capable of input, output, and input/output, respectively.

Specifically, from basic_istream are derived the classes basic_ifstream andbasic_istring stream, from basic_ostream are derived basic_ofstream and basic_ostringstream, and from basic_iostream are derived basic_fstream and basic_stringstream.

Page 60: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 64

UNIT-6Virtual functions, Polymorphism

6a. Describe the use of following manipulators: (05 marks)

i) setw : setw(int w) Set the field width to w. Outputii) setfill: setfill(int ch) Set the fill character to ch.iii) setprecision: setprecision (int p) Set the number of digits of precision.iv) setiosflags: setiosflags() manipulator to directly set the various format flags

related to a stream.v) Resetiosflags : resetiosflags (fmtflags f ) Turn off the flags specified in f.

6b) What are the rules for overloading the operator (05 marks)

Rules for overloading the operators are:

Operators obey the precedence, grouping, and number of operands dictatedby their typical use with built-in types. Therefore, there is no way to express theconcept "add 2 and 3 to an object of type Point," expecting 2 to be added to the xcoordinate and 3 to be added to the y coordinate.

Unary operators declared as member functions take no arguments; if declared asglobal functions, they take one argument.

Binary operators declared as member functions take one argument; if declaredas global

functions, they take two arguments. If an operator can be used as either a unary or a binary operator (&, *, +, and -),

you can overload each use separately. Overloaded operators cannot have default arguments. All overloaded operators except assignment (operator=) are inherited by derivedclasses. The first argument for member-function overloaded operators is always of the

class type of the object for which the operator is invoked (the class in which theoperator is declared, or a class derived from that class). No conversions are suppliedfor the first argument.

The meaning of any of the operators can be changed completely.

6c) Define a class Date, use overloaded + operator to add two dates and displaythe result ante-date . Assume non leap year dates.(10 marks)

#include<iostream.h>#include<conio.h>#include<process.h>int mon[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};class date

Page 61: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 65

{int day,month,year;public:date(){}void input(){cout<<"Enter the date,month and year\n";cin>>day>>month>>year;}int isleap(int year){return((year%4==0 && year%100!=0)||(year%400==0));}int no_of_days(int year,int month){if(isleap(year) && month==2)return 29;elsereturn mon[month];}void swap(date &d1,date &d2){date temp;temp.year=d1.year;temp.month=d1.month; temp.day=d1.day;d1.year=d2.year;d1.month=d2.month;d1.day=d2.day;d2=temp;}long int operator -(date d2){if(d2.year>year)swap(*this,d2);if(d2.year==year && d2.month>month)swap(*this,d2);if(d2.year==year && d2.month==month && d2.day>day)swap(*this,d2);long int diff=0;while(year!=d2.year||month!=d2.month||day!=d2.day){ diff++;if(d2.day==no_of_days(d2.year,d2.month)){

Page 62: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 66

d2.day=1;

if(d2.month==12){ d2.year++;d2.month=1;} elsed2.month++;} elsed2.day++;}return diff;}

date operator +(long int n){while(n>0){n--;if(day==no_of_days(year,month)){day=1;if(month==12){ year++;month=1;}elsemonth++;}elseday++;}date d;d.year=year;d.month=month; d.day=day;return d;}friend ostream &operator<<(ostream &,date &);};

ostream &operator<<(ostream &s,date &d){s<<"the new date is"<<endl;

Page 63: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 67

s<<d.day<<"/"<<d.month<<"/"<<d.year;return s;}

void main(){int choice;date d1,d2;long int days,diff=0;clrscr();for(;;){cout<<"\n1.sub"<<endl<<"2.add"<<endl<<"3.exit\n";cout<<"Enter your choice \n";cin>>choice;switch(choice){case 1:d1.input();

d2.input();diff=d1-d2;cout<<"The difference between two dates="<<diff<<"days\n";break;

case 2:d1.input();cout<<"Enter the number of days\n";cin>>days;d1=d1+days; cout<<d1;break;

default:exit(0);}getch();}}

MAY/JUNE 2010

6a) explain error handling and manipulators in c++?(6)

bad()Returns true if a failure occurs in a reading or writing operation. For example in case wetry towrite to a file that is not open for writing or if the device where we try to write has nospace left.fail()Returns true in the same cases as bad() plus in case that a format error happens, as tryingtoread an integer number and an alphabetical character is received.

Page 64: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 68

eof()Returns true if a file opened for reading has reached the end.tellg() and tellp()These two member functions admit no parameters and return a value of type pos_typethat is an integer data type representing the current position of get stream pointer (in caseof tellg) or put stream pointer (in case of tellp).seekg() and seekp()This pair of functions serve respectively to change the position of stream pointers get andput.Both functions are overloaded with two different prototypes:seekg ( pos_type position );seekp ( pos_type position );good()It is the most generic: returns false in the same cases in which calling any of the previousfunctions would return true.In order to reset the state flags checked by the previousmember functions you can use member function clear(), with no parameters.

Jan 2008- 2009

6b)why friend function is required to overload binary operators?(8)

Given an object of that class called Ob, the following expression is valid:Ob + 100 // valid

Ob generates the call to the overloaded + function, and the addition is performed.100 + Ob // invalid

In this case, it is the integer that appears on the left. Since an integer is a built-intype, no operation between an integer and an object of Ob's type is defined.Therefore, the compiler will not compile this expression.

The solution to the preceding problem is to overload addition using a friend, not amember, function. When this is done, both arguments are explicitly passed to theoperator function. Therefore, to allow both object+integer and integer+object,simply overload the function twice. .

when we overload an operator by using two friend functions, the object mayappear on either the left or right side of the operator.

This program illustrates how friend functions are used to define an operation thatinvolves an object and built-in type:#include <iostream>using namespace std;class loc {int longitude, latitude;public:loc(){}loc(int lg, int lt) {

Page 65: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 69

longitude = lg;latitude = lt;}void show() {cout << longitude << " ";cout << latitude << "\n";}friend loc operator+(loc op1, int op2);friend loc operator+(int op1, loc op2);};c) what are the rules for overloading operators?(5)

we cannot define new operators, such as **. we cannot redefine the meaning of operators when applied to built-in data types. Overloaded operators must either be a nonstatic class member function or a global

function. A global function that needs access to private or protected class membersmust be declared as a friend of that class. A global function must take at least oneargument that is of class or enumerated type or that is a reference to a class orenumerated type

Operators obey the precedence, grouping, and number of operands dictated bytheir typical use with built-in types. Therefore, there is no way to express theconcept "add 2 and 3 to an object of type Point," expecting 2 to be added to the xcoordinate and 3 to be added to the y coordinate.

Unary operators declared as member functions take no arguments; if declared asglobal functions, they take one argument.

Binary operators declared as member functions take one argument; if declared asglobal functions, they take two arguments.

If an operator can be used as either a unary or a binary operator (&, *, +, and -),you can overload each use separately.

Overloaded operators cannot have default arguments. All overloaded operators except assignment (operator=) are inherited by derived

classes. The first argument for member-function overloaded operators is always of the

class type of the object for which the operator is invoked . No conversions aresupplied for the first argument.

Page 66: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 70

UNIT-7I/O System Basics, File I/0

JUNE/JULY 09

7c. With an example , explain how to overload pointer to member operator (4marks)

The –> pointer operator, also called the class member access operator, is considereda unary operator when overloading. Its general usage is shown here:object->element;Here, object is the object that activates the call. The operator–>() function must returna pointer to an object of the class that operator–>() operates upon. The element must besome memberaccessible within the object.The following program illustrates overloading the –> by showing the equivalencebetween ob.iand ob–>i when operator–>() returns the this pointer:#include <iostream> using namespace std;

operator–>() function must be a member of the class upon which it works.

7B . Define a function template giving its syntax. Write a c++ program to implementarray representation of a stack for integers, characters and floating point numbersusing class template. (12 marks)

A generic function defines a general set of operations that will be applied to various typesof data. The type of data that the function will operate upon is passed to it as aparameter. Through a generic function, a single general procedure can be applied to awide range of data.A generic function is created using the keyword template. The normal meaning ofthe word "template" accurately reflects its use in C++. It is used to create a template (orframework) that describes what a function will do, leaving it to the compiler to fill inthe details as needed. The general form of a template function definition is shown here:

template <class Ttype> ret-type func-name(parameter list) {// body of function }

Page 67: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 71

// This function demonstrates a generic stack. #include <iostream>using namespace std;const int SIZE = 10;// Create a generic stack class template <class StackType> class stack{StackType stck[SIZE]; // holds the stack int tos; // index of top-of-stackpublic: stack() { tos = 0; } // initialize stack voidpush(StackType ob); // push object on stack StackTypepop(); // pop object from stack };// Push an object. template <class StackType> voidstack<StackType>::push(StackTypeif(tos==SIZE) {cout << "Stack is full.\n"; return;} stck[tos] = ob;tos++;// Pop an object. template <class StackType> StackTypestack<StackType>::pop()if(tos==0) {cout << "Stack is empty.\n"; return 0; // return null on empty stack} tos--;return stck[tos];int main()// Demonstrate character stacks. stack<char> s1, s2; // create twocharacter stacks inti;s1.push('a'); s2.push('x');s1.push('b');s2.push('y'); s1.push('c');s2.push('z');for(i=0; i<3; i++) cout << "Pop s1: " << s1.pop() << "\n"; for(i=0;i<3; i++) cout << "Pop s2: " << s2.pop() << "\n";// demonstrate double stacks stack<double> ds1, ds2; // create two double stacksds1.push(1.1); ds2.push(2.2);ds1.push(3.3); ds2.push(4.4);ds1.push(5.5); ds2.push(6.6);for(i=0; i<3; i++) cout << "Pop ds1: " << ds1.pop() << "\n"; for(i=0;i<3; i++) cout << "Pop ds2: " << ds2.pop() << "\n";return 0; }

Jan 2008- 2009

7a) explain new and delete operators overloading in c++ with examples ?(10)

The new operator allocates memory and returns a pointer to the start of it.Thedelete operator frees memory previously allocated using new. Thegeneral forms of new and delete are shown here:

p_var = new type;delete p_var;Here, p_var is a pointer variable that receives a pointer to memory that is large enough tohold an item of type type.

Page 68: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 72

Since the heap is finite, it can become exhausted. If there is insufficientavailable memory to fill an allocation request, then new will fail and abad_alloc exception will be generated. This exception is defined in theheader <new>.

program should handle this exception and take appropriate action if a failureoccurs. Initializing Allocated Memory . we can initialize allocated memoryto some known value by putting an initializer after the type name in the newstatement.

The general form of new when an initialization is included:p_var = new var_type (initializer);the type of the initializer must be compatible with the type of data for which memory isbeing allocated. This program gives the allocated integer an initial value of 87:#include <iostream>#include <new>using namespace std;int main(){int *p;try {p = new int (87); // initialize to 87} catch (bad_alloc xa) {cout << "Allocation Failure\n";return 1;}cout << "At " << p << " ";cout << "is the value " << *p << "\n";delete p;return 0; }

b) demonstrate overloading of assignment operator in c+?(10)

The assignment operator works by giving the value of one variable to another variableof the same type or closely similar.:

The assignment operator has a signature like this:

class MyClass {public:

...MyClass & operator=(const MyClass &rhs);...

}

MyClass a, b;...b = a; // Same as b.operator=(a);

Notice that the = operator takes a const-reference to the right hand side of the assignment.

Page 69: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 73

The reason for this should be obvious, since we don't want to change that value; we onlywant to change what's on the left hand side.

Also, you will notice that a reference is returned by the assignment operator. This is toallow operator chaining. You typically see it with primitive types, like this:

int a, b, c, d, e;

a = b = c = d = e = 42;This is interpreted by the compiler as:a = (b = (c = (d = (e = 42))));

In other words, assignment is right-associative. The last assignment operation isevaluated first, and is propagated leftward through the series of assignments. Specifically:

e = 42 assigns 42 to e, then returns e as the result The value of e is then assigned to d, and then d is returned as the result The value of d is then assigned to c, and then c is returned as the result

Now, in order to support operator chaining, the assignment operator must return somevalue. The value that should be returned is a reference to the left-hand side of theassignment

UNIT-8Exception Handling, STL

Page 70: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 74

JUNE/JULY 098a. What are the new style cast operators. Explian the syntax of these operatorswith example (06marks)The first is the traditional-style cast inherited from C

Dynamic_castC++ defines five casting operators. The first is the traditional-style cast inherited fromC. The remaining four were added a few years ago. They aredynamic_cast, const_cast,reinterpret_cast, and static_cast. These operators give you additional control over howcastingtakes place.The general form of dynamic_cast is shown here:dynamic_cast<target-type>(expr)

const_castThe const_cast operator is used to explicitly override const and/or volatile in a cast.The target type must be the same as the source type except for the alteration of itsconstor volatile attributes. The most common use of const_cast is to remove const-ness. Thegeneralform of const_cast is shownhere. const_cast<type>(expr)Here, type specifies the target type of the cast, and expr is the expression being cast intothe new type

static_castThe static_cast operator performs a nonpolymorphic cast. It can be used for anystandard conversion. No run-time checks are performed. Its general form isstatic_cast<type>(expr)Here, type specifies the target type of the cast, and expr is the expression being cast intothe new type.The static_cast operator is essentially a substitute for the original cast operator. It simplyperforms a nonpolymorphic cast. For example, the following casts an int value into adouble.// Use static_cast. #include <iostream>using namespace std;int main() {int i;for(i=0; i<10; i++) cout << static_cast<double> (i) / 3 << " ";return 0; }

reinterpret_castThe reinterpret_cast operator converts one type into a fundamentally different type.For example, it can change a pointer into an integer and an integer into a pointer. It canalso be usedfor casting inherently incompatible pointer types. Its general form isreinterpret_cast<type> (expr)

Page 71: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 75

8b) What are class templates. How are they created. What is the need for classtemplates. Create a template for bubble sort functions.

A generic function is created using the keyword template. The normal meaning of theword "template" accurately reflects its use in C++. It is used to create a template (orframework) that describes what a function will do, leaving it to the compiler to fill in thedetails as needed. The general form of a template function definition is shown here:template <class Ttype> ret-type func-name(parameterlist) {// body of function}Here, Ttype is a placeholder name for a data type used by the function. This namemayused within the function definition. However, it is only a placeholder that thecompiler will automatically replace with an actual data type when it creates a specificversion of the function. Although the use of the keyword class to specify a generic typeatemplate declaration is traditional, you may also use the keyword typename.

The following example creates a generic function that swaps the values of the twovariables with which it is called. Because the general process of exchanging two valuesindependent of the type of the variables, it is a good candidate for being made into agenericfunction.

#include <iostream>using namespace std;template <class X> void bubble( X *items, // pointer to array to be sorted int count)// number of items in array {register int a, b; X t;for(a=1; a<count; a++) for(b=count-1; b>=a; b--)} }if(items[b-1] > items[b]) { // exchange elementst = items[b-1]; items[b-1] = items[b]; items[b] = t;int main(){int iarray[7] = {7, 5, 4, 3, 9, 8, 6}; double darray[5] = {4.3, 2.5, -0.9,100.2, 3.0};int i;cout << "Here is unsorted integer array: "for(i=0; i<7; i++)cout << iarray[i] << ' '; cout << endl;cout << "Here is unsorted double array: "; for(i=0; i<5; i++)cout << darray[i] << ' '; cout << endl;bubble(iarray, 7); bubble(darray, 5);cout << "Here is sorted integer array: "; for(i=0; i<7; i++)cout << iarray[i] << ' '; cout << endl;

Page 72: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 76

cout << "Here is sorted double array: "; for(i=0; i<5; i++)cout << darray[i] << ' '; cout << endl;return 0; }

8 Explain the C++ style solution for handling exceptions (08 marks)

Exception handling is a mechanism that separates code that detects and handlesexceptional circumstances from the rest of your program. Note that an exceptionalcircumstance is not necessarily an error.

When a function detects an exceptional situation, you represent this with an object. Thisobject is called an exception object. In order to deal with the exceptional situation youthrow the exception. This passes control, as well as the exception, to a designated blockof code in a direct or indirect caller of the function that threw the exception. This block ofcode is called a handler. In a handler, you specify the types of exceptions that it mayprocess. The C++ run time, together with the generated code, will pass control to the firstappropriate handler that is able to process the exception thrown. When this happens, anexception is caught. A handler may rethrow an exception so it can be caught by anotherhandler.

The exception handling mechanism is made up of the following elements:

try blocks catch blocks throw expressions Exception specifications (C++ only)

// A simple exception handling example. #include <iostream>using namespace std;int main() {cout << "Start\n";try { // start a try block cout << "Inside try block\n";throw 100; // throw an error cout << "This will not execute";} catch (int i) { // catch an error}cout << "Caught an exception -- value is: "; cout << i << "\n";cout << "End";return 0;}

Jan 2008- 2009

8a)explain try catch and throw exception handling in c++(8)?

- The code within the try block is executed normally. In case that an exception takesplace, his code must use the throw keyword and a parameter to throw an exception. Thetype of the parameter details the exception and can be of any valid type.

Page 73: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 77

int main () {char myarray[10];try{for (int n=0; n<=10; n++){if (n>9) throw "Out of range";myarray[n]='z';

}}catch (char * str){cout << "Exception: " << str << endl;

}return 0;}

- If an exception has taken place, that is to say, if it has executed a throw instructionwithin the try block, the catch block is executed receiving as parameter theexception passed by throw.

b)explain different types of type conversion?(4)

static_ cast:static_cast performs any casting that can be implicitly performed as well as the inversecast . Applied to pointers to classes, that is to say that it allows to cast a pointer of aderived class to its base class and it can also perform the inverse: cast a base class toits derivated class.class Base {};class Derived: public Base{}; Base * a = new Base;Derived * b = static_cast<Derived*>(a);static_cast, aside from manipulating pointers to classes, can also be used toperform conversions explicitly defined in classes, as well as to perform standardconversions between fundamental types:double d=3.14159265;int i = static_cast<int>(d);dynamic_ cast

dynamic_cast is exclusively used with pointers and references to objects.It

allows any type-casting that can be implicitly performed as well as theinverse one when used with polymorphic classes, however, unlike static_cast,dynamic_cast checks, in this last case, if the operation is valid.

it checks if the casting is going to return a valid complete object of the requestedtype. Checking is performed during run-time execution. If the pointer beingcasted is not a pointer to a valid complete object of the requested type, the value

Page 74: Object Oriented Programming in C++ 10CS36 · Object Oriented Programming in C++ 10CS36 UNIT -1: Introduction to C++ JUNE-JULY 2009 1a. Differentiate between procedure oriented and

OBJECT ORIENTED PROGRAMING WITH C++, Question Paper Solution, III sem

Divyashree J, Lecturer, Dept of CSE 78

returned is a NULL pointer.

c)explain with example , Function Templates are implemented?(8)

To perform identical operations for each type of data compactly and conveniently,use function templates. You can write a single function template definition. Basedon the argument types provided in calls to the function, the compilerautomatically instantiates separate object code functions to handle each type ofcall appropriately.

Function templates are implemented like regular functions, except they areprefixed with the keyword template. Here is a sample with a function template.

#include <iostream>using namespace std ;//max returns the maximum of the two elementstemplate <class T>T max(T a, T b){

return a > b ? a : b ;}

Using function templatesUsing function templates is very easy: just use them like regular functions. Whenthe compiler sees an instantiation of the function template, for example: the callmax(10, 15) in function main, the compiler generates a function max(int, int).Similarly the compiler generates definitions for max(char, char) and max(float,float) in this case.

#include <iostream>using namespace std ;//max returns the maximum of the two elementstemplate <class T>T max(T a, T b){

return a > b ? a : b ;}void main(){

cout << "max(10, 15) = " << max(10, 15) << endl ;cout << "max('k', 's') = " << max('k', 's') << endl ;cout << "max(10.1, 15.2) = " << max(10.1, 15.2) << endl ;

}