5-Object Oriented Programming
5-Object Oriented Programming
Object Oriented
Programming
6. What is bytecode?
8. Define interface.
Part B (5 × 16 = 20 marks)
11. (a) (i) List out the features of object oriented programming.
(ii) Distinguish between abstraction and encapsulation.
(iii) Explain Do-while with an example.
(b) (i) What are constructors? Explain the concept of destruct to with
an example?
(ii) Write a C++ program to list out prime to is between the file two
limits.
12. (a) (i) Explain friend function with an example?
(ii) Write a C++ program to concatenate two strings using to
+operator overloading.
(b) (i) What is inheritance? List out the advantages of inheritance.
(ii) Write a C++ program to implement hierarchical inheritance.
13. (a) (i) Explain IO streams used for file operation.
(ii) Write a C++ program to create a file with odd numbers and
create another file with set of even no is and merge these 2 files
& store in it another file. (8 + 8)
(b) (i) Write a C++ program to generate user defined exception
whenever user i/p’s odd numbers.
(ii) Explain function templates with an example. (9 + 7)
14. (a) (i) Explain about java features. (6)
(ii) Discuss about java command in arguments. (4)
(iii) Write a java program to find the sum of the following series. 1 –
2 + 3 – 4 + …. + 0 (6)
(b) (i) Distinguish between.
(1) Abstract class and class.
(2) Interface and class.
(ii) Discuss about benefits of abstract class.
(iii) Explain dynamic method dispatch with an example.
15. (a) (i) How do we add a class or interface to a package.
(ii) Write a java program to implement nested package.
(b) (i) Explain about thread synchronization with an example.
(ii) Write a java program to create a user defined except whenever
user i/p the word ‘hello’.
NOV-DEC 13
OBJECT CLASS
8. Define interface
An interface can directly inherit resources from one or more interfaces. The extends keyword,
which is used to indicate the class inheritance, is used to declare the interface inheritance also
PART B
General form is
Do
{
Statements;
}while(expression);
Program
#include<iostream.h>
Void main()
{
Int n,i=1,sum=0;
Cout<<”enter n value”;
Cin>>n;
Do
{
Sum+=I;
I++;
}while(i<=n);
Cout<<”sum of first”<<n<<”numbers”<<sum;
}
11 (b) (i) what are constructors? Explain the concept of destructors with an example?
Constructors:
A member function with the same name as its class is called constructor and is used to initialize
the objects of that class type with a legal initial value. When a constructor is declared for a class,
initialization of the class objects becomes mandatory.
Destructors
A destructor is the last member function ever called for an object. The destructor function is called
automatically when a class object goes out of scope. the general form of a destructor function is
~ Class_name();
Where class_name is the name of the destructor (which is same as the name of the constructor i.e., the
name of the class) and is preceded by the tilde (~) sysmbol. For example,
Class destruct
{
Private:
Int sign;
………
……..
Public:
destruct() // constructor
{
Sign=0;
}
~ destruct() //destructor
{ }
….
…..
};
A destructor is normally used for releasing dynamically allocated memory that was previously allocated
for an object by the constructor. Like constructors, destructors do not have a return value. Although the
system provides a default destructor, it is considered as a good programming practice to define a
destructor before the end of each class definition. A destructor doesn’t receive arguments and hence it
cannot be overloaded. Each class can have only one destructor strictly.
11 (b)(ii) write a c++ program to list at prime numbers between the given two limits
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int lim;
int isPrime;
for(int x=2;x<1000;x++)
{
lim=(int) sqrt(x+1);
isPrime=1;
for(int y=2;y<=lim;y++){
if(x%y==0){
isPrime=0;
break;
}
}
if(isPrime)
cout << x << " ";
}
return 0;
}
Friend function
Private members cannot access from outside the class. i.e., a non member function cannot have an access
to the private data of a class. C++ allows the common function to be made friendly with 2 classes, thereby
allowing the function to have access to the private data of these 2 classes. A common function need not be
a member of any of these classes. The general format is
12 (a)(ii) write a c++ program to concatenate two strings using + operator overloading
#include<iostream.h>
#include<string.h>
void main()
{
String s1,s2,s3;
s1="Alex ";
s2="is a super hero";
//concatenation of string objects
s3=s1+s2;
cout<<s3;
}
Student
ECE CSE IT
Advantages
The main features of object oriented programming is reusability.
By using the inheritance concept we achieve reusability of code without redefining it.
It is the process of deriving one class from an already existing class. The new class called
derived class.
Existing class called base class. It represents the most general descriptions
A derived class includes all features of the generic base class and then add qualities
specific to it.
Once inherited the derived class can access all the characteristics of the base class.
#include<iostream.h>
#include<conio.h>
};
int main()
{
clrscr();
getch();
}
13 (a)(ii) write a c++ program to create a file with odd numbers and create another file with set of
even numbers and merge these 2 files and store it in another file.
#include<iostream.h>
#include<conio.h>
void main()
{
FILE *f1,*f2,*f3 *ft;
int number,i;
char ch;
clrscr();
f1 = fopen("DATA","r");
f2 = fopen("ODD","w");
f3 = fopen("EVEN","w");
{
if(number%2==0)
putw(number,f3);
else
putw(number,f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen("ODD","r");
f3 = fopen("EVEN","r");
fclose(f2);
fclose(f3);
fclose(ft);
return 0;
}
13 (b)(i) Write a c++ program to generate user defined exception whenever user inputs odd
numbers
#include<iostream.h>
Int main()
{
int x;
cout<<”enter a number”;
cin>>x;
try
{
if(x%2==0)
{
cout<<”the given number is even”;
}
else
{
Throw(x);
}
}
Catch(int i)
{
cout<<”exception caught the given number is odd”<<x;
}
Cout<<”end”;
return 0;
}
13 (b)(ii) Explain function templates with an example
Function templates
A function templates is a function that servesas skeleton for a family of functions whose tasks are
similar. If templates are not used, many overloaded functions are required in example-1.
Eventhough the code for each function is identical, by using template you can define a pattern for
a family of related overloaded functions by letting the data types of parameters.
Example
Template<class T>
T max(Tx,Ty)
{
Return(x>y)?x:y;
};
Void main()
{
Cout<<max(17,19)<<end 1;
Cout<<max(1.5,6.7)<<end 1;
Cout<<max(‘A’,’B’)<<end 1;
}
Output
19
6.7
‘B’
In the above example you have passed only one data type in the runtime.
A Java application can accept any number of arguments from the command line. This allows the user to
specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the
name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To
sort the data in a file named friends.txt, a user would enter:
When an application is launched, the runtime system passes the command-line arguments to the
application's main method via an array of Strings. In the previous example, the command-line arguments
passed to the Sort application in an array that contains a single String: "friends.txt".
14 (a)(iii) write a java program to find the sumof the following series 1-2+3-4+--------+n (6)
Import java.io.DataInputstream;
class abc
{
Public static void main (string args[])
{
DataInputstream in = new DataInputstream (System.in);
System.out.println(“enter n numbers”);
Int n=Integer.parseInt(in.readLine());
int i,sum=0;
for(i=1;i<=n;i++)
{
if(i==1)
{
System.out.println(i);
sum=sum+i;
}
else if(i%2==0)
{
System.out.println(i);
sum=sum-i;
}
else
{
System.out.println(i);
sum=sum+i;
}
}
System.out.println(sum);
}
Program
Class super
{
Public void method()
{
System.out.println(“method super”);
}
}
Class sub extends super
{
Public void method()
{
System.out.println(“method sub”);
}
}
Class dynamic
{
Public static void main(string args[])
{
Super A=new sub();
A.method();
}
}
Output
Method sub
In the above program A.method() call invokes the sub class version of method() and not the super
class version irrespective of the fact that A super type variable. Thus, in dynamic method
dispatch, the type of reference variable is irrelevant while choosing a particular version of the
overridden method for invocation, instead it solely depends on the type of object being referred
by the reference variable.
import dept.*;
import java.io.*;
class course implements show
{
String dept;
String year;
course(String d, String y)
{
dept=d;
year=y;
}
public void display1()
{
System.out.println ("Department:"+dept);
System.out.println ("Year:"+year);
}
}
interface show
{
void display1();
}
class prg
{
public static void main(String args[])
{
course c=new course("BCA","II YEAR");
faculty f=new faculty("BALAGURUSWAMY","JAVA");
c.display1();
f.display();
}
}
Output
********
C:\jdk1.3\bin>javac prg.java
C:\jdk1.3\bin>java prg
Department: BCA
Year: II YEAR
Name of the faculty:BALAGURUSWAMY
Subject handled by:JAVA
Data corruption may occur if the access to a method by many threads is not properly regulated by
way of synchronizing the access to such a shared method. The access to a method shall be synchronized
by specifying the synchronized keyword as a modifier in the method declaration. When a thread starts
executing a synchronized instance method, it automatically gets a logical lock on the object that contains
the synchronized method. This lock will remain as long as that thread is executing that synchronized
method. When the lock is present, no other thread will be allowed entry into that object.
The lock will be automatically released, when that thread completes the execution of that
synchronized method. Any other executable thread will be allowed entry into that locked object only
when it does not have a lock. This is how the JVM carefully coordinates the access to a common
resource by multiple thread.
Program
Public class fivetable extends thread
{
Public void run()
{
For(int i=1;i<=5;i++)
System.out.println(i+”fives are”+(i*5));
}
}
Public class seventable extends thread
{
Public void run()
{
For(int i=1;i<=5;i++)
System.out.println(i+”sevens are”+(i*7));
}
}
Public class thirteentable extends thread
{
Public void run()
{
For(int i=1;i<=5;i++)
System.out.println(i+”fives are”+(i*13));
}
}
Public class multitable
{
Public static void main(string args[])
{
Fivetable five;
Seventable seven;
Thirteentable thirteen;
Five=new fivetable();
Seven=new seventable();
Thirteen=new thirteentable();
Five.start();
Seven.start();
Thirteen.start();
}
}
In the above, when two or more threads have the same priority, the JVM time-share the processor
time between them
15 (b)(ii) write a java program to create a user defined exception whenever user input the word ‘hello’
Import java.io.*;
Class userdefined
{
Public static void main (string args[]) throws IOException
{
System.out.println(“enter the word”);
InputStreamReader reader=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(reader);
String s1=in.readLine();
String s2=”hello”;
try
{
if(s1.equalsIgnoreCase(s2))
{
Throw(new Exception(“please not enter hello”));
}
else
System.out.println(“your word is “+s1);
}
Catch(Exception e)
{
System.out.println(“statement in catch”);
}
}
}
B.E./B.Tech. DEGREE EXAMINATION,
MAY/JUNE 2013
Fifth Semester
Electrical and Electronics Engineering
OBJECT ORIENTED PROGRAMMING
Time : Three hours Maximum : 100 marks
Answer ALL questions.
PART A (10 × 2 = 20 marks)
1. Define attribute.
10. Which class and interface in Java is used to thread and which is the
most advantageous method?
Part B (5 × 16 = 20 marks)
11. (a) (i) Define polymorphism. Describe the type of polymorphism with
example. (8)
(ii) Explain the order in which constructors are called when
object of a derived class is created. (8)
10. Which class and interface in java is used to create thread and which is the most advantages
methods
we shall create and run a thread by using the Thread class, which is available in
java.lang package. Each thread is either an instance of this class . we can also create a thread
by using Runnable interface. This interface contains the declaration of only one method,
namely run() method. We have to pass an instance of the class that implements this interface
into the Thread constructor as its arguments.
PART B
11 (a) (i) Define polymorphism. Describe the type of polymorphism with example
Refer nov/dec 2012 q.no 11 b (i)
11 (a) (ii) Explain the order in which constructors are called when an object of a derived
class is created
A super class constructor should be executed before a subclass constructor is executed.
Only an object of a subclass will be properly initialized. For example,
Class B extends A
{
.
.
.}
Here the class A is the Super class of class B. thus, the constructor of A should be
executed before the constructor of B is executed. We shall execute the constructor of a super
class by using the super keyword in a simple command of the following form
Super(arguments)
Here, the arguments represent an optional list of arguments for the constructor of the
super class. The above statement should appear as the very first statement of the constructor
of the subclass. If a subclass constructor does not call the super class constructor, the super
class object is constructed with its default constructor. If the super class does not havea
default constructor then the compiler will report an error.
Example
Class x
{ int i;
X(int i)
{this.i=i;
}
}
Class y extends x
{
Int j;
Y(int I, int j)
{
Super(i);
This.j=j;
}
}
Class xydemo
{
Public static void main (string args[])
{
Y y1=new y(11,12);
System.out.println(“value of i in class y is”+y1.i);
System.out.println(“value of j in class y is”+y1.j);
}
}
Output
Value of I in class y is 11
Value of j in class y is 12
11 b) #include<iostream.h>
#include<conio.h>
class student
{
Int s;
Public:
Virtual void get()=0;
Virtual void put(){}
};
Class science:public virfun
{
Int sno,phy,che,mat;
Char *na;
Public:
Void get()
{
Cout<<”enter the student no, name, physics, chemistry maths”;
Cin>>sno>>na>>phy>>che>>mat;
}
Void put()
{
Cout<<sno<<na<<phy<<che<<mat;
}
};
Class arts:public virfun
{
Int sno,his,eng,eco;
Char *na;
Public:
Void get()
cout<<”enter the student no, name, history, English,economics”;
Cin>>sno>>na>>his>>eng>>eco;
}
Void put()
{
Cout<<sno<<na<<his<<eng<<eco;
}
};
Void main()
{
Virfun *v[5];
Char ch;
For (int i=0;i<5;i++)
{
Cout<<”Enter your choice. Please enter 1 for science and 2 for arts”;
Ch=getch();
If(ch==’1’)
V[i]=new science;
Else
V[i]=new arts;
Else
Cout<<”you enter correct entry”;
V[i]->get();
}
For(i=0;i<5;i++)
{
V[i]->put();
}
}
12 (a) (i) Write a c++ program using operator overloading to add two time value in the format
HH:MM:SS to the resulting time along with rounding off when 24 hours reached. A time class
is created and operator + is overload to add the 2 time class objects.
class time
{
Private
Int hh,mm,ss;
Public:
Void gettime()
{
Cout<<”get time as hours,minutes,seconds”;
Cin>>hh>>mm>>ss;
}
Void puttime(){
Cout<<”time is”<<hh<<”:”<<mm<<”:”<<ss;
}
Void add(time a, time b)
{
sS=a.ss+b.ss;
If (ss>60)
{
Ss=0;
mm=mm+1;
}
mm=a.mm+b.mm;
If (mm>60)
{
hh=hh+1;
}
}
};
Void main()
{
Time A,B,C;
A.gettime();
B.gettime();
c.add(A,B);
C.puttime();
}
12 (a) (ii) Explain in detail about friend function in c++ with example
Refer Nov-Dec 2008 Q.No. 12 (a)(i)
12 (b) (i) What is multiple inheritance? Discuss the syntax and rules of multiple
inheritance in c++. How can you pass parameters to the constructors of base classes in
multiple inheritance? Explain with suitable example?
Definition:
If one class is derived from more than one class then it is called multiple inheritance.
Syntax
Class base-class1
{ derived
Members;
….
};
Class base-class2
{
Members;
….
};
Class derived : access-specifier base-class1, access-specifier base-class2
{
Members;
….
};
Example
/* Area Of Rectangle and Triangle using Interface * /
interface Area
{
float compute(float x, float y);
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));
area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
OUTPUT
Area Of Rectangle = 2.0
Area Of Triangle = 10.0
12 (b) (ii) what is the difference between a virtual function and a pure virtual function?
Give example of each
The main difference is the body of function.
We define them as :
Pure virtual functions have no body and MUST be overloaded in the derived classes. You
cannot create an instance of a class having a pure virtual function, the need is to inherit from
it and overload the all pure virtual functions.
class sample
{
public:virtual void p_v_fun() = 0; //pure virtual function
};
void main()
{
sample *x; // its a pointer, you cannot declare an object of this class because of pure virtual
function.
sample2 y;
x = &y ;
class X
{
public:
virtual void virFun () { /* some definition */ }
};
virFun () is defined for X and usually redefine the function in derived classes:
class Y : public X {
public:
void virFun () {/* another defintion */ }
};
class Z : public X {
public:
void virFun () {/* another defintion */ }
};
13 (a) (i) Write a c++ program to convert the given string from lowercase to uppercase
using files.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<stdlib.h>
#include<ctype.h>
#include<fstream.h>
void main( )
{
ofstream outfile;
ifstream infile;
char fname1[10],fname2[20];
char ch,uch;
clrscr( );
cout<<"Enter a file name to be copied ";
cin>> fname1;
cout<<"Enter new file name";
cin>>fname2;
infile.open(fname1);
if( infile.fail( ) )
{
cerr<< " No such a file Exit";
getch();
exit(1);
}
outfile.open( fname2);
if(outfile.fail( ))
{
cerr<<"Unable to create a file";
getch();
exit(1);
}
while( !infile.eof( ) )
{
ch = (char) infile.get( );
uch = toupper(ch);
outfile.put(uch);
}
infile.close( );
outfile.close( );
getch( );
}
OUTPUT:
Input file
Asbcdefghijklmnopqrstuvwxyz
Output file
ASBCDEFGHIJKLMNOPQRSTUVWXYZ
13 (a) (ii) Explain the following functions with examples for manipulating file pointers.
Seekg(),Seekp(),Tellg(),Tellp()
seekg
Sets the position of the get pointer. The get pointer determines the next location to be read in the
source associated to the stream.
Syntax:
seekg ( position );
Using this function the stream pointer is changed to the absolute position (counting from the
beginning of the file).
seekg ( offset, direction );
Using this function, the position of the get pointer is set to an offset value relative to some
specific point determined by the parameter direction. offset is of the member type off_type,
which is also an integer type. And direction is of type seekdir, which is an enumerated type
(enum) that determines the point from where offset is counted from.
seekp
The seekp method changes the location of a stream object's file pointer for output (put or write.)
In most cases, seekp also changes the location of a stream object's file pointer for input (get or
read.)
seekp ( position );
Using this function the stream pointer is changed to the absolute position (counting from the
beginning of the file).
seekp ( offset, direction );
Using this function, the position of the put pointer is set to an offset value relative to some
specific point determined by the parameter direction. offset is of the member type off_type,
which is also an integer type. And direction is of type seekdir, which is an enumerated type
(enum) that determines the point from where offset is counted from
tellg
The tellg() function is used with input streams, and returns the current "get" position of the
pointer in the stream.
Syntax:
pos_type tellg();
It has no parameters and return a value of the member type pos_type, which is an integer data
type representing the current position of the get stream pointer.
tellp
Returns the absolute position of the put pointer. The put pointer determines the location in the
output sequence where the next output operation is going to take place.
Syntax:
pos_type tellp();
The tellp() function is used with output streams, and returns the current "put" position of the
pointer in the stream. It has no parameters and return a value of the member type pos_type,
which is an integer data type representing the current position of the put stream pointer.
13 (b) (i) What are the various ways of handling exception? When we use multicatch
handlers? Explain with an example
The exception handing mechanism uses 3 blocks try, throw and catch.
Try
Exception handing mechanism transfers control and information from a point of
execution in a program to an exception handler associated with the try block
When the try block throws an exception, the program control leaves the try block
and enters the catch statement of the catch block.
The syntax for try construct is
Try
{ // code raising exception or referring to a function raising exception
}
Catch (type arg)
{ // action for handling exception
}
The try keyword defines a boundary within which an exception can occur.
It contains a block of code enclosed within braces.
It indicates that the program is prepared for testing the existence of exceptions.
If an exception occurs, the program flow is interrupted.
Throw
When an exception is detected it is thrown using a throw statement in the try
block
The syntax of the throw construct is
Throw T;
The keyboard throw is used to raise an exception when an error is generated in the
computation.
It initializes a temporary object of the type T
Catch
A catch block defined by the keyboard catch ‘catches’ the exception ‘thrown’ by
the throw statement in the try block and handles it appropriately.
It immediately follows the try block.
An exception is said to be caught when its type matches the type in the catch
statement.
The syntax of catch construct is
Catch(T)
{ // actins for handling an exception
}
It is possible that a program segment has more than one catch block if more than one
condition to throw an exception.
Program
#include<iostream.h>
Void test(int x)
{
Try
{ if (x==1)throw x;
Else
If (x==0) throw ‘x’
Else
If(x==-1)throw 1.0;
}
Cout<<”end try block”;
Catch (char c)
{
Cout<<”caught a character”;
}
Catch (int m)
{
Cout<<”caught ainteger”;
}
Catch (double d)
{
Cout<<”caught a double”;
}
}
Void main()
{
Cout<<”Testing multiple catches”;
Cout<<”x==1”;
Test(1)
Cout,,”x==0”;
Test(0)
Cout,,”x==-1”;
Test(-1)
Cout,,”x==2”;
Test(2);
}
13 (b) (ii) Draw the I/O stream hierarchy in c++ and explain it clearly
Refer May/June 2012 q.no 13 (a)
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
{
If (a[i]<b[j];
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
Sytem.out.println(“the following list is copied one array from another array content”);
for(i=0;i<5;i++)
{
System.out.println(b[i]);
}
sytem.out.println(“ascending order”);
for(i=0;i<5;i++)
{
System.out.println(a[i]);
}
System.out.println(“the maximum of an array”+a[4]);
}
}
14 (b)(i) write a simple java program to find a given string in a string array
1. import java.util.Scanner;
2. public class StringSearch
3. {
4. public static void main(String[] args)
5. {
6. // Initializing Array
7. String[] nameSearch = {"Reebok", "Nike"};
8.
9.
10. // Declaring Variables.
11. String newName;
12. int Results;
13.
14. Scanner keyboard = new Scanner(System.in);
15.
16. //Asking for input.
17. System.out.print("\nPlease enter in a name: ");
18. newName = keyboard.nextLine();
19.
20. // Conditional statement.
21. Results = nameSearch(nameSearch, newName);
22.
23. if (Results == -1)
24. {
25. System.out.print("\nFound the name " + newName );
26. }
27. else if(Results != -1)
28. {
29. System.out.print("\nCannot find specified name " + newName);
30. }
31.
32. }
33. public static int nameSearch(String[] names, String name)
34. {
35. for (int n = 0; n < names.length; n++)
36. {
37. if (names[n].equals(name))
38. return n;
39. }
40.
41. return -1;
42. }
43. }
14 (b)(ii) write a java program to split a string into multiple java string objects
Import java.io.*;
Class token1
{public static void main(string args[])
{
Try
{
FileReader fr=new FileReader(“sample.dat”);
BufferedReader br=new BufferedReader(fr);
StreamTokenizer str=new StreamTokenizer(br);
Str.ordinaryChar(‘.’);
Str.wordChars(‘\”,’\”);
While (str.nextToken()!=StreamTokenizer.TT_EOF)
{
Switch(str.ttype)
{
Case StreamTokenizer.TT_WORD;
System.out.println(str.lineno()+”)”+str.sval);
Break;
Case StreamTokenizer.TT_NUMBER;
System.out.println(str.lineno()+”)”+str.nval);
Break;
Default:
System.out.println(str.lineno()+”)”+(char)str.ttype);
}}fr.close();
catch
{Exception e}
{}
}
}}
15 (a) create class box and box 3d. box3d is an extended class of box. The above two
classes has to fulfill the following requirements
Include constructor
Set value of length, breath, height
Find out area and volume
public class Box
{
//data declorations
private double length;
private double width;
private double height;
//constructor
Box(double boxWidth, double boxHeight, double boxLength)
{
height = boxHeight;
length = boxLength;
width = boxWidth;
return volume;
}
return area;
}
}
public class BoxTester
{
public static void main(String[]args)
{
}
}
15 (b) What is exception handling in java? Why is it used with example. Explain
how to handle the exception with overload methods.
An exception is an abnormal condition that arises in a code sequence at a run time. The
exception class defines the possible error conditions that the program may encounter.
The purpose of the exception handling mechanism is to provide means to detect and
report an “exceptional circumstance” so that appropriate action can be taken
This example shows how to handle the exception with overloaded methods. You need to have a
try catch block in each method or where the are used.
public class Main {
double method(int i) throws Exception{
return i/0;
}
boolean method(boolean b) {
return !b;
}
static double method(int x, double y) throws Exception {
return x + y ;
}
static double method(double x, double y) {
return x + y - 3;
}
public static void main(String[] args) {
Main mn = new Main();
try{
System.out.println(method(10, 20.0));
System.out.println(method(10.0, 20));
System.out.println(method(10.0, 20.0));
System.out.println(mn.method(10));
}
catch (Exception ex){
System.out.println("exception occoure: "+ ex);
}
}
}
Result:
The above code sample will produce the following result.
30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException: / by zero
B.E./B.Tech. DEGREE EXAMINATION,
NOV/DEC 2012
Fifth Semester
Electrical and Electronics Engineering
OBJECT ORIENTED PROGRAMMING
Time : Three hours Maximum : 100 marks
Answer ALL questions.
PART A (10 × 2 = 20 marks)
1. Differentiate between an object and a class?
5. What is a namespace?
Part B (5 × 16 = 20 marks)
Solutions
PART A
NOVEMBER/DECEMBER 2012
1) Differentiate between an object and a class?
OBJECT CLASS
Object is an identifiable A class is a group of objects
entity with some that share common properties
characteristics and and relationships.
behavior
It is a collection of objects.
It is an instance of the class
Example: fruit is a class
Example: fruit Mango:
Mango is an object
2) What is an abstract class in c++?
A virtual function equated to zero is called pure virtual function. A class containing pure
function is called an abstract class
3) Why can’t friend function be used to overload assignment operator?
Because we cannot change the basic meaning of an operator. i.e., we cannot redefine the
assignment operator (=). It follows the syntax rules of the original operators.
4) What is a virtual class? Why is it used in c++?
The ios class is a virtual class and is to avoid ambiguity that frequently appears in multiple
inheritances. It has an ability to handle formatted and unformatted I/O operations.
5) What is a namespace?
Namespace defines a scope for the identifiers that are used in a program. For using identifiers
defined in the namespace scope we must include the using directive, like
Using namespace std;
Here std is the namespace.
6) What is the difference between throw and throws?
THROW THROWS
It is used to force an it is used declarative for the
exception method
It is also pass a custom it is used when we are not
message to your exception using try catch statement
handling module (only checked exception)
7) Why is java language called as “robust”?
Java provides many safeguards which ensure that only reliable code is executed on the
multiplatform environment it ensure automatic memory allocation and deallocation
management. It handles all the mishandled error conditions by way of providing on object
oriented exception handing mechanism.
8) How does java make an executable file?
Example: Hello.jva File name
We type the text in the notepad and store namely Hello.java. in java, a program is first compiled
and then interpreted. The compiler compiled the code under the name Hello.class (byte code
format). The java virtual machine converted this code into machine code. The java interpreter
load the byte code in Hello.class file, starts the execution of our program
9) What is the difference between an interface and an abstract class?
INTERFACE ABSTRACT CLASS
It declares a set of methods and their It cannot create objects
signatures.
All abstract methods that are declared
All methods are declared in an in an abstract class.
interface.
10) What is a inner class?
An inner class is the one that is defined inside another class. The methods in an inner class have
access to the data members and methods in the class within which it is defined.
.
PART – B
11 (a)(i) Explain the characteristics of OOPS in detail. (8)
OOP Is an approach that provides a way of modularizing programs by creating partitioned
memory area for both data and functions that can be used as templates for creating copies of
such modules on demand.
OOP treats data as a critical element in the program development and does not allow it
to flow freely around the system. It ties data closely to the functions that operate on it and
protects it from accidental modification from outside functions.
It allows decomposition of a problem into a number of entities called objects and then
builds data and functions around these objects. The data of an object can be accessed only by
the functions associated with the object.
Features
Emphasis is on data rather than procedure
Improvement over the structured programming paradigm.
Data structures are designed such that they characterize the object.
Functions that operate on the data of an object are tied together in the data structure.
Data is hidden that cannot be accessed by external functions.
Object may communicate with each other through functions.
New data and functions scan be added easily.
Follow bottom up approach in program design.
11 (a)(ii) Write a c++ program to generate Fibonacci using copy constructor. (8)
#include <iostream.h>
class fibonacci
{
private:
unsigned long int f0,f1,fib;
public:
fibonacci()
{
f0=0;
f1=1;
fib=f0+f1;
}
fibonacci (fibonacci &ptr)
{
f0=ptr.f0;
f1=ptr.f1;
fib=ptr.fib;
}
void increment()
{
f0=f1;
f1=fib;
fib=f0+f1;
}
void display()
{
cout << fib << 't\';
}
}; //end of class construction
void main (void)
{
fibonacci number;
for (int i=0; i<=15;i++)
{
number.display();
number.increment();
}
}
11 (b)(i) What is polymorphism? Explain different types of polymorphism (8)
Polymorphism means the ability of an organism to assume a variety forms.
It is implemented using the over loaded functions and operations.’
Types of polymorphism
Polymorphism is classified into 2 types
1. Compile time polymorphism.
2. Run time polymorphism
1. Compile time polymorphism
The over loaded member functions are selected for invoking by matching
arguments, both type and number. This information is known to the compiler
at the compile time and therefore compile is able to select the appropriate
function for a particular at the compile time itself. This is called early binding or
static binding or static linking. Also known as compile time polymorphism.
2. Rum time polymorphism
Appropriate member functions could be selected during the run time. This is
called as late binding or dynamic binding or run time polymorphism. Virtual
function is used to achieve run time polymorphism.
polymorphism
Compile time
Run time
polymorphism
polymorphism
Virtual functions
Function overloading Operator overloading
Types of polymorphism
3. Virtual function
When we use the same function name in both the base and derived classes, the function in base class
declared as virtual using the keyword ‘virtual’ preceding its normal declaration.
When a function is made virtual, c++ determines which function to use at run time based on this type
of object pointed to by the pointed rather than the type of the pointer.
Rules for virtual functions
1. The virtual function must be members of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be friend of another class.
5. A virtual function in a base class must be defined, even though it may not be
used.
6. The prototypes of the base class version of a virtual function and all the
derived class version must be4 identical.
7. If 2 functions with the same name have different prototypes, c++ consider
them as overloaded function and the virtual function mechanism is ignored.
8. We cannot have virtual constructors, but we can have virtual destructors.
Virtual functions allow programmers to declare function in a base class, which can be defined in each
derived class. A pointer to an object of a base class can also point to the objects of its derived class. In
this case, member functions to be invoked depend on the class’s object to which the pointer is pointing.
When a call to any object is made using the same interface, the function relevant to that object will be
selected at run time.
11 (b)(ii) Write a c++ program to implement dynamic memory allocation. (8)
#include<iostream.h>
#include<conio.h>
Void main()
{
Int *p=new int[3],k; / /memory allocation for 3 integers
for (k=0;k<3;k++)
{
Cout<<”Enter a numbr”;
Cin>>*p;
P++; // pointing to next location
}
p‐=3; // back to starting location
cout<<”Entered numbers with their address are “;
for(k=0;k<3;k++)
{
Cout<<*p<<”\t”<<(unsigned)p; // type casting
P++;
}
p‐=3;
delete p;
}
Output
Enter a number:7
Enter a number:9
Enter a numbr:8
Entered numbers with their address are
7 3658
9 3660
8 3662
12. (a) (i) Explain about implementation of runtime polymorphism in c++ with an example.
The keyword virtual mechanism for defining the virtual functions.
When declaring the base class member functions, the keyword virtual is used with those
functions, which are to be bound dynamically.
The syntax for defining a virtual function is given below.
Class classname
{
Public:
Virtual return type function name (arguments)
{
….
…..
…..}
……
…..
….
};
Virtual function should be defined in the public section of the class. When such a declaration is
made, it allows to decide which function to be used at run time, based on the type of object, pointed to
by the base pointer rather than the type of the pointer. Virtual functions have to be accessed through a
pointer to the base class. They can be accessed through objects instead of pointers.
The runtime polymorphism is achieved only when a virtual function is accessed through a
pointer to the base class. Only class member functions can be declared as virtual functions. Regular
functions and friend functions do not qualify as virtual functions.
// program to demonstrate the usage of virtual functions.
#include<iostream.h>
Class base_class
{
Public:
Virtual void putdata()
{
Cout<<”this is base class”;
}
};
Class derived_class : public base_class
{
Public:
Void putdata()
{
Cout<<”this is derived class”;
}
};
Class derived_class2 : public base_class
{
Public:
Void putdata()
{
Cout<<”this is derived class 2”;
}
};
Void main()
{
derived_class dc1;
derived_class dc2;
base_class *ptr;
ptr=&dc1;
ptr‐>putdata();
ptr=&dc2;
ptr‐>putdata();
}
Output
This is derived class 1
This is derived class 2
12 (a)(ii) Explain the types of inheritance with example.
Refer 14(b) Nov‐Dec 2007
12 (b)(i) Explain the usage of template in c++.(8)
A significant benefit of object oriented programming is reusability code which eliminates
redundant coding.
Template support generic programming which allows developing reusable software components
such as functions, classes etc., and supporting different data types in a single frame work.
Template allows the construction of a family of template functions and classes to perform the
same operation on different data types.
The templates declared for functions are called function templates and those declared for
classes are called class templates.
A template can be considered as a kind of macro.
A template is defined with a parameter that would be replaced by a specified data type at the
time of actual use of the class or function.
Class templates
Classes can be declared to operate on different data types
A class template specifies how individual classes can be constructed similar to normal class
specification
These classes model a generic class which supports similar operations for different data types.
Syntax for class templates:
Declaration template <class T1, class T2……>
Class classname
{ //data items of template type T1,T2…
T1 data 1;
// function of template arguments T1,T2…..
Void fun1(T1 a, T2 &b);
T fun2(T2 *x,T2 *y);
};
The prefix template <class T> specifies that a template is being declared and that a type name T
will be used in the declaration.
Syntax for class template instantiation:
Class name datatype objectname;
Example:
Class name <char> object1;
Class name <int> object2;
12 (b) (ii) Explain how left shift and right shift operator are overloaded with an example.
The extraction operator (>>) is used with cin object to carry out input operations. The insertion
operator (<<) is used with cout object to carry out output operations. It is also possible to overload both
these extraction and insertion operator with friend function.
The syntax for overloading (<<) insertion operator is as follows
friend ostream & operator <<(ostream &put,v1)
{
//code
return put;
}
The syntax for overloading (>>) operator is as follows
friend istream & operator >> (istream & get, v2)
{
// code
return get;
}
The keyword friend precedes the declaration. The v1 and v2 is a user defined class object. The ostream
and istream is an output stream class and input stream class followed by reference and keyword
operator. The put is an output stream object like cout and the get is an input stream object like cin.
Example:
#include<iostream.h>
#include<conio.h>
class string
{
char *s;
public:
string (char *k)
{
s=k;
}
friend istream & operator >> (istream &get, string & k)
{
cout<<”enter a string”;
get>>k.s;
return get;
}
friend ostream & operator << (ostream &put, string & k)
{
put>>k.s;
return put;
}
};
Int main()
{
String s;
Cin>>s;
cout<<s;
return 0;
}
13. (a) Explain the file handling techniques in cpp. (16)
For every action on file, it must be opened first. A file is opened in either read, write or append or other modes.
Using constructor, a file can be opened by passing a filename as parameter in the constructor. Since constructor is
invoked during the time of object creation, it can be used to initialize the file stream object with the filename, so that
the file stream object refers to the file. The statement
ofstream oufile("myfile.txt");
opens the file myfile.txt for output. After opening the file through file stream object, the read/write
operation can be performed through the stream operator insertion (<<) and extraction (>>). To write to
the file “myfile.txt” opened through file stream object outfile we write the statement
outfile<<"John Doe";
ifstream infile("myfile.txt");
infile>>age;
This statement reads data from file “myfile.txt” to variable age through file stream object infile.
Apart from constructor, file can be opened explicitly by making use of member function open(). The
function open() is a member of all the file stream classes ofstream, ifstream and fstream. The syntax for
opening and closing file explicitly for writing purpose is
ofstream fout;
fout.open("myfile.txt");
// some operation
fout.close();
ifstream fin;
fin.open("myfile.txt");
//some operation
fin.close();
To append data in existing files, or to create a new file if it doesn’t exist, use the file open
mode ios::app in the open ( ) function. Example
Ofstream out;
Out.open(“data.txt”,ios::app);
// some operation
Out.close ()
read( ) and write( ) - they are defined in the classes istream and ostream classes respectively. They are
used for reading and writing blocks of binary data in to a file.
getline( ) - it is defined in the istream used for reading one line at a time from a file. This is a line-
oriented input function, which reads a complete line until it encounters a newline character.
13 (b) Write a c++ program to create class called STRING and implement the following operations.
Display the results after every operation by overloading the operator <<
(i) STRING s 1 = “Anna”
(ii) STRING s2 = “university”
(iii) STRING s3 = s1+s2 (use copy constructor).
#include<iostream.h>
#include<conio.h>
#include<string.h>
class String
{
char x[40];
public:
String() { } // Default Constructor
String( char s[] )
{
strcpy(x,s);
}
String( String & s )
{
strcpy(x,s.x );
}
String operator + ( String s2 )
{
String res;
strcpy( res.x,x );
strcat( res.x,s2.x);
return(res);
}
friend ostream & operator << ( ostream & x,String & s );
};
int main()
{
clrscr();
String s1="Anna";
String s2="University";
String s3 = s1+ s2; // String s3 = s1 +" "+ s2;
cout<<"\n\ns1 = "<<s1;
cout<<"\n\ns2 = "<<s2;
cout<<"\n\ns1 + s2 = "<<s3;
getch();
return 0;
}
14. (a) (i) Explain about various string operations in java.(8)
Strings contain sequences of 16‐bit Unicode characters. The string class represents character strings. All
string literals in java programs such s “abc” are implemented as instances of this class. Strings are
constant; their values cannot be changed after they are created.
For example:
String str=”abc”;
Is equivalent to:
char data[]={‘a’,’b’,’c’};
String str=new String(data);
The various string operations in java are as follows
int length( )
Returns the length of the string. The length is equal to the number of 16‐bit Unicode characters
in the string. Example : str.length( );
String concat(String str)
Concatenates the specified string to the end of this string. If the length of the argument string is
0. Then this string object is returned.
Example: str.concat(“java”);
String replace (char oldchar, char newchar)
Returns a new string resulting from replacing all occurrences of oldchar in this string with
newchar.
Example: “hello”.replace(‘l’,’w’);
String toLowerCase( )
Converts all of the characters in this string to lower case.
Example: str.toUpperCase()
String toUpperCase()
Converts all of the characters in this string to upper case.
Example: str.toLowerCase()
String trim()
Removes white space from both ends of the string.
14 (a)(ii) write a java program to find the maximum number of the given array.(8)
import java.util.Scanner;
class group{
public static void main(String arng[]){
int value[]= new int[5];
int temp,i;
Scanner data = new Scanner(System.in);
System.out.println("Enter 5 element of array" );
// Enhanced for loop
for(i=0; i < 5; i++ ) value[i] = data.nextInt();
// finding Largest number
temp = value[0];
for(i=0; i < 5; i++ )
{
if(temp > value[i])
continue;
else
temp = value[i];
}
System.out.println("Largest number in array is "+temp);
}
}
Output:‐
Enter 5 element of array
25
154
28522
218
2564
Largest number in array is 28522
14 (b)(i) Explain about packages in java. (8)
The java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are:
Languages support package (Java.lang) : A collection of classes and methods required for
implementing basic features of Java .
Utilities Package (Java.util) : A collection of classes to provide utility functions such as date and
time functioins.
Input/Output package (Java.io) : A collection of classes required for input/output manipulation
Networking package (Java.net) : A collection of classes for communicating with other
computers svia Internet.
AWT Package (Java.awt) : the Abstract Window Tool Kit package contains classes that
implements graphical user interface.
Applet Package (Java.applet) : a set of classes that allows creating Java applets.
14 (b)(ii) Write a program to convert an Integer array to String (8)
import java.util.Arrays;
Output
int array converted to String using for loop
12345
String generated from Arrays.toString method: [1, 2, 3, 4, 5]
Final String: 1 2 3 4 5
15 (a)(i) Write a java program to implement multiple inheritance using interface
/* Area Of Rectangle and Triangle using Interface * /
interface Area
{
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));
area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
OUTPUT
Area Of Rectangle = 2.0
Area Of Triangle = 10.0
15(a)(ii) what is multithreading? Explain with an example.
Multithreading is a conceptual programming paradigm where a program process is divided into two or
more subprograms which can be implemented at the same time in parallel. For example, one subprogram
displays animation while other one builds another animation. This is similar to dividing task into
subtasks and assigning them to different process for execution independently and simultaneously. Thread
is similar to a program that has a single flow of control. A program that contains multiple flows of
control is known as multithreaded program.
Multithreading is a powerful programming tool and distinct from other programming languages.
It enables a programmer multiple things at one time. Longer programs can be divided into threads and
executed in parallel.
Creating Threads:
We can create thread in a program using class Thread or implementing interface Runnable.
Lifecycle of a Thread
1. New state - After the creations of Thread instance the thread is in this state but before the start()
method invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state - A thread start its life from Runnable state. A thread first enters
runnable state after the invoking of start() method but a thread can return to this state after either
running, waiting, sleeping or coming back from blocked state also. On this state a thread is
waiting for a turn on the processor.
3. Running state - A thread is in running state that means the thread is currently executing. There
are several ways to enter in Runnable state but there is only one way to enter in Running state: the
scheduler select a thread from runnable pool.
4. Dead state - A thread can be considered dead when its run() method completes. If any thread
comes on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that are hold by
another thread.
Thread.sleep(1000);//Blocked
}catch(Exception e){}
}
}//Dead state
}
15 (b)(i) Write a java program to add 2 integers and raise exception when any other character except
number (0‐9) is given as input.
import java.io.*;
public class exceptionHandle{
public static void main(String[] args) throws Exception{
try{
int a,b;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()+ " is not a numeric value.");
System.exit(0);
}
}
}
15 (b)(ii) write short notes on various I/O streams in java.
The InputStream and OutputStream classes, and their subclasses are used for dealing with data
in binary format. The important methods in these two classes are described in the following tables.
Important Methods in the Inputstream class
7 close() To close the input stream
Important Methods in the Output stream class
Important subclasses in the Input stream class
Important subclasses in the Output stream class
B.E./B.Tech. DEGREE EXAMINATION,
MAY/JUNE 2012
Fifth Semester
Electrical and Electronics Engineering
OBJECT ORIENTED PROGRAMMING
Time : Three hours Maximum : 100 marks
Answer ALL questions.
PART A (10 × 2 = 20 marks)
1. Define abstraction and encapsulation?
Part B (5 × 16 = 20 marks)
11. (a) Explain in detail about class, objects, methods and messages.
(b) Write a c++ program to define overloaded constructor to perform
string initialization, string copy and string destruction.
12. (a) Write a c++ program to implement C=A+B, C=A-B and C=A*B
where A,B and C are objects containing a int value( vector)
. Member operator
* Pointer to member operator
: : Scope access operator
?: Conditional operator
Size of () size of operator
# and ## preprocessor symbols.
4) What are pure virtual functions? Where are used?
A virtual function, equated to zero is called a pure virtual. It is a function declared in a base class
that has no definition relative to the base class. A class containing such pure function is called
an abstract class.
5) Define exception give example.
Exceptions are peculiar problem that a program may encounter at no time.
Ex: 1) invalid argument 2) Insufficient memory 3) Division by zero etc
6) State the purpose of namespaces with example?
Namespace is used to define a scope that could hold global identifiers.
Example: namespace name
{
Declaration of identifiers
}
7) What is byte code?
Byte code is a special instruction that can be run by java interpreter. It is not machine instructions.
8) What are packages?
A package is a collection of related classes and interfaces. We can easily access the classes and
interfaces of a package in a program by importing that package into that program.
9) Define interface. State its use.
An interface can directly inherit resources from one or more interfaces. The extends keyword, which is
used to indicate the class inheritance, is used to declare the interface inheritance also
10) What is thread?
A thread is a program unit that is executed independently of other parts of the program, many threads
may be defined and used within a program.
PART B
11 (a) Explain in detail about class, objects, methods and messages.
CLASS: “A class is a group of objects that share common properties and relationships.”
The entire set of data and code of an object can be made a user defined data type with the help
of a class. Objects are variable of the type class.
A class is a collection of objects sof similar type.
Classes are user defined data types and behave like the built in types of a programming
language.
Example: 1. Fruit has been defined das a class, then the statement fruit mango; will create an
object mango belonging to the class fruit.
Objects: “Object is an identifiable entity with some characteristics and behavior”
Objects are the basic run‐time entities in an object oriented system.
They may represent a person, a place, a bank account, a table of data or any item that the
program has to handle.
They may also represent user defined data such as vectors, time and lists.
Programming problem is analyzed in terms of objects and the nature of communication
between them.
Program objects should be chosen such that they match closely with real world objects.
When programming is executed, the objects interact by sending messages to one another.
Example: 1. Orange is an object. Its characteristics are it is spherical shaped; its colour is orange
etc. Its behavior is juicy and it tastes sweet sour.
2. Customer and account are 2 objects in a program, then the customer object may send a
message to the account object requesting for the bank balance.
Methods: An operation required for an object or when coded in a class is called a method.
Operations that are required for an object are to be defined in a class. All objects in a class
perform certain common actions or operations. Each action needs an object that becomes a
function of the class that defines it and is referred to as a method.
Example:
class A
{
Private
data member1;
data member2; Members
data member(n);
Public
method1() { }
method2() { } Methods or Member functions.
method _n { }
};
Messages
An object oriented programming consists of a set of objects that communicate with each other.
The process of programming in an object oriented involves the following steps.
1. Creating classes that define objects and their behavior
2. Crating objects from class definition.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information.
The message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and the information to be sent.
Communication with an object is feasible as long as it in alive.
Example
Employee. salary (name)
Object message information
11 (b) Write a c++ program to define overloaded constructor to perform string initialization, string copy
and string destruction.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
private:
int age;
char name[25];
public:
student(int a, char n[25])
{
age=a;
strcpy(name,n);
}
void show()
{
cout<<"\nThe name of the student is: "<<name;
cout<<"\nHis age is: "<<age;
}
~student() //destructor defined
{
cout<<"\nObject Destroyed";
}
};
int main()
{
student s1(21,"Rahul");
student s2(23,"Dipankar");
clrscr();
s1.show();
s2.show();
return 0;
}
Output:
The name of the student is : Rahul
His age is : 21
The name of the student is : Dipankar
His age is : 23
Object Destroyed
Object Destroyed
12 (a) Write a c++ program to implement C=A+B, C=A‐B and C=A*B where A,B and C are objects
containing a int value( vector)
#include<iostream.h>
class vector
{
public :
int a,b,c,d,e;
vector operator+(vector p)
{
p.c=p.a+p.b;
return p;
}
vector operator*(vector p)
{
p.c=p.a*p.b;
return p;
}
vector operator‐(vector p)
{
p.c=p.a‐p.b;
return p;
}
void accept()
{
cout<<”enter 2 values”);
cin>>a>>b;
}
};
void main()
{
vector x;
x.accept();
x.c=x.a+x.b;
cout<<”sum”<<x.c<<endl;
x.d=x.a‐x.b;
cout<<”difference”<<x.d<<endl;
x.e=x.a*x.b;
cout<<”multiply”<<x.e<<endl;
}
12 (b) Explain run time polymorphism with example program.
Rum time polymorphism
Appropriate member functions could be selected during the run time. This is called as late binding or
dynamic binding or run time polymorphism. Virtual function is used to achieve run time polymorphism.
polymorphism
Compile time
Run time
polymorphism
polymorphism
Virtual functions
Function overloading Operator overloading
Types of polymorphism
Virtual function
When we use the same function name in both the base and derived classes, the function in base class
declared as virtual using the keyword ‘virtual’ preceding its normal declaration.
When a function is made virtual, c++ determines which function to use at run time based on this type
of object pointed to by the pointed rather than the type of the pointer.
Rules for virtual functions
The virtual function must be members of some class.
They cannot be static members.
They are accessed by using object pointers.
A virtual function can be friend of another class.
A virtual function in a base class must be defined, even though it may not be used.
The prototypes of the base class version of a virtual function and all the derived class version
must be4 identical.
If 2 functions with the same name have different prototypes, c++ consider them as overloaded
function and the virtual function mechanism is ignored.
We cannot have virtual constructors, but we can have virtual destructors.
Virtual functions allow programmers to declare function in a base class, which can be defined in each
derived class. A pointer to an object of a base class can also point to the objects of its derived class. In
this case, member functions to be invoked depend on the class’s object to which the pointer is pointing.
When a call to any object is made using the same interface, the function relevant to that object will be
selected at run time.
Definition of virtual functions
The keyword virtual mechanism for defining the virtual functions.
When declaring the base class member functions, the keyword virtual is used with those
functions, which are to be bound dynamically.
The syntax for defining a virtual function is given below.
Class classname
{
Public:
Virtual return type function name (arguments)
{
….
…..
…..}
……
…..
….
};
Virtual function should be defined in the public section of the class. When such a declaration is
made, it allows to decide which function to be used at run time, based on the type of object, pointed to
by the base pointer rather than the type of the pointer. Virtual functions have to be accessed through a
pointer to the base class. They can be accessed through objects instead of pointers.
The runtime polymorphism is achieved only when a virtual function is accessed through a
pointer to the base class. Only class member functions can be declared as virtual functions. Regular
functions and friend functions do not qualify as virtual functions.
// program to demonstrate the usage of virtual functions.
#include<iostream.h>
Class base_class
{
Public:
Virtual void putdata()
{
Cout<<”this is base class”;
}
};
Class derived_class : public base_class
{
Public:
Void putdata()
{
Cout<<”this is derived class”;
};
};
Class derived_class2 : public base_class
{
Public:
Void putdata()
{
Cout<<”this is derived class 2”;
}
};
Void main()
{
derived_class dc1;
derived_class dc2;
base_class *ptr;
ptr=&dc1;
ptr‐>putdata();
ptr=&dc2;
ptr‐>putdata();
}
Output
This is derived class 1
This is derived class 2
13 (a) Explain the different types of streams and various formatted I/O
In java, a stream is a path along which the data flows. Every stream has a source and a destination. The
source and destination for a stream may be two other stream in the same program or two different
programs (client and server program) or two physical devices (HDD and console screen).
Two fundamental types of streams are input streams and output streams. While an output stream
writes data into file (or stream or program or device), an input stream is used to read data from a file (or
stream or program or device.) The java.io package has plenty of Stream Classes. They are
INPUTSTREAM AND OUTPUTSTREAM CLASSES
The InputStream and OutputStream classes and their subclasses are used for dealing with data in binary
format. The important methods in these two classes are described in the following tables.
Important Methods in the Inputstream class
Important Methods in the Outputstream class
Important subclasses in the Inputstream class
Important subclasses in the Outputstream class
DATAINPUTSTREAM CLASS
The DataInputStream class extends FilterInputStream class and implements DataInput interface. The
FilterInputStream class extends the InputStream class. Therefore, the DataInputStream class contains
all the methods available in the InputStream class.
readShort(), readInt(), readLong(), readFloat(), readDouble(), readBytes(), readChar(), readBoolean(),
readUTF().
DATAOUTPUTSTREAM CLASS
The DataOutputStream class extends FilterOutputStream class and implements DataOutput interface.
The FilterOutputStream class extends the OutputStream class. Therefore, the DataOutputStream class
contains all the methods available in the OutputStream class.
writeShort(),writeInt(),writeLong(),writeFloat(),writeDouble(),writeBytes(),writeChar(),writeBoolean()
, writeUTF().
STREAMTOKENIZER CLASS
This class is a subclass of object class, which is a predefined class in the java.lang package. The methods
is in the StreamTokenizer class are useful in breaking up a stream of text from an input text file into
meaningful tokens. Here some important points are
The methods in this class parse the data received from a character input stream and generate a
sequence of tokens.
A token is a group of characters that represent a word or a number.
This class defines four predefined constants – TT‐EOF,TT‐EOL,TT‐WORD AND TT‐NUMBER
If the current token is a number,ttype is equal to TT‐NUMBER and nval contains its value.
If the current token is a word, ttype is equal to TT‐WORD and sval contains its value.
Otherwise, ttype contains the character that has been read.
FILTER STREAMS
Filter streams are defined as streams that filter bytes or characters for some purpose. The basic
input stream provides a method only for reading bytes or characters. If we want to read integers,
doubles, or strings, we have to use the appropriate filter streams
PRINT STREAMS
We can use print streams to output data into a file or to the console. The PrintStream class has the
print() method . The println() method inserts a new line character at the end of the output.
OBJECT STREAMS
The object streams enable us to store and retrieve all instance variables of an object automatically. The
important object stream classes are ObjectInputStream and ObjectOutputStream. While the
ObjectOutputStream class helps us to save an entire object out to disk, the ObjectInputStream class
enables us to read the object back in.
13 (b) Explain the various file handling mechanism in detail
Refer Nov‐Dec 2012 Q. No.13 (a)
14) a) Write a java program to create two single dimensional arrays, initialize them and add them, store
the result in another array.
import java.io.*;
class array1
{
public static void main (String[] args)
{
int a[]={17,15,46,36,78};
int b[]={34,56,44,89,25};
int c[]=new int[10];
int i;
14 (b) Write a java program to perform all string operations using String class.
public class Stringdemo
{
public static void main(String s[]]
{
char ch;
String str=”This Is A Test”;
String upper=str.toUpperCase();
String lower=str.toLowerCase();
String concat=str.concat(“In Java”);
String trm=” Hello World “.trim();
String replace=”Hello”.replace(‘I’,’W’);
ch=”abc”.charAt(2);
System.out.println(ch);
System.out.println(“Uppercase “+upper);
System.out.println(“Lowercase “+lower);
System.out.println(“Concatenate”+concat);
System.out.println(“Trimming “+trm);
System.out.println(“Replace “+replace);
}
}
Output
c
Uppercase THIS IS A TEXT
Lowercase this is a text
Concatenate This Ia A TestIn Java
Trimming Hello World
Replace Hewwo
15 (a) explain in detail about inheritance with example program in java language.
Refer Nov‐Dec 2007 Q. No. 14 (b)
15 (b) Explain with example program exception handling in java.
Refer Nov‐Dec 2007 Q. No. 13 (a)(ii)
B.E./B.Tech. DEGREE EXAMINATION,
NOV/DEC 2009
Fifth Semester
Electrical and Electronics Engineering
OBJECT ORIENTED PROGRAMMING
Time : Three hours Maximum : 100 marks
Answer ALL questions.
PART A (10 × 2 = 20 marks)
1. What is object oriented programming? List any four oop languages.
10. Give the paint method of an applet which draws a blue circle.
Part B (5 × 16 = 20 marks)
11. (a) (i) Explain the concepts of object oriented programming in detail
(ii) Explain in detail ignore(), peek() and putback() with an example
12 (a) (i) Write in detail about friend function and friend classes
5. What is hierarchical inheritance?
When many subclasses inherit from c++ single base class. It is used to support hierarchical design of the
program.
Example: hierarchical classification of student
Student
Arts engineering medical
ECE CSE IT.
6. Define this pointer.
C++ uses unique keyword called ‘this’ to represent an object that invokes a member function.
7. How does java achieve platform independence?
Java programs can be easily moved from one computer system to another, anywhere and anytime. Changes and
upgrades in operating system, processors and system resources will not force any changes in java programs. This
is the reason where java achieves platform independence.
8. Distinguish between method overriding and method overloading in java
Overriding Overloading
The ability to change the definition of an inherited A language feature that allows a function or
method or attribute in a subclass. operator to be given more than one definition.
The type of the arguments with which the function
or operator is called, determines which definitions
will be used.
9. What happens if an exception handler is not defined when exception is thrown?
The flow of execution stops immediately after the throw statement; any subsequent statements are not
executed. The compiler displays an error; it will not create the .class file
10. Give the paint method of an applet which draws a blue circle.
Ex:
…..
…
Public void paint(Graphics g)
{
g.setColor(color.blue);
g.filloval(30,80,100,100);
}
…
…
Here we call that the filloval() method, which is present in the Graphics class, is to be used in the paint() method
for drawing the circle with blue color.
PART B
11 a) i) Explain the concepts of object oriented programming in detail (10)
CLASS: “A class is a group of objects that share common properties and relationships.”
The entire set of data and code of an object can be made a user defined data type with the help of a
class.
Objects are variable of the type class.
A class is a collection of objects of similar type.
Example: 1. Fruit has been defined das a class, then the statement fruit mango; will create an object
mango belonging to the class fruit.
Objects: “Object is an identifiable entity with some characteristics and behavior”
Objects are the basic run‐time entities in an object oriented system.
They may represent a person, a place, a bank account, a table of data or any item that the program has
to handle.
They may also represent user defined data such as vectors, time and lists.
Example: 1. Orange is an object. Its characteristics are it is spherical shaped; its colour is orange etc. Its
behavior is juicy and it tastes sweet sour.
Methods: An operation required for an object or when coded in a class is called a method. Operations that are
required for an object are to be defined in a class. All objects in a class perform certain common actions or
operations. Each action needs an object that becomes a function of the class that defines it and is referred to as
a method.
Example:
class A
{
Private
data member1;
data member2; Members
data member(n);
Public
method1() { }
method2() { } Methods or Member functions.
method _n { }
};
Messages
An object oriented programming consists of a set of objects that communicate with each other. The process of
programming in an object oriented involves the following steps.
1. Creating classes that define objects and their behavior
2. Crating objects from class definition.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information.
The message for an object is a request for execution of a procedure and therefore will invoke a function
in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function (message) and the
information to be sent.
Communication with an object is feasible as long as it in alive.
Example
Employee. salary (name)
Object message information
Data abstraction
Abstraction refers to the act of representing essential features without including the background details or
explanations.
Data encapsulation
The wrapping up of data and operation/functions into a single unit called data encapsulation
The data is not accessible to the outside world, and only those functions which are wrapped in the class can
access it.
Inheritance
Inheritance is the process of creating new classes from existing classes.
Example
Student
Arts engineering medical
ECE CSE IT
Polymorphism
Polymorphism means the ability of an organism to assume a variety forms. It is implemented using the over loaded
functions and operations.
Types of polymorphism
Polymorphism is classified into 2 types
1. Compile time polymorphism.
2. Run time polymorphism
Dynamic binding
It means that the code associated with a given procedure call is not known until the time of the call at run time.
11 a)(ii) Explain in detail ignore(), peek() and putback() with an example (6)
ignore() function: It is used to read and remove characters from a input stream. Syntax of ignore() function:
istream &ignore(streamsize num=1, int_type delimiter=EOF);
Here, characters are read and ignored until num or until delimiter is encountered.
peek() function: It is used to get next character in input stream without removing that particular character from
the input stream. Syntax of peek() function:
int_type peek( );
putback() function: It is used to return the last character which was read from the stream to the same stream.
Syntax of putback() function:
istream &putback(char c);
11 b) (i) Write in detail about passing arguments to function (9)
Refer Nov‐Dec 2007 Q.No.13 (a)(i)
11 b) (ii) Write a user defined manipulator to print “\t\t” (7)
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
void main( )
{
clrscr( );
cout <<1<<tab<<2 <<tab<<3;
}
OUTPUT
123
In the above program, tab named manipulator is defined. The definition of tab manipulator contains the escape sequence ‘\t’.
Whenever we call the tab manipulator, the ‘\t’ is executed and we get the effect of tab.
12 (a) (i) Write in detail about friend function and friend classes (8)
Refer Nov‐Dec 2008 Q.No. 12 (a)
12 (a) (ii) Write a program to create a student database using array of objects (8) #include<iostream.h>
#include<stdio.h>
class student
{
char name[10][8],course[10][8];
inti,j,roll‐no;
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<"Enter the name : " ;cin>>name;
cout<<"Enter the roll no. :" ;cin>>roll_no;
cout<<"Enter the course : "; cin>>course;
}
void student :: putdata()
{
cout<<"Name of the student : "<<name;
cout<<"\n Roll no. : "<<roll_no;
cout<<"\nCourse : "<<course;
}
void main()
{
int i;
clrscr();
student std[5];
for(i=0;i<5;i++)
{
cout<<"\n \t\tDetails of the student"<<i+1<<"\n";
std[i].getdata();
}
for(i=0;i<5;i++)
{
std[i].putdata();
}
for(i=0;i<5;i++)
{
std[i].putdata();
}
getch();
}
12 b)(i) Explain with example the significance of static keyword in member function and variable declaration (10)
A static function can have access to only other static members (functions or variables) declared in the same class. This
function can be called using the class name (instead of its objects) as follows:
Class_name :: function_name;
Example
#include<iostream>
class test
{
int code;
static int count;
public:
void setcode(void)
{
code=++count;
}
void showcode(void)
{
cout<<”object number”<<code<<”\n”;
}
static void showcount(void)
{
cout<<”count”<<count<<”\n”;
}
};
int test :: count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test :: showcount();
test t3;
t3.setcode;
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
Static variable declaration
When a variable is declared as static, it means that it is not dependent on any particular instance of a class. These
variables belong to the entire class and are called class variables. A static variable can be accessed b just specifying the
name of the class even without creating an object.
Method can also be declared as static. A static method has several restrictions.
They can call only other static methods
They must only access static data and they cannot refer to this or super in anyway.
12 b) (ii) Explain copy constructors with an example (6)
A constructor can accept a reference to its own class as a parameter is called the copy constructor.
A copy constructor is a constructor of the form class name (class name &)
The compiler will use the copy constructor whenever you initialize an instance using values of another instance
of same type.
Example;
Sample S1; // default constructor
Sample S2=S1; // copy constructor
A copy constructor takes reference to an object of the same classs an argument.
Example:
class sample
{ int i,j;
public:
sample (int a, int b) // constructor
sample (sample &s) // copy constructor
{ j=s.j;
i=s.i;
}
};
sample s1(4,6); // s1 initialized
sample s2(s1); // s1 copied to s2 copy constructor called.
sample s3=s1; // s1 copied to s3
Copy constructor is used to declare and initialize an object from another object.
Example: integer I2 (I1);
It defines the objects I2 and at the same time initializes it to the value of I1.
The process of initializing through a copy constructor is known as copy initialization.
13 (a) what are the three ways for achieving the conversion from one class type to another class type? Discuss (16)
When an object of one class is assigned to object of another class, it is necessary to give clear‐cut instructions to the
compiler. The method must be instructed to the compiler. There are two ways to convert object data type from one
class to another. One is to define a conversion operator function in source class or a one argument constructor in a
destination class. Consider the following.
X=A;
Here X is an object of class XYZ and A is an object of class ABC. The class ABC data type is converted to class XYZ. The
conversion happens from class ABC to XYZ. The ABC is a source class and XYZ is a destination class.
Ex:
#include<iostream.h.
#include<conio.h>
class minutes
{
int m;
public;
minutes()
{ m=240; }
get()
{ return (m); }
void show()
{
cout<<”minutes=”<<m;
}
};
class hours
{
int h;
public:
void operator=(minutes x);
void show()
{
cout<<”\n hours=”<<h;
};
void hours::operator=(minutes x)
{
h=x.get()/60;
}
int main();
{
clrscr();
minutes minute;
hours hour;
hour=minute;
minute.show();
hour.show();
return 0;
}
OUTPUT
Minutes = 240
Hours=4
Explanation:
In the above program, two classes are declared. The class minutes has one integer member variable m and two member
functions get () and show(). It also contains constructor without argument. The class hours has one integer member
variable and show () member function. The class hours contains overloaded operator function. In function main (),
minute is an object of class minutes and hours is an object of class hours. The program converts minutes to hours. The
equation hour=minute invokes the operator function. In function operator (), x is an object of class minutes. The object
x invokes the member function get () that returns total number of minutes. Number of hours is obtained by dividing the
total number of minutes by 60. The equation h=x.get()/60 performs this task and assigns result to h. Thus, the result of
the program is as per given above.
13(b)(i) write a program to find the sum of two numbers by overloading the ‘+’ operator (6)
#include<iostream.h>
#include<conio.h>
Class complex
{
Float x,y;
Public:
Complex() {}
Complex (float real, float imag)
{ x=real; y=imag;}
Complex operator +(complex);
Void display();
};
Complex complex::operator +(complex c)
{
Complex temp;
Temp.x=x+c.x;
Temp.y=y+c.y;
Return(temp);
Void complex::display()
{
Cout<<x<<”+”<<y<<”I”<<endl;
}
Void main()
{
Complex c1,c2,c3;
C1=complex(2.5,3.5);
C2=complex(1.6,2.7);
C3=c1+c2;
Cout<<”c3=”;
C3.display();
}
13 b)(ii) Explain the different types of inheritance with suitable examples (10)
Refer Nov‐Dec 2007 Q.No. 14 (b)
14 (a)(i) List the advantages of java in detail (8)
Java is a simple and compact language with simple syntactical structures.
It provides many safeguards which ensure that only reliable code is executed on the multiplatform
environment.
It handles all the mishandled error conditions by way of providing an object oriented exception handling
mechanism
Everything in java is treated as an object. All data and program code reside within classes and objects.
It is a secure language. It never allows unauthorized memory access by external program
It ensure automatic memory allocation and deallocation management
Its programs are portable. Java can be used to produce code that can run on a variety of CPUs under
differing environment.
Java support multithreading.
14 a) (ii) Write a program to find the sum of ‘n’ numbers and produce of ‘n’ numbers. Get the choice from the
user as a command line argument (8)
#include<iostream.h>
void main()
{
char yes;
int i,n,sum=0,product=1;
do
{
cout<<”enter the limit”;
cin>>n;
for (i=1;i<=n;i++)
{
sum=sum+i;
product=product*i;
}
cout<<”\nthe sum of “<<n<<” numbers”<<sum;
cout<<”\nthe product of “<<n<< “ numbers”<<product;
cout<<”\n do u want to continue say y/n”;
cin>>yes;
}while((yes==’y’)||(yes==’y’));
}
14 (b)(i) write about final variable, final method and final classes with suitable examples (10)
Final variable and final methods
All methods and variables can be overridden by default in subclasses. To prevent the subclasses from overriding the
members of the super class, they can be declared as final using the modifier as ‘final’.
Example:
final int SIZE=100;
Making a method final ensures that the functionality defined in this method will never be altered in any way. Similarly,
the value of a final variable can never be changed. Final variables, behave like class variables and they do not take any
space on individual objects of the class.
Final classes
Final classes are those classes which cannot be inherited, that is, a final class cannot be subclassed. If a class has to be
prevented from being inherited, the class can be declared as final.
Syntax
Final class classname{…..}
Example: this program would not compile as the class sub extends from class base declared as final.
final class base
{
base()
{system.out.println(“constructor of super class”);
}
void fun1()
{system.out.println(“function inside super class sis called”);
}
}
class sub extends base
{
sub()
{
system.out.println(“constructor of sub class”);
}
}
class finaldemo
{
public static void main(string args[])
{
sub s=new sub();
s.fun1();
}
}
14 b) (ii) write a program to find the area of a triangle , square, rectangle using method overloading (6)
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
class fn
{
public:
void area(int); //square
void area(int,int); //rectangle
void area(float ,int,int); //triangle
};
void fn::area(int a)
{
cout<<"Area of square:"<<a*a;
}
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";
cout<<"\n1.Area of square\n2.Area of Rectangle\n3.Area of Triangle\n4.Exit\n:”;
cout<<”Enter your Choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter side of the square:";
cin>>r;
obj.area(r);
break;
case 2:
cout<<"Enter Sides of the Rectangle:";
cin>>a>>b;
obj.area(a,b);
break;
case 3:
cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
obj.area(0.5,a,b);
break;
case 4:
exit(0);
}
getch();
}
15(a)(i) Explain with an example how multiple inheritance is achieved in java (10)
Refer Nov‐Dec 2012 Q.No. 15 (a)(i)
15 (a)(ii) How is synchronization of threads performed (6)
Data corruption may occur if the access to a method by many threads is not properly regulated by way of
synchronizing the access to such a shared method. The access to a method shall be synchronized by specifying the
synchronized keyword as a modifier in the method declaration. When a thread starts executing a synchronized instance
method, it automatically gets a logical lock on the object that contains the synchronized method. This lock will remain
as long as that thread is executing that synchronized method. When the lock is present, no other thread will be allowed
entry into that object.
The lock will be automatically released, when that thread completes the execution of that synchronized method.
Any other executable thread will be allowed entry into that locked object only when it does not have a lock. This is how
the JVM carefully coordinates the access to a common resource by multiple thread.
15 (b)(i) Explain the exception handling mechanism with an example (8)
Refer Nov‐Dec 2007 Q.No.13 (a)(ii)
15 (b)(ii)Explain the life cycle of an applet and write a simple applet to display a moving banner. (8)
The Applet class inherits the paint method from the Container class. The following methods to
implement in applets: init, start, paint, stop and destroy.
init()
The init() method is the first method to be called. This is where the user should initialize variables. This
method is called only once during the run time of the applet.
start()
The start() method is called after init(). It is also called to restart an applet after it has been stopped.
While init() is called once- the first time an applet is loaded – start() is called each time an applet’s
HTML document is displayed on screen. So if a user leaves a web page and come back, the applet
resumes execution at astart()
paint()
The paint() method is called each time the applet’s output must be redrawn. For example, the window in
which the applet is running may be overwritten by another window and then uncovered. The paint()
method has one parameter of type Graphics. This parameter will contain the graphics context, which
describes the graphics environment in which the applet is running. The context is used whenever the
output to the applet is required.
stop()
The stop() method os called when a web browser leaves the HTML document containing the applet and
goes to another page.
destroy()
The destroy method is called when the environment determines that the user’s applet needs to be
removed completely from memory. The stop() method is always called before destroy()
/* <applet code="movingBanner" height=50 width=300> </applet> */
import java.awt.*;
import java.applet.*;
publicvoid start(){
t = new Thread(this);
stopFlag=false;
t.start();
}
publicvoid run(){
for(;;){
try{
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1,msg.length());
msg = msg + ch;
if(stopFlag)
break;
}catch(InterruptedException e) {}
}
}
publicvoid stop(){
stopFlag=true;
t = null;
}
Part B (5 × 16 = 20 marks)
11. (a) (i) compare the features of object oriented programming languages
with procedure oriented programming languages
(ii) Explain how security of data is provided in object oriented
programming languages
(b) (i) What are base class and derived class? Give examples
#include <iostream>
using namespace std;
int main() {
float celsius;
float fahrenheit;
cout << "Enter Celsius temperature: ";
cin >> celsius;
fahrenheit = (5/9) * (celsius + 32);
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
}
PART B
11. (a) (i) compare the features of object oriented programming languages with procedure oriented
programming languages (8)
Object oriented programming as an approach that provides a way of modularizing program by creating
partitioned memory area for both data and functions that can be used as templates for creating copies of
such modules on demand.
OOP POP
1. Data in hidden and cannot be accessed by Data move openly around the system from
external functions. function to function
2. Programs are divided into what are known Large programs are divided into smaller programs
s objects. known as functions.
3. Emphasis on data rather than procedure Emphasis on doing things (algorithms)
4. Follow bottom‐up approach in program Follow top down in program design.
design
11 (a)(ii) Explain how security of data is provided in object oriented programming languages (8)
The following are the benefits of Object‐Oriented Programming over procedural programming language.
a) Using inheritance concepts, we can reuse the existing classes i.e. program code or data structure. In other words we
can eliminate the redundant code.
b) Data hiding mechanism helps us to build the secure programs that cannot be invaded by code in the other parts of
the program.
c) The data centered design approach helps to a quire more details of model in implementable form.
d) OOP’s can easily upgrade a small system to a large system with just a few modifications in the previous existing code
or data structure.
e) Message passing concepts for communication among objects makes the interface descriptions with external system
much simpler.
f) Using OOP concepts the time and space complexity can be reduced.
11 (b)(i) What are base class and derived class? Give examples (8)
The mechanism of deriving a new class from an old one called inheritance. The old class is referred to as the
base class and the new one is called the derived class or subclass.
A derived class can be defined by specifying its relationship with the base class in addition to its own details.
The general form of defining a derived class is:
Class derived‐class‐name : visibility base‐class‐name
{
…..
… members of derived class.
}
The colon indicates that the derived class name is derived from the base‐class name
The visibility mode is optional and if present may be either private or public. The default visibility mode is
private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived.
When a base class is privately inherited by a derived class ‘public members’ of the base class become ‘private
members’ of the derived class and therefore the public member of the base class can only be accessed by the
member functions of the derived class. The result is that no member of the base class is accessible to the
objects or the derived class.
When a base class is publicly inherited by a derived class
1. Public members of the base class become public member of the derived class.
2. Public members are accessible to the objects of the derived class.
The private members are not inherited and therefore, the private members of a base class will never become
the member of its derived class.
Example:
1. Class ABC:private XYZ
{ // members of ABC // private derivation
};
2. Class ABC:public XYZ
{ // members of ABC // public derivation
};
3. Class ABC: XYZ
{ // members of ABC // private derivation by default
};
11 (b)(ii) Explain data encapsulation with suitable example (8)
Encapsulation is the most fundamental concept of OOP. It is the way of combining both data and the
functions that operate on that data under a single unit. The data is not accessible to the outside world, and only
those functions which are wrapped in the class can access it.
Encapsulation is achieved through information hiding, which is the process of hiding all the secrets of an
object that do not contribute to its essential characteristics, the structure of an object is hidden, as well as the
implementation of its method.
Take a simple example.
Say Customer, waiter and kitchen are three objects. As we know customer and kitchen do not know each other in
general situation. The waiter is the intermediary between them. Objects can't see each other in an Object Oriented
world. The 'hatch' enables them to communicate and exchange coffee and money.
Encapsulation keeps computer systems flexible. The business process can change easily. The customer does not care
about the coffee making process. Even the waiter does not care. This allows the kitchen to be reconstructed, is only the
'hatch' remains the same. It is even possible to change the entire business process. Suppose the waiter will brew coffee
himself. The customer won't notice any difference even.
12 (a) State and explain the control structures used in C++ (16)
A computer program is a collection of statements. The statements in the program are executed one after the
other, in order in which they are given in the program. If we want to change the sequence in which these
statements are executed with the help of control statements.
The following control structures are discussed as follows
If statement
The general format is
If (expression is true)
{
Action1;
}
Action2;
Action3;
If the condition is true, then the statements are executed and the control is passed to the statement
immediately after the if statement. If the condition is false, control is passed directly to the statement following
the if statement.
Example
If (x>10)
Cout<<”x is greater than 10”;
If.. else statement
The general format is
If (expression is true)
{
Action1;
}
Else
{
Action2;
}
Action3;
If the condition is true, then Action1 part is executed. Otherwise Action2 part is executed.
Example
If(age>=18)
Cout<<”eligible to vote”;
Else
Cout<<”not eligible to vote”;
The switch statement
This is a multiple branching statement where, based on a condition, the control is transferred to one of
the many possible points. This is implemented as follows.
Switch(expression)
{
Case1:
{
Action1;
}
Case2:
{
Action2;
}
.
.
.
Default:
{
Action n;
}
}
.
.
.
The expression is evaluated and its values are matched against the values of the constants specified in
the case statements. When a match is found, the statement sequence associated with that case is executed
until the break statement or the end of switch statement is reached. The default statement gets executed when
no match is found. It is optional.
12 (b)(i) What are constructors and destructors? Explain with a suitable example (8)
Constructors:
A member function with the same name as its class is called constructor and is used to initialize the objects of
that class type with a legal initial value. When a constructor is declared for a class, initialization of the class objects
becomes mandatory.
Destructors
A destructor is the last member function ever called for an object. The destructor function is called
automatically when a class object goes out of scope. the general form of a destructor function is
~ Class_name();
Where class_name is the name of the destructor (which is same as the name of the constructor i.e., the name of the
class) and is preceded by the tilde (~) sysmbol. For example,
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
private:
int age;
char name[25];
public:
student(int a, char n[25])
{
age=a;
strcpy(name,n);
}
void show()
{
cout<<"\nThe name of the student is: "<<name;
cout<<"\nHis age is: "<<age;
}
~student() //destructor defined
{
cout<<"\nObject Destroyed";
}
};
int main()
{
student s1(21,"Rahul");
student s2(23,"Dipankar");
clrscr();
s1.show();
s2.show();
return 0;
}
12 (b)(ii) Write a program in C++ to find the prime numbers between 1 and 1000. (8)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int lim;
int isPrime;
for(int x=2;x<1000;x++)
{
lim=(int) sqrt(x+1);
isPrime=1;
for(int y=2;y<=lim;y++){
if(x%y==0){
isPrime=0;
break;
}
}
if(isPrime)
cout << x << " ";
}
return 0;
}
13 (a)(i) Explain the use of static members with an example (8)
Refer Nov_Dec 2009 Q.No. 12 (b)(i)
13 (a)(ii) Define friend class and friend function. Explain each with examples (8)
Refer Nov-Dec 2008 Q.No. 12 (a)(i)
13 (b) Explain operator overloading with complex numbers addition as an example (16)
Operator overloading provides a flexible option for the creation of new definitions for most of the c++
operators. The mechanism of giving special meanings to an operator is known as operator overloading
Example
#include<iostream.h>
#include<conio.h>
Class complex
{
Float x,y;
Public:
Complex() {}
Complex (float real, float imag)
{ x=real; y=imag;}
Complex operator +(complex);
Void display();
};
Complex complex::operator +(complex c)
{
Complex temp;
Temp.x=x+c.x;
Temp.y=y+c.y;
Return(temp);
Void complex::display()
{
Cout<<x<<”+”<<y<<”I”<<endl;
}
Void main()
{
Complex c1,c2,c3;
C1=complex(2.5,3.5);
C2=complex(1.6,2.7);
C3=c1+c2;
Cout<<”c3=”;
C3.display();
}
14(b) Define inheritance. Explain the different types of inheritance with suitable examples (16)
Refer Nov-Dec 2007 Q.No.14 (b)
15 (a) Explain the features of c++ that are helpful to develop an object oriented system (16)
Refer Nov-Dec 2012 Q.No. 11 (a)(i)
15(b) Write a program in c++ to record electric readings and compute the electricity bill. Use object oriented
programming concepts (16)
Refer Nov-Dec 2007 Q.No. 15(a)
B.E./B.Tech. DEGREE EXAMINATION,
NOV/DEC 2008
Fifth Semester
Electrical and Electronics Engineering
OBJECT ORIENTED PROGRAMMING
Time : Three hours Maximum : 100 marks
Answer ALL questions.
PART A (10 × 2 = 20 marks)
1. Differentiate explicit and implicit type casting
3. Define static data members. Give example for static members and array
of objects.
Part B (5 × 16 = 20 marks)
12. (a) Explain friend function, passing and returning objects with
example program
(b) Explain parameterized constructor and constructor overloading
with example program
13. (a) Write a C++ program to implement complex number addition,
subtraction and multiplication using binary operator overloading
(b) Explain hybrid inheritance and virtual classes/ members with
example programs.
14 (a) Explain constants, variables and operators in java. Write a
simple java program to concatenate two strings.
(b) Explain array declaration, initialization and use in java. Write a
java program to implement matrix multiplication.
15 (a) Explain multithreading with example program by extending
thread class.
(b) Explain java applet programming with example.
Nov-Dec 2008
PART A
3. Define static data members. Give example for static members and array of objects.
A data member of access can be qualified as static. It is initialized to zero, when the first
object of its class is created. No other initialization is permitted. It is visible only within
the class but life time is entire program
Ex: class emp
{
static int count;
char name[30];
public;
void getdata(void);
void putdata(void);
};
. Member operator
11(b) Explain function prototyping and function overloading with example programs
Function prototype
A function prototype is a declaration of the function that tells the program about the type
of value returned by the function and the number and type of arguments. A function is
called by providing the function name, followed by the parameters enclosed in braces.
General form
function name(argument list)
Example
int sum (int n1,n2)
Function overloading
A function name having several definitions that are differentiable by the number or type
of their argument is known as function overloading. The function would perform
different operations depending on the argument list in the function call.
Example:
#include <iostream>
int volume(int);
double vlolume(double, int);
int main()
{
cout<<volume(10);
cout<<”\n”<<volume(2.5,8);
return 0;
}
int volume(int s)
{
return(s*s*s);
}
double volume(double r, int h)
{
return(3.14*r*r*h);
}
12 a) Explain friend function, passing and returning objects with example program
Friend function
Private members cannot access from outside the class. i.e., a non member function cannot have an
access to the private data of a class. C++ allows the common function to be made friendly with 2 classes,
thereby allowing the function to have access to the private data of these 2 classes. A common function
need not be a member of any of these classes. The general format is
class class name
{
‐‐‐‐‐
…..
….
Public:
…..
…….
…..
friend return type function name (arguments);
};
The function declaration should be preceded by the keyword friend.
The function is anywhere in the program
The function definition does not use either the keyword friend or the scope operator ::
A function can be declared as a friend in any number of classes
It has full access rights to the private members of the class.
Example
#include<iostream.h>
class sample
{
int a,b;
public:
void setvalue()
{
a=25;
b=40;
}
friend float mean (sample s);
};
float mean(sample s1)
{
return float(s1.a+s1.b)/2;
}
void main()
{
sample x;
x.setvalu();
cout<<mean(x);
}
12(b) Explain parameterized constructor and constructor overloading with example program
PARAMETERIZED CONSTRUCTORS
DEFINION: “The constructor that can take arguments are called parameterized constructor”.
It allows us to initialize the various data elements of different objects with
different values when they are created.
The initial values must be passed at the time of object creation. It can be done in
2 ways.
1. By calling the constructor implicitly.
2. By calling the constructor explicitly.
By implicit call, that the constructor is called even when its name has not been mentioned in the
statement.
Example: ABC object 1 ( 13,11,’p’);
By explicit call that name of he constructor is explicitly provided.
Example: ABC object 1 = ABC ( 13,11,’p’);
CONSTRUCTOR OVERLOADING
Just like function, the constructor of a class may also be overloaded (i.e.,) more than one constructor
defined in the class.
Example
#include<iostream.h>
class complex
{
float x,y;
public:
complex(){
complex(float a)
{x=y=a;}
complex (float real,float imag)
{
x=real;
y=imag;
}
friend complex sum(complex,complex);
friend void show(complex);
};
Output
A=2.7+3.5i
B=1.6+1.6i
C=4.3+5.1i
13 (a) Write a C++ program to implement complex number addition, subtraction and multiplication
using binary operator overloading
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b;
public:
void read()
{
cout<<"\n\nEnter the REAL PART : ";
cin>>a;
cout<<"\n\nEnter the IMAGINARY PART : ";
cin>>b;
}
complex operator +(complex c2)
{
complex c3;
c3.a=a+c2.a;
c3.b=b+c2.b;
return c3;
}
complex operator -(complex c2)
{
complex c3;
c3.a=a-c2.a;
c3.b=b-c2.b;
return c3;
}
complex operator *(complex c2)
{
complex c3;
c3.a=(a*c2.a)-(b*c2.b);
c3.b=(b*c2.a)+(a*c2.b);
return c3;
}
void display()
{
cout<<a<<"+"<<b<<"i";
}
};
void main()
{
complex c1,c2,c3;
int choice;
clrscr();
cout<<"\t\tCOMPLEX NUMBERS\n\n1.ADDITION\n\n2.SUBTRACTION\n\n”:
cout<<”3.MULTIPLICATION\n\n";
cout<<"\n\nEnter your choice : ";
cin>>choice;
if(choice==1||choice==2||choice==3)
{
cout<<"\n\nEnter the First Complex Number";
c1.read();
cout<<"\n\nEnter the Second Complex Number";
c2.read();
}
switch(choice)
{
case 1 : c3=c1+c2;
cout<<"\n\nSUM = ";
c3.display();
break;
case 2 : c3=c1-c2;
cout<<"\n\nSUBTRACTION = ";
c3.display();
break;
case 3 : c3=c1*c2;
cout<<"\n\nPRODUCT = ";
c3.display();
break;
default : cout<<"\n\nUndefined Choice";
}
getch();
}
13(b) Explain hybrid inheritance and virtual classes/ members with example programs.
“Hybrid Inheritance" is a method where one or more types of inheritance are combined together and
used. Example as follows:
#include <iostream.h>
class mm
{
protected:
int rollno;
public:
void get_num(int a)
{ rollno = a; }
void put_num()
{ cout << "Roll Number Is:"<< rollno << "\n"; }
};
class marks : public mm
{
protected:
int sub1;
int sub2;
public:
void get_marks(int x,int y)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
}
};
class extra
{
protected:
float e;
public:
void get_extra(float s)
{e=s;}
void put_extra(void)
{ cout << "Extra Score::" << e << "\n";}
};
In the above example the derived class "res" uses the function "put_num()". Here the "put_num()"
function is derived first to class "marks". Then it is deriived and used in class "res". This is an example of
"multilevel inheritance‐OOP's concept". But the class "extra" is inherited a single time in the class "res",
an example for "Single Inheritance". Since this code uses both "multilevel" and "single" inheritence it is
an example of "Hybrid Inheritance".
virtual classes/ members
A member of a class that can be redefined in its derived classes is known as a virtual member. In order
to declare a member of a class as virtual, we must precede its declaration with the keyword virtual: They
allow dynamic binding of member functions. Because all virtual functions must be member functions,
virtual member functions are simply called virtual functions.
class A
{
....
....
};
class B1 : virtual public A
{
....
....
};
class B2 : virtual public A
{
....
....
};
class C : public B1, public B2
{
.... // only one copy of A
.... // will be inherited
};
14(a) Explain constants, variables and operators in java. Write a simple java program to concatenate
two strings.
Constant:
A constant (also known as literal) is any data that cannot be changed. Five major types of constants
available in java are as follows.
integer, floating point, character, string, Boolean
Ex: 13.5 – float constant
true – Boolean constant
Variables:
A variable refers to a memory location that holds a piece of data. This data is retrieved by calling the
variable name. A variable name generally follows certain rules.
Some valid variable names are
Operators
A symbol that represents an operation, such as multiplication or division, is called an operator. Some of
the well known operators available in java are as follows.
Simple java program to concatenate two strings.
class concat{
public static void main(String args[])
{
String s1,s2,s3;
s1="Alex ";
s2="is a super hero";
//concatenation of string objects
s3=s1+s2;
System.out.println(s3);
//concatenation of Strings
System.out.println("Super Hero "+"Always Favorites");
}
}
Output Should Be:
Alex is a super hero
Super Hero Always Favorites
14(b) Explain array declaration, initialization and use in java. Write a java program to implement matrix
multiplication.
Array declaration:
An array is a group of variables of the same type. These variables are grouped together under a
common name. Each individual variable is called as an Array Element and is numbered as 0,1,2 and so
on. These numbers are called the subscript. An array element is referred to by the common name and
its subscript (enclosed within square brackets []).
The array num has a single subscript‐it is known as one‐dimensional array. Arrays can also have
more than one subscript. Such arrays are called multi‐dimensional arrays. The general form is:
Type array_name[];
array_name=new type[size];
Here type array_name[]; declared the array by specifying its type and name.
array_name=new type[size]; specifies the size of the array and allots space for them.
For example,
int num[];
num=new int[5];
declares an integer array of 5 elements. it means that five integers can be stored in that array.
These numbers would be referred to as
Num[0] Num[1] Num[2] Num[3] Num[4]
Where num is the array name and 0, 1, 2, 3 and 4 are the subscripts. Each of these array
elements is exactly like an integer variable and can store one integer value. The only difference is that
array element is allotted consecutive memory location.
Array initialization
Arrays can be initialized when they are declared. An array initialize is a list of comma separated
expressions surrounded by curly braces. The commas separate the values of the array elements. The
array will automatically be created large enough to hold the number of elements specified in the array
initialize.
Example
int number[]={31,28,341,305};
Java program to implement matrix multiplication.
import java.lang.*;
import java.io.*;
class arraymul
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter no of rows");
int m=Integer.parseInt(br.readLine());
System.out.print("enter no of columns");
int n=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
int i,j,k;
{
for( i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.print("enter no of rows");
int p=Integer.parseInt(br.readLine());
System.out.print("enter no of columns");
int q=Integer.parseInt(br.readLine());
int b[][]=new int[p][q];
{
for( i=0;i<p;i++)
{
for( j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
}
int c[][]=new int[m][i];
if(n==p)
{
for( i=0;i<m;i++)
{
for( j=0;j<q;j++)
{
c[i][j]=0;
for( k=0;k<p;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.println(c[i][j]);
}
}
}
}
} }
15 (a) Explain multithreading with example program by extending thread class.
Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at
the same time and parallel). In such cases, each part is called a thread. So a multithreaded program is
one in which there are two or more threads, each of which is performing a different action. It allows a
process to run its tasks in parallel mode on a single processor system
Threads are used in java by
a. extending the Thread class
b. implementing the Runnable interface
The following is the example to extend the Thread class:
public class MyThread extends Thread
{
String messsage;
MyThread(String msg)
{
message=msg;
}
public void run()
{
for(int count=0;count<=5;count++)
{
System.out.println("Run method: " + message);
}
}
}
The line public class MyThread extends Thread’ indicates he class header.
Every thread functionality need to be implemented in the run() method.
The thread is to display the ‘counter’ value for 5 times.
The following code creates the MyThread object and invokes the run() method in it.
public class MainMyThread
{
public static void main(String[] args)
{
MyThread dt1=new MyThread("Run");
MyThread dt2=new MyThread("Thread");
dt1.start(); // this will start thread of object 1
dt2.start(); // this will start thread of object 2
}
}
The start() method of both the threads invokes the run() method of MyThread class.
Similar to the above, the run() method can be implemented by implementing Runnable interface.
15(b) Explain java applet programming with example.
A java applet is a java program that can be executed by a web browser. The browser has an inbuilt JVM
that helps in executing these applets. The applets can also be executed tested using a utility available as
part of JDK – the applet viewer.
Following example demonstrates how to create a basic Applet by extending Applet Class. we will need
to embed another HTML code to run this program.
iImport java. applet.*;
import java.awt.*;
public class Main extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}
Now compile the above code and call the generated class in your HTML code as follows:<HTML>
<HEAD>
</HEAD>
<BODY>
<div >
<APPLET CODE="Main.class" WIDTH="800" HEIGHT="500">
</APPLET>
</div>
</BODY>
</HTML>
Result:
The above code sample will produce the following result in a java enabled web browser.
Welcome in Java Applet.
B.E./B.Tech. DEGREE EXAMINATION,
NOV/DEC 2007
Fifth Semester
Electrical and Electronics Engineering
OBJECT ORIENTED PROGRAMMING
Time : Three hours Maximum : 100 marks
Answer ALL questions.
PART A (10 × 2 = 20 marks)
1. What are the unique advantages of an object oriented programming
paradigm?
2. What is a class? How class and the instance of the class are created?
Part B (5 × 16 = 20 marks)
PART A
1. What are the unique advantages of an object oriented programming paradigm?
Object oriented programming supports all of object based programming features along with 2
additional features namely inheritance and dynamic binding.
2. What is a class? How class and the instance of the class are created?
A group of objects that share common properties and relationships. Once a class has been
declared, we can create variable of that type by using the class name.
Class name list of objects;
example : item x,y,z
objects can also be created when a class is defined by placing their names immediately after the
closing brace.
Example:
class item
{
…….
……..
} x,y,z
3. What is a Abstract data type? How it differ from class?
An abstraction that describes a set of objects interms of an encapsulated or hidden data and
operations on that data. when defining a class, we are creating a new abstract data type that
can be treated like any other built‐in data type.
4. What are inline functions? Give an example.
Function execution involves the overhead of jumping to and from the calling statement. The
execution time is considerably large whenever a function is small, in such cases inline functions
can be used.
Example:
Inline float square (float)
{
X=x*x;
Return (x);
}
5. What is a constructor? Is it mandatory to use constructors in a class?
A member function with the same name as its class is called constructor and is used to initialize
the objects of that class type with a legal initial value. When a constructor is declared for a
class, initialization of the class objects becomes mandatory.
6. Define friend function with its rules.
A function declared as a friend is not in the scope of the class in which it has been declared as
friend.
Rules
1. The function declaration should be preceded by keyword Friend
2. The function definition does not use either the keyword friend or scope operator.
3. It can be declared as a friend in any number of classes.
4. It has full access rights to private members of class.
7. What is function overloading? List out its advantages.
A function name having several definitions that are differentiable by the number or type of their
arguments is known as overloaded function and their process is known as function overloading
Advantages
1. Overloaded functions are extensively used for handling class objects.
2. Sometimes, the default arguments may be used instead of overloading. This may reduce
the number of functions to be defined.
8. What is a Hierarchy inheritance? Give an example.
When many subclasses inherit from c++ single base class. It is used to support hierarchical
design of the program.
Example: hierarchical classification of student
Student
Arts engineering medical
ECE CSE IT
9. What is a operator function? Give an example
To define an additional task to an operator, we must specify what it means in relation to the
class to which the operator is applied. This is done with the help of special function called
operator function.
Example
Vector operator +(vector) // addition
Int operator ==(vector) // comparison
10. What is dynamic binding?
The addresses of the functions are determined at run time rather than compile time.
PART B
11 (a) Explain the various important paradigm of object oriented Programming with an programming
example. (16)
Paradigm means organizing principles of a program. It is an approach to programming.
MONOLITHIC PROGRAMMING
Monolithic programming consists of only global data and sequential code.
Program flow control is achieved through the use of jumps and the program code is duplicated
each time it is to be used.
No support of the subroutine concept.
It is suitable for developing small and simple applications.
No support for data abstraction.
It is difficult to maintain or enhance the program code.
Examples: 1. Assembly language.
2. BASIC
PROCEDURAL PROGRAMMING
Programs organized in the form of subroutine and all data items are global.
Program controls are through jumps and call to subroutines.
Subroutines are abstract to avoid repetitions.
Suitable for medium sized software applications
Difficult to maintain and enhance the program code.
EXAMPLES: 1. FORTRAN
2. COBAL
STRUCTURED PROGRAMMING
Program consists of multiple modules and in turn each module has a set of functions of related
types.
Programs are divided into individual procedures that perform different tasks.
Procedures are independent of each other.
Procedures have their own local data and processing logic.
Parameter passing facility between the procedures for information communication.
Controlled scope of data.
Introduction of the concepts of user defined data types.
Support for modular programming.
Projects can be broken up into modules and programmed independently
Maintenance of a large system is tedious and costly.
Examples: 1. Pascal
2. C
OBJECT ORIENTED PROGRAMMING
OOP Is an approach that provides a way of modularizing programs by creating
partitioned memory area for both data and functions that can be used as templates for creating
copies of such modules on demand.
OOP treats data as a critical element in the program development and does not allow it
to flow freely around the system. It ties data closely to the functions that operate on it and
protects it from accidental modification from outside functions.
It allows decomposition of a problem into a number of entities called objects and then
builds data and functions around these objects. The data of an object can be accessed only by
the functions associated with the object.
Features
Emphasis is on data rather than procedure
Improvement over the structured programming paradigm.
Data structures are designed such that they characterize the object.
Functions that operate on the data of an object are tied together in the data structure.
Data is hidden that cannot be accessed by external functions.
Object may communicate with each other through functions.
New data and functions scan be added easily.
Follow bottom up approach in program design.
11(b) Write a program to create a class “STUDENT” with data members Rollo, Name, Course, Branch,
and Semester. Store them in an array of objects. Input the total number if students and perform the
following:
(I) Stored List of students in the ascending order of name.
(ii) Branch wise student list.
#include<iostream.h>
#include<stdio.h>
class student
{
char name[10][8],temp[10],course[10][8],branch[15][8];
inti,j,roll‐no,semester;
public:
void getdata();
void putdata();
};
void student :: getdata()
{
cout<<"Enter the name : " ;cin>>name;
cout<<"Enter the roll no. :" ;cin>>roll_no;
cout<<"Enter the course : "; cin>>course;
cout<<"Enter the branch : "; cin>>branch;
cout<<"Enter the semester : "; cin>>semester;
}
void student :: putdata()
{
cout<<"Name of the student : "<<name;
cout<<"\n Roll no. : "<<roll_no;
cout<<"\nCourse : "<<course;
cout<<"\nBranch : "<<branch;
cout<<"\nSemester: "<<semester;
}
void main()
{
int i;
clrscr();
student std[5];
for(i=0;i<5;i++)
{
cout<<"\n \t\tDetails of the student"<<i+1<<"\n";
std[i].getdata();
}
for (i = 0; i <5 - 1 ; i++)
{
for (j = i + 1; j <5; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
cout<<”sorted list of students in the ascending order of names”;
for(i=0;i<5;i++)
{
std[i].putdata();
}
for (i = 0; i <5 - 1 ; i++)
{
for (j = i + 1; j <5; j++)
{
if (strcmp(branch[i], branch[j]) > 0)
{
strcpy(temp, branch[i]);
strcpy(branch[i], branch[j]);
strcpy(branch[j], temp);
}
}
}
cout<<”\n2. Branch wise student list”;
for(i=0;i<5;i++)
{
std[i].putdata();
}
getch();
}
12 (a) What is friend class? Create a two classes ABC and XYZ which stores the values of distances. ABC
stores distances in meters and centimeters and XYZ in feet and inches. Write a program that can read
values for the class objects and add one object ABC with another object of XYZ. Use a friend function to
carry out the addition operation. The display should be in the format of feet and inches or meters and
centimeters depending on the object on display. (16)
#include <iostream.h>
#include <conio.h>
Class xyz;
Class abc
{
float mt;
int cm;
public:
void getdata(void);
void display(void);
friend abc add(abc,xyz);
};
Class xyz
{
int feet;
float inches;
public:
void getdata(void);
void display(void);
friend abc add(abc,xyz);
};
Void abc :: getdata(void)
{
clrscr();
cout<<"\t\tDM GETDATA FUNCTION\n\n";
cout<<"\n\nEnter Values for metres :-";
cin>>mt;
cout<<"Enter Values for centimetres:-";
cin>>cm;
}
Void abc :: display(void)
{
cout<<"\n\nThe value of distance in metres is "<<mt;
cout<<"\nThe value of distance in Centimetres is "<<cm;
}
Void xyz :: getdata(void)
{
clrscr();
cout<<"\t\tDB GETDATA FUNCTION\n\n";
cout<<"\n\nEnter Values for feet :-";
cin>>feet;
cout<<"Enter Values for inches :-";
cin>>inches;
}
Void xyz :: display(void)
{
cout<<"\n\nThe value of distance in feet is "<<feet;
cout<<"\nThe value of distance in inches is "<<inches;
}
abc add(abca,xyz b)
{
abc temp;
temp.cm=a.cm+(b.feet*30)+((b.inches*30)/12.0);
temp.mt=a.mt+(temp.cm % 100);
temp.cm=temp.cm-((temp.cm % 100)*100);
return(temp);
}
void main()
{
abc a;
a.getdata();
xyz b;
b.getdata();
clrscr();
cout<<"\n\t\tAFTER CONVERSION AND THEIR ADDITION IS PERFORMED\n";
abc extra;
extra=add(a,b);
extra.display();
getch();
}
12(b)(i) Explain the various types of constructor with an programming example. (10)
PARAMETERIZED CONSTRUCTORS
DEFINION: “The constructor that can take arguments are called parameterized constructor”.
It allows us to initialize the various data elements of different objects with different
values when they are created.
The initial values must be passed at the time of object creation. It can be done in 2
ways.
1. By calling the constructor implicitly.
2. By calling the constructor explicitly.
By implicit call, that the constructor is called even when its name has not been mentioned in the
statement.
Example: ABC object 1 ( 13,11,’p’);
By explicit call that name of he constructor is explicitly provided.
Example: ABC object 1 = ABC ( 13,11,’p’);
DEFAULT CONSTRUCTORS
Definition: “A constructor that accepts no parameter is called the default constructor”.
If a class has no explicit constructor defined, the complier will supply a default
constructor.
The defaults constructor provided by the complier does not do anything specific. It
simply allocates memory to data members of object.
A constructor with default arguments is equivalent to default constructor.
Example:
Class A
{ int i;
float j;
public
A (int a=0, float b=1000.0);
}; //proto type declaration with default arguments other members
A :: A(int a, float b)
{
I=a;
J=b;
}
Void main()
{ A 01(23,2715.50) // Argument values passed for
A 02; // Take default argument values
‐‐‐‐‐‐
‐‐‐‐‐
‐‐‐‐‐‐
}
COPY CONSTRUCTOR
A constructor can accept a reference to its own class as a parameter is called the copy
constructor.
A copy constructor is a constructor of the form class name (class name &)
The compiler will use the copy constructor whenever you initialize an instance using values of
another instance of same type.
Example;
Sample S1; // default constructor
Sample S2=S1; // copy constructor
A copy constructor takes reference to an object of the same classs an argument.
Example:
Class sample
{ int I,j;
Public:
Sample (int a, int b) // constructor
Sample (sample &s) // copy constructor
{ j=s.j;
I=s.i;
}
};
Sample S1(4,6); // S1 initialized
Sample S2(s1); // S1 copied to S2 copy constructor called.
Sample S3=S1; // S1 copied to S3
Copy constructor is used to declare and initialize an object from another object.
Example: integer I2 (I1);
It defines the objects I2 and at the same time initializes it to the value of I1.
The process of initializing through a copy constructor is known as copy initialization.
DYNAMIC CONSTRUCTORS
Allocation of memory to objects at the time of their construction is known as dynamic
construction of objects.
The memory is allocated with the help of the new operator.
Class string
{
‐‐‐
‐‐‐
‐‐‐‐‐
Public:
String()
{
Length=0;
Name=new char [length+1];
}
};
Dynamic initialization of objects
The dynamic initialization means that the initial values may be provided during run time. Every class
objects can be initialized dynamically.
Example:
Class sample
{ in roll no;}
Float marks;
Public
Sample ( int a, float b)
{ roll no = a; marks = b;}
…..
…..
….
};
void main
{ int x; float y;
Cout<<”Enter roll no & mark of the student”<<endl;
Cin..x..y;
Sample S1(x,y)
….
…..
….
}
CONSTRUCTOR OVERLOADING
Just like function, the constructor of a class may also be overloaded (i.e.,) more than one constructor
defined in the class.
#include<iostream.h>
Class complex
{
Float x,y;
Public:
Complex(){
Complex(float a)
{x=y=a;}
Complex (float real,float imag)
{
X=real;
Y=imag;
}
Friend complex sum(complex,complex);
Friend void show(complex);
};
Output
A=2.7+3.5i
B=1.6+1.6i
C=4.3+5.1i
12(b)(ii) Describe the concept of Destructor function with an programming example. (6)
A destructor is the last member function ever called for an object. The destructor function is called
automatically when a class object goes out of scope. the general form of a destructor function is
~ Class_name();
Where class_name is the name of the destructor (which is same as the name of the constructor i.e., the
name of the class) and is preceded by the tilde (~) sysmbol. For example,
Class destruct
{
Private:
Int sign;
………
……..
Public:
destruct() // constructor
{
Sign=0;
}
~ destruct() //destructor
{ }
….
…..
};
A destructor is normally used for releasing dynamically allocated memory that was previously allocated
for an object by the constructor. Like constructors, destructors do not have a return value. Although
the system provides a default destructor, it is considered as a good programming practice to define a
destructor before the end of each class definition. A destructor doesn’t receive arguments and hence it
cannot be overloaded. Each class can have only one destructor strictly.
13 (a)(i) Describe the concept of Pass by reference and Call by value with an programming example.
PASS BY REFERENCE
A function can also return a reference. Consider the following function:
Int & max ( int &x,int &y)
{
if (x > y)
return x;
else
retrun y;
}
Since the return type of max () is int&, the function returns reference to x or y ( and not the valuie).
Then a function call such as max (a,b) will yield a reference to either a or b depending on their values.
This means that this function call can apper on the left‐hand side of an assignment statement. This is,
the statement
Max(a,b) = ‐1;
is legal and assigns‐1 to a if it is larger, otherwise‐1 to b.
CALL BY VALUE
A function passes an arguments by value. The called function creates a new set of variables and copies
the values of arguments in to them.
Example:
Int main()
{
int cube(int);
int vol,side=9;
….
…
Vol=cube(side);
Cout<<vol;
Return 0;
}
Int cube(int a)
{
Return (a*a*a);
}
Advantages
Expressions can be passed as arguments.
Unwanted changes to the variables in the calling function can be avoided.
Disadvantages
Information cannot be passed back from the calling function to the called function through
arguments.
13(a)(ii) Explain the concept of exception handing in c++ with an example (8)
The exception handing mechanism uses 3 blocks try, throw and catch.
Try
Exception handing mechanism transfers control and information from a point of
execution in a program to an exception handler associated with the try block
When the try block throws an exception, the program control leaves the try block and
enters the catch statement of the catch block.
The syntax for try construct is
Try
{ // code raising exception or referring to a function raising exception
}
Catch (type arg)
{ // action for handling exception
}
The try keyword defines a boundary within which an exception can occur.
It contains a block of code enclosed within braces.
It indicates that the program is prepared for testing the existence of exceptions.
If an exception occurs, the program flow is interrupted.
Throw
When an exception is detected it is thrown using a throw statement in the try block
The syntax of the throw construct is
Throw T;
The keyboard throw is used to raise an exception when an error is generated in the
computation.
It initializes a temporary object of the type T
Catch
A catch block defined by the keyboard catch ‘catches’ the exception ‘thrown’ by the
throw statement in the try block and handles it appropriately.
It immediately follows the try block.
An exception is said to be caught when its type matches the type in the catch statement.
The syntax of catch construct is
Catch(T)
{ // actins for handling an exception
}
Example
#include<iostream.h>
Int main()
{ int a,b;
Cout<<”Enter values a and b”;
Cin>>a>>b;
Int x=a‐b;
Try
{ if (x!=0)
{ cout<<”result(a/x)=”<<a/x;
}
Else // there is an exception
{ throw(x); //throws int object
}
}
Catch (int i)
{ cout<<”exception caught:x=”<<x;
}
Cout<<”end”;
Return o;
}
Output
Enter values of a and b
20 15
Result (a/x)=4
End
Program detects and catches a division by zero problem.
13(b) what is a template function? Design and implement a template version function Min() and Max()
for finding the minimum and maximum values of given set of elements of list T represented by a seqList
<T> object. (16)
Template function
A function template specifies how an individual function can be constructed.
Program
template<class T >// or template<typename T >
T maximum( T value1, T value2, T value3 )
{
T maximumValue = value1; // assume value 1 is maximum
if ( value2 >maximumValue )
maximumValue = value2;
if ( value3 >maximumValue )
maximumValue = value3;
returnmaximumValue;
}
#include <iostream>
usingnamespacestd;
#include "maximum.h"
int main()
{
int int1, int2, int3;
cout<< "Input three integer values: ";
cin>> int1 >> int2 >> int3;
cout<< "The maximum integer value is: "
<< maximum( int1, int2, int3 );
double double1, double2, double3;
cout<< "\n\nInput three double values: ";
cin>> double1 >> double2 >> double3;
cout<< "The maximum double value is: "
<< maximum( double1, double2, double3 );
char char1, char2, char3;
cout<< "\n\nInput three characters: ";
cin>> char1, char2, char3;
cout<< "The maximum character value is: "
<< maximum( char1, char2, char3 ) <<endl;
system("pause");
return 0;
}
14(a) Write a program to overload unary operator for processing counters. It should support both
upward counting and downward counting. It must also support operator for adding to counters and
storing the result in another counter. (16)
#include<iostream.h>
#include<conio.h>
class counter
{
int count;
public:
counter()
{
count=0;
}
intget_count()
{
return count;
}
void operator++()
{
count++;
}
};
void main()
{
counter c1,c2;
cout<<"\nC1 ="<<c1.get_count();
cout<<"\nC2 ="<<c2.get_count();
14(b) Explain the various types of inheritance with an programming example for each type. (16)
Inheritance is the process of creating new classes from existing classes. While deriving new
classes from existing classes, the access specifier take the control over the data members and the
member function present in the base classes. The access specifier, specified before the base class name
indicates whether the feature of the base class are privately derived, protectedly derived or publicly
derived.
Depending upon the use of access specifiers, inheritance may be classified as,
Private inheritance
Protected inheritance
Public inheritance
Private inheritance
If private access type is specified in a class (or if no access type is specified) then a private
derivation is assumed. For example
Class student : private teacher // private derivation
{
. . .
. . . body of the derived class
}
or
class student : teacher // private derivation by default
{
. . .
. . . body of the derived class
}
Denotes the same.
When a base class is inherited by using the private access specifier,
The private members inherited from the base class are inaccessible to the member functions of
the derived class. They remain private in the base class and are visible only in the base class.
The protected members inherited from the base class become private members of the derived
class, and hence they can be accessed either by member functions or by friend functions of the
derived class. They are inaccessible to the objects of the derived class.
The public members inherited from the base class become private members of the derived class
and therefore the public members of the base class can only be accessed by the member
functions of the derived class. They are inaccessible to the objects of the derived class. If
another private derivation occurs from this derived class, the public members of the base class
become inaccessible to the member functions of the new derived class.
Protected inheritance
If protected access type is specified in a class then a protected derivation is assumed. This type
of deriving a base class is uncommon and it is rarely done. For example,
Class student : protected teacher //protected derivation
{
……
……
…. Body of the derived class
}
When a base class is inherited by using the protected access specifier.
The private members inherited from the base class are inaccessible to the member
functions of the derived class. They are inaccessible to the objects of derived class.
The protected members inherited from the base class also become protected members
of the derived class. They can be accessed by the member or friend functions of the
derived class, and are accessible to the objects of derived class.
The public members inherited from the base class also become protected members of
the derived class. They can be accessed by the member function or friend functions of
the derived class, but they are accessible to the objects of derived class.
Public inheritance
If public access type is specified in a class, then a public derivation is assusmed. Public
derivation is more common than private and protected type of derivations. For example,
Class student : public teacher //public derivation
{
……
……
…. Body of the derived class
}
When a base class is inherited by using the public access specifier.
The private members inherited from the base class are inaccessible to the member
functions of the derived class. They are inaccessible to the objects of derived class.
The protected members inherited from the base class also become protected members
of the derived class. They can be accessed by the member or friend functions of the
derived class.
The public members inherited from the base class also become public
members of the derived class. They can be accessed by the member function or friend
functions, as well as the objects of the derived class using the member access operator.
Example
//program to understand private, protected and public inheritance
//access.cpp
#include<iostream.h>
Class master
{
Private :
Int a;
Protected:
Int b;
Public:
Int c;
};
Class slavel:private master // private inheritance
{
Public:
Void assigndata_to_private_member()
{
a=5; // error. Private members inherited from the base class are inaccessible to the members
//functions of the derived class
}
Void assigndata_to_protected_member()
{
b=5; // Protected members inherited from the base class are inaccessible to the members
//functions of the derived class
}
Void assigndata_to_public_member()
{
c=5; // Public members inherited from the base class are inaccessible to the members
//functions of the derived class
}
};
Class slavel:protected master // protected inheritance
{
Public:
Void assigndata_to_private_member()
{
a=5; // error. Private members inherited from the base class are inaccessible to the members
//functions of the derived class
}
Void assigndata_to_protected_member()
{
b=5; // Protected members inherited from the base class are inaccessible to the members
//functions of the derived class
}
Void assigndata_to_public_member()
{
c=5; // Public members inherited from the base class are inaccessible to the members
//functions of the derived class
}
};
Class slavel:private master //public inheritance
{
Public:
Void assigndata_to_private_member()
{
a=5; // error. Private members inherited from the base class are inaccessible to the members
//functions of the derived class
}
Void assigndata_to_protected_member()
{
b=5; // Protected members inherited from the base class are inaccessible to the members
//functions of the derived class
}
Void assigndata_to_public_member()
{
c=5; // Public members inherited from the base class are inaccessible to the members
//functions of the derived class
}
};
Void main()
{
master m1;
slave1 s1;
slave2 s2;
slave3 s3;
m1.a=12; //error. You cannot access a private member using an object outside a class
m1.b=14; //error. You cannot access a protected member using an object outside a class
m1.c=16; // You can access a public member using an object outside a class
s1.c=18; /* You cannot access a public base class member outside a class by using the derived
class object in private derivation */
s2.c=18; /* You cannot access a public base class member outside a class by using the derived
class object in protected derivation */
s3.c=18; /* You can access a public base class member outside a class by using the derived class
object in public derivation */
}
15(a) Consider the TNEB electricity bill generation problem. Define suitable classes and objects. Write a
program to implement the application with neat output format.
>100 RS.1.20 per unit
>200 RS.2 per unit
>300 RS.3 per unit
#include<iostream. h>
#include<conio.h>
classebill
{
private:
intcno;
charcname[20];
int units;
double bill;
public:
void get()
{
Cout<<"Enter custno,name and no. of units";
Cin>>cno>>cname>>units;
}
void put()
{
Cout<<''\nCustomer no is"<<cno;
Cout<<''\nCustomer name is''<<cname;
Cout<<''\nNumber of units consumed"<<units;
Cout<<''\nBiII of Customer"<<bill;
}
voidcalc()
{
if(units<=100)
bill=units*1.20;
else if(units<=300)
bill= 100* 1.20+( units-1 00)*2;
else
bill=100*1.20+200*2+(units-300)*3;
}
};
void main()
{
ebill p1;
p1.get();
p1.calc();
p1.put();
getch();
}
Output:
Enter custno,name and no. of units 4 navtej 200
Customer no is 4
Customer name is navtej
Number of units consumed 200
Bill of Customer 320
15(b) Write short notes on
(i) PURE VIRTUTAL FUNCTIONS
The function inside the base class is seldom used for performing any task. It only serves as a
placeholder. For example, we have not defined any object of class media and therefore the function
display() in the base class has been defined ‘empty’. Such functions are called “do‐nothing” functions.
A “do‐nothing” function may be defined as follows:
Virtual void display () =0;
Such functions are called pure virtual functions. A pure virtual function is a function declared in a base
class that has no definition relative to the base class. In such cases, the compiler requires each derived
class to either define the function or redeclare it as a pure virtual function. Remember that a class
containing pure virtual functions cannot be used to declare any objects of its own.
(ii) I/O Manipulators
Manipulators are operators that are used to format the data display
End:
The endl manipulator when used in an output statement, causes a linefeed to be
inserted.
It has same effect as using the new line character “\”.
EXAMPLE:
COUT << “M”=”<<M<<EBDL;
SETW() MANIPULATOR
The setw() manipulator set the width of field assigned for the output.
It takes the size of the field ( in number of charaters ) as a parameter.
Example:
Cout<<setw(6)<<”r”;
It generates the following output on the screen.
(each underscore represents a blank space)_ _ _ _ R.