Escolar Documentos
Profissional Documentos
Cultura Documentos
2012-2013
Department of CSE
Syllabus
CS2312 OBJECT- ORIENTED PROGRAMMING LAB 0 03 2
1. Function overloading, default arguments in C++ 2. Simple class design in C++, namespaces, objects creations 3. Class design in C++ using dynamic memory allocation, destructor, copy constructor 4. Operator overloading, friend functions 5. Overloading assignment operator, type conversions 6. Inheritance, run-time polymorphism 7. Template design in C++ 8. I/O, Throwing and Catching exceptions 9. Program development using STL 10. Simple class designs in Java with Javadoc 11. Designing Packages with Javadoc comments 12. Interfaces and Inheritance in Java 13. Exceptions handling in Java 14. Java I/O 15. Design of multi-threaded programs in Java TOTAL : 45 PERIODS
Page 1 of 86
Department of CSE
Page 2 of 86
Department of CSE
Ex No: 1a
Sum of numbers using Default arguments
Date:
AIM: To add numbers using default arguments. ALGORITHM: Step 1: Start. Step 2: Read 5 integer numbers Step 3: Three variables are alone initialized. Step 4: Call the function sum . Step 5: Initially only two arguments are passed. Step 6: Next three arguments which are read are passed to the function. Step 7: Sum of these numbers are calculated in the function. Step 8: Stop.
Page 3 of 86
Department of CSE
Output:
Enter 5 integer numbers 24157 Total = 19 Total = 15 Total=14 Total=19 Result: Thus the program executed successfully St Josephs College of Engineering ISO 9001:2008 Page 4 of 86
Department of CSE
Page 5 of 86
Department of CSE
Ex No: 1b Date:
AIM: To swap two integers, float numbers and character using function overloading. ALGORITHM: Step 1: Start Step 2: Read two integers. Step 3: Call the function swap(i,j), i and j is declared as integers. Step 4: Read two float numbers. Step 5: Call the function swap(p,q), p and q is declared as float. Step 6: Read two characters. Step 7: Call the function swap(c1,c2), c1 and c2 is declared as character Step 8: Print all the swapped values. Step9: Stop.
Page 6 of 86
Department of CSE
#include<iostream.h> #include<conio.h> void swap(float &c,float &d) { float t; t=c; c=d; d=t;} void swap(int &a,int &b){ int t; t=a; a=b; b=t; } void swap(char &e,char &f){ char t; t=e; e=f; f=t;} void main() { int i1,i2; float f1,f2; char c1,c2; clrscr(); cout<<"\n Enter two integers : \n"; cout<<" i1 = "; cin>>i1; cout<<"\n i2 = "; cin>>i2; swap(i1,i2); cout<<"\n Enter two float numbers : \n"; cout<<" f1 = ";
St Josephs College of Engineering ISO 9001:2008 Page 7 of 86
Department of CSE
cin>>f1; cout<<"\n f2 = "; cin>>f2; swap(f1,f2); cout<<"\n Enter two Characters : \n"; cout<<" c1 = "; cin>>c1; cout<<"\n c2 = "; cin>>c2; swap(c1,c2); cout<<"\n AFTER SWAPPING \n"; cout<<" \n\n INTEGERS i1 = "<<i1<<"\t i2 = "<<i2; cout<<" \n\n FLOAT NUMBERS f1= "<<f1<<"\t f2 = "<<f2; cout<<" \n\n CHARACTERS c1 = "<<c1<<"\t c2 = "<<c2; getch(); } Login: Pugal Output: Enter two integers : i1 = 10 i2 = 20 Enter two float numbers : f1 = 11.1 f2 = 22.34 Enter two Characters : c1 = A c2 = B AFTER SWAPPING INTEGERS i1 = 20 CHARACTERS c1 = B i2 = 10 f2 = 11.1 c2 = A FLOAT NUMBERS f1= 22.34
Result: Thus the program executed successfully St Josephs College of Engineering ISO 9001:2008 Page 8 of 86
Department of CSE
Page 9 of 86
Department of CSE
#include<iostream.h> #include<conio.h> class sample { private: int a,b; public: void read() { cout<<"\n\nENTER TWO NUMBERS\n\n"; cin>>a>>b; } int max() { if(a>b) return a; else return b; } void show() { cout<<"\n Maximum number is = "<<max()<<"\n\n"; } }; void main() { clrscr(); sample obj1,obj2; cout<<"\n\t USING FIRST OBJECT\n"; obj1.read(); obj1.show(); cout<<"\n\t USING SECOND OBJECT\n";
St Josephs College of Engineering ISO 9001:2008 Page 10 of 86
Department of CSE
obj2.read(); obj2.show(); getch(); } Login: Pugal Output: USING FIRST OBJECT ENTER TWO NUMBERS 10 20 Maximum number is = 20 USING SECOND OBJECT ENTER TWO NUMBERS 56 12 Maximum number is = 56
Result: Thus the program executed successfully
Page 11 of 86
Department of CSE
Ex No: 3a Date:
AIM: To write a program to illustrate copy constructor in c++. ALGORITHM: Step1: Include the required header files. Step2: Declare the constructor with arguments as integer data type inside the class Step3: In the function definition display show the values. Step4: In the main function declare the objects. Step5: In the main function evaluate display(). Step6: Stop
Page 12 of 86
Department of CSE
int main() { code A(300); code B(A); code C=A; cout<<"\n id of A: ";A.display(); cout<<"\n id of B: ";B.display(); St Josephs College of Engineering ISO 9001:2008 Page 13 of 86
Department of CSE
Page 14 of 86
Department of CSE
To write a C++ program to implement the concept of Dynamic memory allocation, constructor and destructor. Algorithm: Step1: Start. Step2: Define a class str with all three types of constructors without argument, with argument and copy constructor which is used for dynamically creating the memory. Step3: The member function join() is used for concatenating two strings. Step4: Define Destructor. Step5: Create objects for the class str to execute the constructor separately. Step6: Display the values for each object. Step7: Stop.
Page 15 of 86
Department of CSE
#include<iostream.h> #include<string.h> #include<conio.h> class str { char *name; int len; public: str() { len=0; name=new char[len+1]; } str(char *s1) { len=strlen(s1); name=new char[len+1]; strcpy(name,s1); } str(str &s2) { len=s2.len; name=new char[len+1]; strcpy(name,s2.name); } ~str() { cout<<"\n Memory Destroyed\n"; } void join(str &s1,str &s2) { len=s1.len+s2.len;
St Josephs College of Engineering ISO 9001:2008 Page 16 of 86
Department of CSE
cout<<"\n Length = "<<len; delete name; name=new char[len+1]; strcpy(name,s1.name); strcat(name,s2.name); } void show(){ cout<<name<<"\n";} }; void main(){ clrscr(); str e1("computer"); str e2("science"); str e3; cout<<"\n String1 ="; e1.show(); cout<<"\n String2 ="; e2.show(); e3.join(e1,e2); cout<<"\n The concatenated String is = "; e3.show(); str e4(e3); cout<<"\n Using Copy Constructor String is = "; e4.show(); getch(); } Login: Pugal Output: String1 =computer String2 =science Length = 15 The concatenated String is = computer science Using Copy Constructor String is = computer science
Result: Thus the program executed successfully St Josephs College of Engineering Page 17 of 86 ISO 9001:2008
Department of CSE
Ex No: 3c Date:
Implementation of Destructor
AIM: To write a program to delete a memory address using destructor. ALGORITHM: Step1: Include the required header file Step2: Declare the data members and member functions of class fib. Step3: Function definitions are made using scope resolution operator. Step4: Destructor is declared inside the class using ~ operator. Step5: An object is declared inside the main function. Step6: Member functions are called using dot operator. Step7: Using a for loop the numbers of the series are printed.
Page 18 of 86
Department of CSE
Department of CSE
Login: Pugal
Output: 0 1 1 2 3 5 8 13 21 34 55 89 Memory space deleted Result: Thus the program executed successfully
Page 20 of 86
Department of CSE
Step2: Inside the class declaration declare the required data members and member functions Step3: The overloading function is declared in the class declaration using friend keyword. Step4: All the member functions are defined outside the class declaration. Step5: In the main function, required numbers of objects are created and call to different Member functions are made. Step6: Stop.
Page 21 of 86
Department of CSE
Department of CSE
Login: Pugal
Output: 4.5+-i5.5 2.5+-i4.5 7+-i10 Result: Thus the program executed successfully
Page 23 of 86
Department of CSE
Step2: Inside the class declaration declare the required data members and member functions Step3: The overloading function of assignment operator is declared in the class declaration. Step4: All the member functions are defined outside the class declaration. Step5: In the main function, required numbers of objects are created and call to different member functions are made. Step6: Stop.
Page 24 of 86
Department of CSE
Department of CSE
Page 26 of 86
Department of CSE
AIM: To write a program to demonstrate Type conversion from one object to another object. ALGORITHM: Step1: Include the required header files Step2: Inside the class declaration declare the required data members and member functions Step3: All the member functions are defined outside the class declaration. Step4: In the main function, required numbers of objects are created and call to different member functions are made. Step7: Three numbers are read in the main function. Step8: Functions are called to find the greatest of three numbers using type conversion. Step9: Stop.
Page 27 of 86
Department of CSE
Department of CSE
Login: Pugal
Output: Enter three numbers 56 23 89 Greatest number is 89 Result: Thus the program executed successfully
Page 29 of 86
Department of CSE
Step2: Inside the class declaration declare the required data members and member functions Step3: Declare a derived class for the base class with its own data members and member Functions. Step4; Define the member functions of both the derived class and base class. Step5: In the main() function create an object for the derived class which inherits the Properties of base class. Step6: Call the required member functions. Step7: Stop.
Page 30 of 86
Department of CSE
Department of CSE
Department of CSE
Login: Pugal
Output: INPUT ~~~~~~~ Enter Name : pugalenthi Enter Age : 37 Enter Rollno : 100 Enter Registerno : 200 Enter Branch : cse OUTPUT ~~~~~~~ Name : pugalenthi Age : 37 Roll No : 100 Register No : 200 Branch : cse Result: Thus the program executed successfully
Page 33 of 86
Department of CSE
ALGORITHM: Step1: Include the required header files Step2: Inside the class declaration declare the required data members and member functions Step3: Declare a derived class for the base class with its own data members and member Functions. Step4: Create a derived class named derived which derives both base1 and base2 classs. Step5: In the main() function create an object for the derived class which inherits the Properties of both base classes. Step6: Call the required member functions using the object created. Step7: Stop.
Page 34 of 86
Department of CSE
Department of CSE
Login: Pugal
Output: Enter 2 numbers : 26 OUTPUT ~~~~~~~~ Added Value = 8 Subtracted Value = -4 Product of added and subtracted value=-32 St Josephs College of Engineering ISO 9001:2008 Page 36 of 86
Department of CSE
Page 37 of 86
Department of CSE
Step2: Inside the class declaration declare the required data members and member functions Step3: A template is declared. Step4: In the main() function create an object . Variables a is declared as an integer, b is f Float and c is declared as double. Step5: Square of the numbers is found out by incorporating runtime polymorphism method Step6: Call the required member functions. Step7: Stop.
Page 38 of 86
Department of CSE
Login: Pugal
Output: Enter an Integer : 6 Square of a = 36 Enter a Float Value : 14 Square of b = 196 Enter a Double Value : 20 Square of c = 400 Result: Thus the program executed successfully St Josephs College of Engineering ISO 9001:2008 Page 39 of 86
Department of CSE
To write the C++ program to implement the concept of Template with I/O . Algorithm: Step1: Start. Step2: Define a ostream with setw and setfill functions to format the display. Step3: Define a Template T. Step4: Define the sort() using the template T. Step5: Get the integer values and call the sort(). Step6: Get the charaters and call the sort(). Step7: Call the print() to display the values. Step8: Stop.
Page 40 of 86
Department of CSE
#include<iostream.h> #include<conio.h> #include<iomanip.h> ostream &symbol(ostream &output) { return(output<<setw(35)<<setfill('*')<<"\n"); } template<class T> void print(T *a,int n) { for(int i=1;i<=n;i++) { cout<<"\t"<<a[i]; } } template<class T> void sort(T *a,int n) { for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) { if(a[i]>a[j]) { T temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } void main()
St Josephs College of Engineering ISO 9001:2008 Page 41 of 86
Department of CSE
{ clrscr(); int a[10],i,n; char c[10]; cout<<symbol<<"\n TEMPLATES USING IOMANIPULATION"<<endl<<symbol; cout<<"\n Enter the number of elements (Maximum of 10) \n"; cin>>n; cout<<"\n Enter "<<n<<" Integers\n"; for(i=1;i<=n;i++) cin>>a[i]; cout<<"\nBefore Sorting\n"; print(a,n); sort(a,n); cout<<"\nAfter sorting\n"; print(a,n); cout<<"\n Enter the number of elements (Maximum of 10) \n"; cin>>n; cout<<"\n Enter "<<n<<" charaters\n"; for(i=1;i<=n;i++) cin>>c[i]; cout<<"\nBefore sorting\n"; print(c,n); sort(c,n); cout<<"\nAfter Sorting\n"; print(c,n); getch();} Login: Pugal Output: ********************************** TEMPLATES USING IO MANIPULATION ********************************** Enter the number of elements (Maximum of 10) 6
St Josephs College of Engineering ISO 9001:2008 Page 42 of 86
Department of CSE
Enter 6 Integers 4 7 12 34 8 9 Before Sorting 4 4 3 Enter 3 charaters e a b Before sorting e a a b b e After Sorting
Result: Thus the program executed successfully
7 7
12 8
34 9
8 12
9 34
Page 43 of 86
Department of CSE
To write a C++ program to implement the concept of Exception handling. Algorithm: Step1: Start. Step2: Create a class My Exception with the divide() Step3: If x is 0 then the exception is thrown then the catch block displays the message division by zero is not possible Step4: Stop.
Page 44 of 86
Department of CSE
#include<iostream.h> #include<conio.h> class MyException { int n; public: MyException(int a) { n=a; } int Divide(int x) { try { if(x==0) { throw x; cout<<"This statement will not be executed\n"; } else { cout<<"Trying division succeeded\n"; cout<<"\n Quotient = "<<n/x; } } catch(int) { cout<<"Exception : Division by zero. Check the value"; } return 0; } };
St Josephs College of Engineering ISO 9001:2008 Page 45 of 86
Department of CSE
void main() { int a; cout<<"\n Enter a Number : "; cin>>a; MyException ex(10); ex.Divide(a); } Login: Pugal Output: Enter a Number : 5 Trying division succeeded Quotient = 2 This statement will not be executed Enter a Number: 0 Exception: Division by zero. Check the value
Result: Thus the program executed successfully
Page 46 of 86
Department of CSE
Ex No: 9 Date:
Algorithm: Step1: Include all the required header files. Step2: Write the appropriate syntax for vector. Step3: Get the values using a for loop. Get upto 10 numbers. Step4: Using the index sort the numbers in ascending and descending order. Step5: Print the index that is the numbers in sorted order. Step6: Stop.
Page 47 of 86
Department of CSE
Department of CSE
Department of CSE
To write a java program to calculate the area of rectangle and circle. Algorithm: Step1: Start. Step2: create a class area which includes the parameter for rectangle and circle. Step3: Define area of rectangle and circle within the class. Step4: create a method (void main()) and pass objects as parameters to the methods. Step5: Display the area of rectangle and circle in void main(). Step6: Stop.
Page 50 of 86
Department of CSE
class area { float length; float breadth; double radius; void getrectdata(float a,float b) { length=a; breadth=b; } void getcirdata(float c) { radius=c; } float rectarea(area rec) { return(rec.length*rec.breadth); } double cirarea(area cir) { return(3.14*cir.radius*cir.radius); } } class ex3 { public static void main(String args[]) { area ar=new area(); float a; double b; ar.getrectdata(4,2); ar.getcirdata(4);
St Josephs College of Engineering ISO 9001:2008 Page 51 of 86
Department of CSE
a=ar.rectarea(ar); b=ar.cirarea(ar); System.out.println("\nArea of Rectangle="+a); System.out.println("\nArea of Circle="+b); } } OUTPUT: Z:\Pugal>set path=C:\Program Files\Java\jdk1.6.0-16\bin Z:\Pugal>javac ex3.java Z:\Pugal>java ex3 Area of Rectangle=8.0 Area of Circle=50.24
Result: Thus the program executed successfully
Page 52 of 86
Department of CSE
Ex No: 11 Date:
AIM: To implement packages using a java program. ALGORITHM: Step1: Declare packages P1,P2,P3,P4 implementing the classes foat point, relational operator, increment operator , decrement operator respectively as public. Step2: Import the four packages in a separate decrement, containing the main function as public static. Step3: Create objects for the classes of the different packages and display the results by calling the display function of respective classes. Step4: Create a sub directory under the main directory and name the folder as package name.
Page 53 of 86
Department of CSE
Department of CSE
Department of CSE
Department of CSE
Page 57 of 86
Department of CSE
To write a java program to implement the concept of multiple inheritance. Algorithm: Step1: Start. Step2: Define a class stu to get the name and roll no and display the same. Step3: Define a class test that acts as a sub-class of stu. Get the marks m1, m2 and display the same. Step4: Define an interface sports that carries the spors weightage. Step5: Define class result that extends class test and implements interface sports. Step6: Calculate the total marks in class result. Step7: Define class final pgm and void main() as public static. Step8: Declare an object s to class result and invoke getdata(), getmark() and display() to print the output. Step9: Stop.
Page 58 of 86
Department of CSE
class stu { String name; int rollno; void getdata(String s,int r) { name=s; rollno=r; } void putdata() { System.out.println("\nName="+name); System.out.println("\nRoll No="+rollno); } } class test extends stu { int m1,m2; void getmarks(int x,int y) { m1=x; m2=y; } void putmarks() { System.out.println("\nMark1="+m1); System.out.println("\nMark2="+m2); } } interface sports { final int sp=6;
St Josephs College of Engineering ISO 9001:2008 Page 59 of 86
Department of CSE
abstract void putsp(); } class result extends test implements sports { int tot; public void putsp() { System.out.println("\nSports wt="+sp); } void display() { tot=m1+m2+sp; putdata(); putmarks(); putsp(); System.out.println("\nTotal="+tot);} } class ex2 { public static void main(String args[]) { result s=new result(); s.getdata("aaa",123); s.getmarks(50,50); s.display();} } OUTPUT: Z:\Pugal>set path=C:\Program Files\Java\jdk1.6.0-16\bin Z:\Pugal>javac ex2.java Z:\Pugal>java ex2 Name=aaa Roll No=123 Mark1=50 Mark2=50 Sports wt=6 Total=106
St Josephs College of Engineering ISO 9001:2008 Page 60 of 86
Department of CSE
Page 61 of 86
CS2312- Object Oriented Programming Lab-EEE Dept Ex No: 13 Date: Aim: To write a java program to implement the concept of exception handling. Algorithm: Step1: Start. Step2: Create a class MyException which extends the Exception class. Step3: Define a user defined Exception. Step4: In void main(), peform an arithmetic operation. Step5: In try block check the result is less than 0.01. Step6: In catch block catch the exception and call the user defined exception. Step7: In finally block display the message. Step8: Stop.
2012-2013 Implementation Of Exception Handling In Java
Department of CSE
Page 62 of 86
Department of CSE
import java.lang.Exception; class MyException extends Exception { MyException(String message) { super(message); } } class TestMyException { public static void main(String args[]) { int x=5,y=1000; try { float z=(float) x/(float) y; if(z<0.01) { throw new MyException("number is too small"); } } catch (MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage()); } finally { System.out.println("i am always here"); } } }
St Josephs College of Engineering ISO 9001:2008 Page 63 of 86
Department of CSE
Output: Z:\Pugal>set path=C:\Program Files\Java\jdk1.6.0-16\bin Z:\Pugal>javac TestMyException.java Z:\Pugal>java TestMyException Caught my exception number is too small i am always here
Result: Thus the program executed successfully
Page 64 of 86
Department of CSE
Aim: To write a java program to implement the concept of I/O. Algorithm: Step1: Start. Step2: Import the classes util and io. Step3: Define a class inventory which define the void main(). Step4: Get the item code, no of items and item cost from the user. Step5: Using the DataOutputStream class write the item details inside the file invent.dat. Step6: Using the DataInputStream class retrieve the stored details from the file and calculate the total cost. Step7: Display the item code, no of items, cost and total cost in the console. Step8: Stop.
Page 65 of 86
Department of CSE
import java.util.*; import java.io.*; class invert { static DataInputStream din=new DataInputStream(System.in); static StringTokenizer st; public static void main(String args[]) throws IOException { DataOutputStream dos= new DataOutputStream(new FileOutputStream("invent.dat")); System.out.println("enter code number:"); st=new StringTokenizer(din.readLine()); int code= Integer.parseInt(st.nextToken()); System.out.println("enter number of items:"); st=new StringTokenizer(din.readLine()); int items= Integer.parseInt(st.nextToken()); System.out.println("enter cost:"); st=new StringTokenizer(din.readLine()); double cost= new Double(st.nextToken()).doubleValue(); dos.writeInt(code); dos.writeInt(items); dos.writeDouble(cost); dos.close(); DataInputStream dis = new DataInputStream(new FileInputStream("invent.dat")); int codeNumber = dis.readInt(); int totalItems = dis.readInt(); double itemCost = dis.readDouble(); double totalCost = totalItems * itemCost; dis.close(); System.out.println(); System.out.println("Code Number:"+ codeNumber); System.out.println("Item Cost :"+ itemCost); System.out.println("totalitems :"+ totalItems);
St Josephs College of Engineering ISO 9001:2008 Page 66 of 86
Department of CSE
System.out.println("totalcost :"+totalCost); } } Output: Z:\Pugal>set path=C:\Program Files\Java\jdk1.6.0-16\bin Z:\Pugal>javac invert.java Z:\Pugal>java invert enter code number: 1001 enter number of items: 193 enter cost: 452 Code Number:1001 Item Cost :452.0 totalitems :193 totalcost :87236.0
Result: Thus the program executed successfully
Page 67 of 86
CS2312- Object Oriented Programming Lab-EEE Dept Ex No: 15 Date: Aim: To write a java program to implement multithreading. Algorithm: Step1: Start. Step2: Define a class A that extends Thread. Step3: Call run(). Within this , use for loop to display the value of I from to 5. Step4: Define a class B that extends Thread. Step5: Call run() to display the value of j from 1to 10. Step6: Define class C that extends Thread. Step7: Call run() to display the value of k from 1 to 15. Step8: In the main() call A, B, C classes using start() with the help of an object. Step9: Stop.
2012-2013 Implementation Of Multi Threading In Java
Department of CSE
Page 68 of 86
Department of CSE
class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("from Thread A:i="+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=10;j++) { System.out.println("from Thread B:j="+j); } System.out.println("Exit from B"); } } class C extends Thread { public void run() { for(int k=1;k<=15;k++) { System.out.println("from Thread C:k="+k); } System.out.println("Exit from C"); }
St Josephs College of Engineering ISO 9001:2008 Page 69 of 86
Department of CSE
} class ex1 { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } } OUTPUT: Z:\Pugal>set path=C:\Program Files\Java\jdk1.6.0-16\bin Z:\Pugal>javac ex1.java Z:\Pugal>java ex1 from Thread A:i=1 from Thread B:j=1 from Thread C:k=1 from Thread A:i=2 from Thread B:j=2 from Thread C:k=2 from Thread A:i=3 from Thread B:j=3 from Thread C:k=3 from Thread A:i=4 from Thread B:j=4 from Thread C:k=4 from Thread A:i=5 from Thread B:j=5 from Thread C:k=5 Exit from A from Thread B:j=6
St Josephs College of Engineering ISO 9001:2008 Page 70 of 86
Department of CSE
from Thread C:k=6 from Thread B:j=7 from Thread C:k=7 from Thread B:j=8 from Thread C:k=8 from Thread B:j=9 from Thread C:k=9 from Thread B:j=10 from Thread C:k=10 Exit from B from Thread C:k=11 from Thread C:k=12 from Thread C:k=13 from Thread C:k=14 from Thread C:k=15 Exit from C
Result: Thus the program executed successfully
Page 71 of 86
Department of CSE
List of object oriented concepts are Encapsulation, data abstraction, Inheritance, polymorphism, message passing, extensibility, persistence, delegation, generality . 2. Define object? Defining variables of a class data type is known as class instantiation and such variables are called objects. Object is a instance of a class. 3. Define class? Object oriented programming constructs support a data type called class. A class encloses both the data and functions. The enclosed data and function in a class are called data member and member function respectively. 4. Define encapsulation? It is a mechanism that associates the code and data it manipulates into a single unit. In C++ , this is supported by a construct called class. An instance of a clas is known as an object, which represents areal world entity. 5. Define data abstraction ? The technique of creating new data type that are well suited to an application to be programmed is known as data abstraction. The class is a construct in C++ for creating user defined data types called ADTS. 6. Define message passing in oops? It is a process of invoking an operation of object. In response to a message , the corresponding method is executed in the object. 7. Write the difference between class and structure in C++? Class in C++ is similar to C struct except that in C++ the class can have functions as well. Class members can be divided into public and private portions. Private members can not be accessed by non members, while public members can be accessible to both members and non members. But the default type of struct is public. 8. What do you mean by inheritance? It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes (derived classes) from the existing ones(base classes), thus enabling the creation of a hierarchy of classes that simulate the class and sub class concept of the real world. 9. Define polymorphism? St Josephs College of Engineering ISO 9001:2008 Page 72 of 86
Department of CSE
2012-2013 It allows a single name/operator to be associated with different operation depending on the type of data passed to it. 10. List out all C++ access specifiers? The list of C++ access specifiers are private, public, and protected. Private: Private members can be accessed by only members of the same class and can not be accessed by non members. Public: public members can be accessible to both members and non members. Protected : it can be accessed by members of subclasses and own members and can not be accessed by non members. 11. Define data member and member function? Data members are variables defined in a class. These can be either be private or public. Member functions are functions defined in a class, it may be defined inside or outside the body of the class.
12. What is the use of static members? A static data member is defined with a static keyword preceding it in the class definition. It must have a definition outside the body of the class. It is shared between all the objects of a class. 13. What is function overloading? Function overloading in C++ allows more than one function with same name but with different set of arguments. This process is known as function overloading and each participating function is known as overloaded function. 14. Define volatile function? A member function can also be declared as volatile if it is invoked by a volatile object. A volatile objects value can be changed by external parameter which are not under the control of the program. 15. What is friend function? A friend function is either a non member function or a member function of some other class, which is given special permission to access private variables of the class. The function is said to be the friend of a the class under consideration. 16. Define constant object?
Page 73 of 86
Department of CSE
2012-2013 Constant (const) objects are objects that are not modifiable. C++ provides safeguarding against accidental modification by not allowing access of the object to a normal member function. Const object , obviously , is not allowed to do operations which modify the object. 17. Give an example for nested classes? Class outside { Private: Class inside { Int insideint; Public: Void setinsideint(int tempinside) { Insideint = tempinside; } }; // this ends the inner clas definition Public: Int outsideint; Inside insideobject; Void useinside() { Insideobject.setinsideint(outside); Cout<< outsideint; } }; // this ends the outer class 18. What is inline function? This is the function which, when a statement calling them is compiled , is replaced by the body of the same function. 19. How will you create pointer to data members? In C++ , pointers can also have an address for an object. They are known as pointers to objects. A pointer to an object contains an address of that object. Pointer increment will increment the address by the size of an object. The size of the object is determined by the size of all of its nonstatic data elements. 20. What is local class? For the sake of completeness , C++ allows classes to be defined inside functions as well . These classes are called local classes. 21. Define constructor? A function with the same name as the class itself responsible for constructing and returning objects of the class is called constructor. 22. What do you mean by copy constructor? St Josephs College of Engineering ISO 9001:2008 Page 74 of 86
Department of CSE
2012-2013 Copy constructor is used to copy the value of one object into another. When one object is copied to another using initialization , they are copied by executing the copy constructor. The copy constructor contains the object as one of the passing argument. 23. Define default constructor and give example? A constructor without any argument is called default constructor. Ex Class complex { Public: void comples(); }; 24. What is parameterized constructor? A constructor with one or more than one argument is called parameterized constructor. Ex Class complex { Public: Complex complex( int real, int imag); }; 25. Define destructor? The function which bears the same name as class itself preceded by ~ is destructor. The destructors automatically called when the object goes out of scope. 26. What do you mean by explicit constructor? The one argument constructor which is defined with keyword explicit before the definition. Explicit word prohibits the generation of conversion operator for a single argument constructor. 27. Explain multiple constructor? A class with more than one constructor comes under multiple constructor. Multiple constructor is constructed with different argument list. That is either with empty default constructor or with parameterized constructor. 28. What is operator overloading? St Josephs College of Engineering ISO 9001:2008 Page 75 of 86
Department of CSE
2012-2013 The process of giving an existing operator a new , additional meaning is called operator overloading. 29. What is the lifetime of an object? The life time of a global object is throughout the execution of the program. Otherwise , the object comes into existence when constructor is over and is alive till it gives out of scope, i.e just before the destructor is applied. 30. List out the operator which can not be overloaded ? 1. The dot operator for member access.(.) 2. The dereference member to class operator .( *) 3. Scope resolution operator.(: 4. Size of operator (sizeof). 5. Conditional ternary operator(:?) 6. Casting operators static_cast<>, dynamic_cast<>, reinterpret_cast<>, const_cast<> 7. # and ## tokens for macro preprocessor. 31. Define new operator? The operator new is used for allocation of memory, it gets memory from heap. It is similar to malloc() in C. Ex to get memory for an integer and assign the address of allocated memory to pointer p, Int* p = new int. 32. Define delete operator? Delete in C++ does a similar job as free() function in C, i.e it releases the memory occupied by the new operator. 33. Define wrapper classes? A class which makes a C like struct or built in type data represented as a class. For example, an Integer wrapper class represents a data type int as a class.
34. List out the operators that can not be overloaded as a friend? 1. Assignment operator =. 2. Function call operator () 3. Array subscript operator [] St Josephs College of Engineering ISO 9001:2008 Page 76 of 86
Department of CSE
When we need to convert between different types , we guide the compiler how to convert from one type to another by writing operator functions or constructors. 36. Difference between unary and binary operator? All operators having a single argument are unary operators. When we overload these operators as member function, we do not need to pass any argument explicitly. Operators with two argument are known as binary operators. They will have a single argument when defined as member function. The first argument to that operator is always the invoking object. 37. Explain insertion and extraction operator? Insertion operator : The << operator which is used to write to the console is known as insertion operator. It is also known as the output operator. Extraction operator : The >> operator which is used to read from the keyboard is known as extraction operator. It is also known as the input operator. 38. Explain function overloading? Function overloading in C++ allows more than one function with same name but with different set of arguments. This process is known as function overloading and each participating function is known as overloaded function. 39. List out the user defined conversion? 1.conversion from built in data type to an object. 2. conversion from object to a built in data type. 40. What is function objects? Objects of the classes where () operator is overloaded. In this case objects can be written with a () and can be treated like functions. Such objects which can be called like a function are known as function objects.
41. What is function template? Function templates are generic functions, which work for any data type that is passed to them. The data type is not specified while writing the function. while using that function, we pass the data type and get the required functionality. 42. List out the draw back of using macros? Draw back of using macros are St Josephs College of Engineering ISO 9001:2008 Page 77 of 86
Department of CSE
2012-2013 1. Macros are not visible to the compiler. They are substituted by their body by a pre compiler. If there is some error in the body of the macro, the error is represented in a non user friendly form. 2. The type related information is lost in the macros. Moreover it is not possible to have any related validations in the macros. 3. Macros are evaluated twice. Once when they are copied and the next time when they are executed. 43. What is class template? A generic class outlined by specification of a generic type using template keyword. The actual class is defined later using this template. 44. What is the use of export keyword? Export keyword is required for implementing the separate compilation method. When the template definition is proceeded by export, the compiler can manage to compile other files without needing the body of the template functions or member function of the template class. 45. Explain the use of Type name ? The type name or class keywords are used to define generic name for the type in function or class template. 46. Explain the advantages of template? Templates are used to increase software reusability, efficiency and flexibility. It increases the reusability without inheritance. Function templates in C++ provides generic functions independent of data type. The advantage of class template is that we can define a generic class that works for any data type that is passed to it as a parameter. 47. What is instantiation? Generation of either function or class for a specific type using the class of function template is known as instantiation of the class or function. 48. Explain the two models for template compilation? Compilation models for template are 1. Inline vs non-inline function calls in multiple files. 2. Template instantiation in multiple files. 49. Give an example of multi argument template? It is possible to have template with more than one argument. Other argument can be generic or normal. Example St Josephs College of Engineering ISO 9001:2008 Page 78 of 86
Department of CSE
The error handling mechanism of C++ is generally referred to as exception handling. Exceptions are classified into two types 1. Synchronous 2. Asynchronous. The proposed exception handling mechanism in C++ is designed to handle only synchronous exceptions caused within a program. When a program encounters an abnormal situation for which it is not designed , the user may transfer control to some other part of the program that is designed to deal with the problem. 52. Write the need for exception handling? Need for exception handling 1. Dividing the error handling 2. Unconditional termination and programmer preferred termination 3. Separating error reporting and error handling 4. The object destroy problem. 53. List out the components of exception handling mechanism? Components of exception handling mechanism are Try - try for indicating program area where exception can be thrown. Throw for throwing an exception. Catch catch for actually taking an action for the specific exception. 54. What is the use of catch all ? Catch all the expression catch(...) is known as catch all. It is possible to catch all types of exceptions in a single catch section. 55. Define Rethrowing an exception? Rethrowing the exception is once handled by a handler, can be rethrown to a higher block. This process is known as rethrowing. 56. Define uncaught exception? St Josephs College of Engineering ISO 9001:2008 Page 79 of 86
Department of CSE
2012-2013 Uncaught_exception() is the function to call when we want to check before throwing any exception if some other exception is already on. 57. What is the use of terminate()? Terminate() is a function to call when the exception handling mechanism does not get any proper handler for a throw exception. 58. What is the use of unexpected()? Unexpected() is a function to call when the exception handling mechanism encounters an exception not allowed from exception specification. 59. What are the disadvantages of the exception handling mechanism? Exception handling has some disadvantage that is it adds runtime and demands different style of programming than conventional programming. It is not the tool to replace normal error handling. 60. What is uncaught()? When the exception is thrown , the destructors of all the objects defined in the try block are called one by one. Then the exception is handled . Now it is said to be caught. If we check for uncaught exception now it is found to be caught. 61. List the different types of inheritance? Different types of inheritance are 1.single inheritance 2. multiple inheritance 3.hierarchical inheritance 4.multilevel inheritance 5.hybrid inheritance
62. What is derived class? The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as the base class and new one is called derived class.
63. What are the advantages of using inheritance? Advantages of using inheritance 1. We are in need of extending the functionality of an existing class. St Josephs College of Engineering ISO 9001:2008 Page 80 of 86
Department of CSE
2012-2013 2. We have multiple classes with some attributes common to them. We would like to avoid problems of inconsistencies between the common attributes. 3. We would like to model a real world hierarchy in our program in a natural way. 64. Explain access control? Member functions of a class , member functions of the derived class, friend and object can access different parts of the class. Access for public , private and protected members is different for all entities. Access control describes who can access what and in which form. The following fig shows the access control
the
public members of the class private members of the class protected members of the class
65. Define multiple inheritance? Derivation of a single class from more than one class is called multiple inheritance.
A B
Page 81 of 86
Department of CSE
A virtual base class which is defined as virtual at the time of inheriting it. The compiler takes a note of it and when it is inherited further using multiple inheritance, it ensures that only one copy of the sub object of the virtual inherited class exists in the derived class. 67. Define abstract class? A class without any object is known as an abstract class. 68. Define composite objects? Composite or container object is defined as an object which includes other objects as data members. 69. Define runtime polymorphism? Polymorphism achieved using virtual functions is knows as runtime polymorphism. 70. Define compile time polymorphism? Polymorphism achieved using operator overloading and function overloading is known as compile time Polymorphism. 71. Define this pointer? It is the pointer to invoking an object implicitly when a member function is called. 72. Define virtual function? A function defined with virtual keyword in the base class is known as virtual function. Compiler will decide the exact class pointed to by the base class pointer and call the respective function of that class if the function is defined as virtual. 73. What do you mean by pure virtual function? A virtual function with =0 on place of a body in the class. They may not have a body. It is possible to have a body of pure virtual function defined outside the class. 74. What is RTTI? RTTI is defined as run time type information and it is a mechanism to decide the type of the the object at runtime. 75. Define static binding? Linking a function during linking phase is known as static binding. Normal functions are statically bound. 76. Define dynamic binding? St Josephs College of Engineering ISO 9001:2008 Page 82 of 86
Department of CSE
2012-2013 Linking the function at run time is known as dynamic binding. Virtual functions are dynamically bound. Though it is possible for the compiler to statically bind the static invocations of virtual functions and also the case where it is possible to decide at compile time. In that case virtual function are also statically bound. 77. What is cross casting? When a multiply derived class object is pointed to by one of its base class pointers, casting from one base class pointer into another base class pointer is known as cross casting. 78. What is down casting? Casting from a base class pointer to a derived class pointer is known as down casting. 79. What is reinterpret_cast? Reinterpret_cast is defined as a casting operator for abnormal casting like int to pointer and pointer to int. 80. What is the use of typeid operator? This operator can be applied to any object or class or built in data type. It returns the typeinfo object associated with the object under consideration. 81. What are streams? A stream is a conceptual pipe like structure, which can have one end attached to the program and other end attached by default to a keyboard, screen or a file. It is possible to change where one end is pointing to, while keeping the other end as it is. 82. List all formatted I/O in C++? The following list of ios functions are called formatted I/O in C++ Width(), precision(), fill(), setf(), unsetf().
83. Define manipulator? Manipulator are functions which are non member but provide similar formatting mechanism as ios functions 84. Write the difference between manipulators and ios function? The major difference in the way the manipulators are implemented as compared to the ios member functions. The ios member funtions return the previous format state which can be used latter if necessary. But the manipulator does not return the previous state. 85. Explain setf()? St Josephs College of Engineering ISO 9001:2008 Page 83 of 86
Department of CSE
2012-2013 The function specifies format flags that controls output display like left or right justification, padding after sign symbol, scientific notation display, displaying base of the number like hexadecimal, decimal, octal etc. Ex cout.setf(ios::internal,ios::adjustfield); Cout.setf(ios::scitific,ios::floatfield); 86. Define Namespace? Namespace is a kind of enclosure for functions, classes and variables to separate them from other entities. 87. Explain get() and put() function? The classes istream and ostream define two member functions get() and put() respectively to handle a single character input and output operations. The function cin.get() had two different versions. The first version has a prototype void get(char) and the other has prototype char get(void). The fuction cout.put() used to display a character . 88. Explain read() and write() function? The functions read() and write() are used for read and write operations. In addition to string parameter for reading and writing these two functions have additional parameter indicating the size of the string. Cin.read(string variable, maximum size of the string variable that can be input) Cin.write(string variable, maximum size of the string variable that can be output) 89. Explain seekg() and seekp() function? Seekg() moves get pointer to a specified location Seekp() moves put pointer to a specified location Seekg(offset, refposition); Seekp(offset,refposition); 90. Explain tellg() and tellp() function? Tellg() gives the current location of the get pointer Tellp() gives the current position of the put pointer. 91. What is global namespace? The golbal namespace is namespace where every function or class is copied in older C++ by default. 92. Define Koening lookup? St Josephs College of Engineering ISO 9001:2008 Page 84 of 86
Department of CSE
2012-2013 Knoeing lookup is the ability of the compiler to find out exact namespace of the object in use even when not specified by the programmer. 93. List different way of constructing a string object? A string object can be created in 3 ways. 1. Defining a string object in a normal way. 2. Defining a string object using initialization 3. Defining a string object using a constructor. Ex String firststring; // normal defintion String secondstring(Hello); // definition using one agrument constructor String thirdstring(secondstring); // definition using initialization String fourthstring=firststring; // defining and initializing 94. Define standard template library? Standard template Library or STL , is a collection of generic software components(generic containers) and generic algorithms, glued by objects called iterators. 95. Write some example manipulators in C++? The following are some examples of manipulators Setw(), setprecision(), setfill(), setiosflags(), resetiosflags() 96. List out the advantages of readymade software components? There are few advantages of readymade components 1. Small in size 2. Generality 3. Efficient, tested , debugged and standardized 4. Portability and reusability. 97. Compare C++ and C strings? The C type string have some problem like assignment using = is not possible, comparison of two string using == is not possible, initializing a string with another is not possible. These problems are solved in C++ by using string objects. Generic algorithms like fine(), replace(), sort() etc are also available for operations on string objects in C++. St Josephs College of Engineering ISO 9001:2008 Page 85 of 86
Department of CSE
2012-2013 98. Write functions that can help us in finding out different characteristics of the string object? String characteristics can be found out using built in functions available. 1. The empty() which checks if the string object contains any data . ex st1.empty() to check if st1 is an empty string object. The function returns a Boolean value. If it returns 1 if the function is empty , else it returns 0. 2. The size() function returns the size of the string 3. The max_size() gives the maximum permissible size of a string in a given system. 4. The resize() which resizes the string by the number supplied as argument. 99. List out different substring operations for string object? The following are some substring operations in C++ 1. Find location of a substring or a character in a given string. 2. Find the character at a given location in a given string. 3. Insert a specific substring at a specific place. 4. Replacing specific characters by other characters. 100.What is the advantages of using generic algorithm? Some distinct advantages of using generic algorithms are 1. Programmers are freed from writing routines like sort(), merge(), binary_search(), find() etc. They are available as readymade from STL. 2. The algorithm use the best mechanisms to be as efficient as possible; desighing which may not be possible for most of the programmers.
Page 86 of 86