QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 – OBJECT ORIENTED PROGRAMMING UNIT – I PART -A (2 Marks) 1. Differentiate between an object and a class. (AUC DEC 2012) Classes are templates of objects. Objects are instances of classes. Using one single class, we can create multiple objects. A class is a static piece of code that consists of attributes which don’t change during the execution of a program – like the method definitions within a class. Objects are created and eventually destroyed – so they only live in the program for a limited time. 2. What is an abstract class in C++? (AUC DEC 2012) Abstract classes act as expressions of general concepts from which more specific classes can be derived. You cannot create an object of an abstract class type; however, you can use pointers and references to abstract class types. A class that contains at least one pure virtual function is considered an abstract class. Classes derived from the abstract class must implement the pure virtual function or they, too, are abstract classes. 3. Define abstraction and encapsulation.(AUC MAY 2012) The insulation of data from direct access by the program is called as data hiding or information binding. Wrapping up of data and function within the structure is called as encapsulation. 4. When will the destructors be called? Is it explicit or implicit?(AUC MAY 2012) It is used to destroy the objects that have been created by constructor. Destructor name is same as class name preceded by tilde symbol (~) A destructor never takes any arguments nor it does it return any value. The compiler upon exit from the program will invoke it. Whenever new operator is used to allocate CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 1 memory in the constructor, we should use delete to free that memory. It is implicit. 5. What is the difference between a pointer and a reference? (AUC DEC 2011) A pointer takes the address of an item and remains pointing at that same location until explicitly changed. A reference is more like an alias of the item, it behaves as if it is the item. If the item changes the reference changes and vice versa. 6. What are copy constructors?(AUC DEC 2011) A copy constructor is used to declare and initialize an object from another object. It takes a reference to an object of the same class as an argument Eg: integer i2(i1); would define the object i2 at the same time initialize it to the values of i1. Another form of this statement is Eg: integer i2=i1; The process of initializing through a copy constructor is known as copy initialization. 7. What is the ambiguity between default constructor and default argument constructor? (AUC DEC 2010) The default argument constructor can be called with either one argument or no arguments. When called with no arguments, it becomes a default constructor. When both these forms are used in a class, it cause ambiguity for a statement such as A a; The ambiguity is whether to call A::A() or A::A(int i=0) 8. Write a copy constructor for class date (assume mm, dd, yy as its members) (AUC DEC 2010) date::date(date &d) { mm=d.mm; dd=d.dd; yy=d.yy; } CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 2 9. What is the difference between call by value and call by reference? AU MAY 2014 10. What are inline functions? An inline function is a function that is expanded in line when it is invoked. That is compiler replaces the function call with the corresponding function code. The inline functions are defined as Inline function-header { function body } 11. What are the access specifiers in C++? Access specifiers defines the access rights for the statements or functions that follows it until another access specifier or till the end of a class. The three types of access specifiers are "private", "public", "protected". private: The members declared as "private" can be accessed only within the same class and not from outside the class. public: The members declared as "public" are accessible within the class as well as from outside the class. protected: The members declared as "protected" cannot be accessed from outside the class, but can be accessed from a derived class. This is used when inheritance is applied to the members of a class. 12. What is the difference between a class and a structure? A struct is a value type and a class is a reference type. When we instantiate a class, memory will be allocated on the heap and when struct gets initiated it gets memory on the stack. Classes can have explicit parameter less constructors. But structs dosn't have this. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 3 Classes support inheritance. No inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces. 13. Define function overloading? AU MAY 2013 Function overloading means we can use the same function name to create functions that perform a variety of different tasks. Eg: An overloaded add ( ) function handles different data types as shown below. // Declarations i. int add( int a, int b); //add function with 2 arguments of same type ii. int add( int a, int b, int c); //add function with 3 arguments of same type iii. double add( int p, double q); //add function with 2 arguments of different type //Function calls add (3 , 4); //uses prototype ( i. ) add (3, 4, 5); //uses prototype ( ii. ) add (3 , 10.0); //uses prototype ( iii. ) 14. What is the purpose of friend function? How it is used? A function that has access to the private member of the class but is not itself a member of the class is called friend functions. The general form is friend data_type function_name( ); Friend function is preceded by the keyword ‘friend’. 15. Explain the functions of default constructor? A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization. Also it can be used for memory allocation. 16. What is the purpose of scope resolution operator? Scope resolution operator is used to uncover the hidden variables. It also allows access to global version of variables. Eg: #include<iostream. h> int m=10; // global variable m void main ( ) { int m=20; // local variable m cout<<”m=”<<m<<”\n”; cout<<”: : m=”<<: : m<<”\n”; } CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 4 output: 20 10 (: : m access global m) Scope resolution operator is used to define the function outside the class. Syntax: Return type <class name> : : <function name> Eg: Void x : : getdata() 17. How objects can be used as arguments? This can be done in two ways • A copy of the entire object is passed to the argument • Only address of the objects is transferred to the f unction 18. What is dynamic binding? When it is used? Binding refers to the linking of a procedure to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at the run-time. 19. Justify the need for static members. Static data members are initialized to zero when the first object is created. No other initialization is permitted • only one copy of that member is created for the entire class and is shared by all the objects • It is only visible within the class, but its life time is the entire class type and scope of each static member variable must be defined outside the class • It is stored separately rather than objects 20. How is dynamic initialization of objects achieved? Dynamic initialization means the first value assigned to the variable after memory allocation is not known at compile time, it is evaluated only at run time. PART –B (16 Marks) 1. (i) Explain the characteristics of OOPS in detail. (8) (AUC DEC 2012,13) • • • • • • Emphasis is on data rather than procedure. Programs are divided into what are known as objects. Data structures are designed such that they characterize the objects. Functions that operate on the data of an object are tied together in the data structure. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 5 • • New data and functions can be easily added whenever necessary. Follows bottom-up approach in program design. (ii) Write a C++ program to generate Fibbonacci using Copy constructor. (8) (AUC DEC 2012) 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++) { CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 6 number.display(); number.increment(); } } 2. (i) What is polymorphism? Explain different types of polymorphism. (8) AU MAY 2014 Polymorphism is the phenomenon where the same message sent to two different objects produces two different set of actions. Polymorphism is broadly divided into two parts: • Static polymorphism – exhibited by overloaded functions. • Dynamic polymorphism – exhibited by using late binding. Static Polymorphism Static polymorphism refers to an entity existing in different physical forms simultaneously. Static polymorphism involves binding of functions based on the number, type, and sequence of arguments. The various types of parameters are specified in the function declaration, and therefore the function can be bound to calls at compile time. This form of association is called early binding. The term early binding stems from the fact that when the program is executed, the calls are already bound to the appropriate functions. The resolution of a function call is based on number, type, and sequence of arguments declared for each form of the function. Consider the following function declaration: void add(int , int); void add(float, float); When the add() function is invoked, the parameters passed to it will determine which version of the function will be executed. This resolution is done at compile time. Dynamic Polymorphism Dynamic polymorphism refers to an entity changing its form depending on the circumstances. A function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are resolved dynamically when the program is executed. The term late binding refers to the resolution of the functions at run-time instead of compile time. This feature increases the flexibility of the program by allowing the appropriate method to be invoked, depending on the context. Static Vs Dynamic Polymorphism Static polymorphism is considered more efficient, and dynamic polymorphism more flexible. Statically bound methods are those methods that are bound to their calls at compile time. Dynamic function calls are bound to the functions during run-time. This involves the additional step of searching the functions during run-time. On the other hand, no run-time search is required for statically bound functions. As applications are becoming larger and more complicated, the need for flexibility is increasing rapidly. Most users have to periodically upgrade their software, and this could become a very tedious task if static polymorphism is applied. This is because any change in requirements requires a major modification in the code. In the case of dynamic binding, the function calls are resolved at run-time, thereby giving the user the flexibility to alter the call without having to modify the code. To the programmer, efficiency and performance would probably be a primary concern, but to the user, flexibility or maintainability may be much more important. The decision is thus a trade-off between efficiency and flexibility. (ii) Write a C++ program to implement Dynamic memory allocation. (8) (AUC DEC 2012) CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 7 Allocation of memory at the time of execution (run time) is known as dynamic memory allocation. The functions calloc() and malloc() support allocating of dynamic memory. Dynamic allocation of memory space is done by using these functions when value is returned by functions and assigned to pointer variables. New and delete operators are used for dynamic memory allocation. #include <iostream> #include <new> using namespace std; int main () { int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new (nothrow) int[i]; if (p == 0) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n++) { cout << "Enter number: "; cin >> p[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << p[n] << ", "; delete[] p; } return 0; } 3. Explain in detail about Classes, Objects, Methods and Messages. (AUC MAY 2012) Objects: Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data. An Object is a collection of data members and associated member functions also known as methods. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 8 Classes: Classes are data types based on which objects are created. Objects with similar properties and methods are grouped together to form a Class. Thus a Class represent a set of individual objects. Characteristics of an object are represented in a class as Properties or messages. The actions that can be performed by objects becomes functions of the class and is referred to as Methods. For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object functions like Start, Move, Stop form the Methods of Car Class. 4. Write a C++ program to define overloaded constructor to perform string initialization, string copy and string destruction.(AUC MAY 2012) CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 9 5. (i) Explain the basic OOP concepts. (10) Objects Classes Data abstraction and encapsulation Inheritance Polymorphism Dynamic binding Message passing Objects Objects are the basic real-time entities in an object oriented design. It consists of data, user-defined data and functions to deal those data. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 10 Programming problem is analyzed in terms of objects and the communication between them. They match closely with the real-time objects. Objects can interact with each other easily. Classes It is a user-defined data type which consists of set of data and functions. Using a single class, we can create many numbers of objects. Objects are the variables of the type class. Class is a collection of objects of similar type. For example, mango, apple and guava are members of the class fruit. Consider, fruit apple; where fruit is a class and apple is an object to it. Data Abstraction and Encapsulation The wrapping up of data and functions into a single unit is known as encapsulation. The data is not accessible to the outside world, and only those functions which are inside the class can access. These functions provide the interface between the object’s data and the program. The insulation of the data from direct access by the program is called as data hiding. Abstraction is the concept of representing essential features without including the background details or explanations. Classes uses this concept and are defined as a list of abstract attributes such as size, weight and cost and functions to operate on these attributes. Those functions are said to be methods. Since the classes use the concept of data abstraction, they are known as Abstract Data CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 11 Types. Inheritance It is the process by which objects of one class acquire the properties of objects of another class. This concept provides the idea of ‘reusability’ which enables us to add the additional features to the existing content. This is possible by deriving a class from the existing class. The new class will have the combined features of both the classes. From the bird class, flying bird and non-flying bird classes are derived. Note that each class defines only those features that are unique to it. Polymorphism It means the ability to take more than one form. A single operation may exhibit different behaviors in different situations. For example, addition operation can be used to add two numbers and also to combine two strings. This process is said to be operator overloading. A single function name can be used for multiple functions which can be differentiated using different number and different types of arguments. This is called as function overloading. Polymorphism allows the objects to have different internal structures to share the same external interface. It is useful in implementing the inheritance. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 12 Dynamic binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with the given procedure call is not known until the time of the call at run time. This is associated with inheritance and polymorphism. Consider the procedure ‘draw’ in figure 1.9. Inheritance is used and ‘draw’ has to be redefined in every object. At run-time, the code matching the object will be called. Message passing An object-oriented program consists of a set of objects that communicate with each other. It involves: 1. Creating classes that define objects and their behavior. 2. Creating objects from class definitions. 3. Establishing communications among objects. A message for an object is a request for execution of a procedure and so the corresponding code will be invoked. Overloading Overloading is one type of Polymorphism. It allows an object to have different meanings, depending on its context. When an exiting operator or function begins to operate on new data type, or class, it is understood to be overloaded. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 13 (ii) Write a C++ program that will ask for a temperature in Fahrenheit and display it. (6) (AUC DEC 2011) #include <iostream> int main() { float fahrenheit; cout << "Enter temperature in Fahrenheit: "; cin >> fahrenheit; cout << "Fahrenheit = " << fahrenheit << endl; return 0; } 6. (i) Illustrate the concept of function overloading to find the maximum of two numbers.(10) (AUC DEC 2011) #include<iostream> using namespace std; int max1(int a,int b); int max2(int a,int b,int c); float max3(float a,float b,float c); int main() { int result=max1(11,123); cout<<"The maximum number between 11 and 123 is "<<result; result=max2(121,22,55); cout<<"\nThe maximum number between 121, 22 and 55 is "<<result; float fresult=max3(34.34,22.11,55.01); cout<<"\n The maximum number between 34.34,22.11 and 55.01 is "<<fresult; } int max1(int a, int b) { if (a>b) return a; else return b; } int max2(int a,int b,int c) { CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 14 int highest; if (a>b) highest= a; else highest=b; if(c>highest) highest=c; return highest; } float max3(float a,float b,float c) { float highest; if (a>b) highest= a; else highest=b; if(c>highest) highest=c; return highest; } Output The maximum number between 11 and 123 is 123. The maximum number between 121, 22 and 55 is 121. The maximum number between 34.34, 22.11 and 55.01 is 55.01. (ii) What are inline functions? Write a sample code to explain it. (6) (AUC DEC 2011) Functions are used to save memory space. Suppose, the function is small, the time needed to execute that is greater than the actual time. In such cases, the inline function is used. Inline function is function that is expanded in line when it is invoked. The compiler replaces the function call with the corresponding function code. It helps to achieve the faster execution. inline function-name { function body } inline double cube(double a) { return(a*a*a); } c=cube(3.9); g=cube (1.2,5.6); The inline function is good enough until the code is smaller. Once the size grows, the purpose of inline function may be lost. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 15 The inline keyword sends a request to the compiler, not the command. Once the function definition is too long, the compiler rejects this request and takes it as a normal function. Some situations where inline expansion may not work: 1. 2. 3. 4. For functions returning values, if a loop, a switch, or a goto exists. For functions not returning values, if a return statement exists. If functions contain static variables. If inline functions are recursive. 7. Write a C++ program to perform 2D matrix operations as follows: (i) Define class matrix, use appropriate constructors. (5) (ii) Define methods for the following two matrix operations: determinant and transpose. (6) (iii) Write a main program to demonstrate the use of the matrix class and its methods. (5)(AUC DEC 2010) #include<iostream.h> #include<conio.h> class Matrix { private: int rowSize; int colSize; int **data; public: Matrix() CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 16 { } Matrix(int r,int c) { rowSize=r; colSize=c; data=new int*[rowSize]; for(int i=0;i<rowSize;i++) data[i]=new int[colSize]; } Matrix(const Matrix& obj) { rowSize=obj.rowSize; colSize=obj.colSize; data=new int*[rowSize]; for(int i=0;i<rowSize;i++) data[i]=new int[colSize]; for(i=0;i<rowSize;i++) { for(int j=0;j<colSize;j++) { data[i][j]=obj.data[i][j]; } } } ~Matrix() { for(int i=0;i<rowSize;i++) delete data[i]; delete[] data; } Matrix& operator=(Matrix &obj); Matrix& operator+(Matrix m1); void getMatrix(); void displayMatrix(); }; Matrix& Matrix::operator=(Matrix &obj) { rowSize=obj.rowSize; colSize=obj.colSize; data=new int*[rowSize]; for(int i=0;i<rowSize;i++) data[i]=new int[colSize]; for(i=0;i<rowSize;i++) { for(int j=0;j<colSize;j++) { CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 17 data[i][j]=obj.data[i][j]; } } return *this; } Matrix& Matrix::operator+(Matrix m1) { static Matrix temp(rowSize,colSize); for(int i=0;i<rowSize;i++) { for(int j=0;j<colSize;j++) { temp.data[i][j]=this->data[i][j]+m1.data[i][j]; } } return temp; } void Matrix::getMatrix() { for(int i=0;i<rowSize;i++) { for(int j=0;j<colSize;j++) { cin>>data[i][j]; } } } void Matrix::displayMatrix() { for(int i=0;i<rowSize;i++) { cout<<"\n"; for(int j=0;j<colSize;j++) { cout<<data[i][j]<<"\t"; } } cout<<endl; } int main() { clrscr(); cout<<"Enter 2 - 2x2 matix elements"; Matrix m1(2,2); Matrix m2(2,2); m1.getMatrix(); m2.getMatrix(); Matrix m3; CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 18 cout<<endl<<"Matrix 1\n"; m1.displayMatrix(); cout<<"Matrix 2\n"; m2.displayMatrix(); m3=m1+m2; cout<<"Result +\n"; m3.displayMatrix(); getch(); return 0; } 8. Explain the features of object oriented programming. Describe how each of these implemented in C++ and Java. (AUC DEC 2010) [Refer Q.No: 3] 9. Explain different types of constructor with example. Default Constructors A constructor that accepts no parameter is called default constructor. The default constructor for class A is A::A(). If no such constructor is defined then the compilers supplies a default constructor. Therefore statement such as Aa; invokes the default constructor of the compiler to create the object a. Parameterized constructors The constructors that can take arguments are called parameterized constructors. class integer { int m,n; public: integer(int x, int y); // parameterized constructor ….. }; integer::integer(int x, int y) { m=x;n=y; } We should pass the initial value as arguments to the constructor function when an object is declared. This is done in two ways. By calling the constructor implicitly By calling the constructor explicitly integer int1=integer(0,100); //explicit call integer int1(0,100); //implicit call Implicit call is called shorthand method, which is easy to implement. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 19 The parameters of a constructor can be of any type except that of the class to which it belongs. For example, class A { …. …. public: A(A); } A constructor can accept a reference to its own class as a parameter. Example: A(A&); This is said to be copy constructor. Multiple constructors in a class Constructors can be overloaded as follows: CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 20 The declaration integer i1; invokes first constructor and set m and n to zero. The statement integer i2(20,40); invokes second constructor and initialize data members m and n to 20 and 40. The statement integer i3(i2); invokes third constructor which copies the values of i2 into i3. The last constructor is called copy constructor. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 21 There are three constructors in the class complex. The first constructor which takes no arguments, is used to create objects which are not initialized. The second which takes one argument is used to create objects and initialize them. The third which takes two arguments is used to create objects and initialize them to specific values. The first constructor complex() { } It contains the empty body and does not do anything. It is used to create objects without any initial values. It is used to avoid ambiguity. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 22 We must define this ‘do-nothing’ constructor to satisfy the compiler. Copy constructor It is used to declare and initialize an object from another object. Ex: integer i2(i1); Another form is: integer i2=i1; The process of initializing through a copy constructor is called as copy constructor. But, the statement i2=i1; would not invoke copy constructor and it simply initializes i2 with i1 values. [operator overloading]. A copy constructor takes a reference to an object of the same class as itself as an argument. A reference variable has been used as an argument to the copy constructor. We cannot pass the argument by value to a copy constructor. When no copy constructor is defined, the compiler supplies its own copy constructor. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 23 10. (i) Explain with example how destructors are used. A destructor is used to destroy the objects that have been created using constructors. It is also a member function with the same name as class name preceded by a tilde. For example, the destructor for the class integer can be given as: ~integer() { } A destructor can never take any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program to clean up storage that is no longer accessible. Whenever new operator is used to allocate memory, we should use delete operator to free that memory. matrix:: ~matrix() { for(int i=0;i<d1;i++) delete p[i]; delete p; } This is required because when the pointers to objects go out of scope, a destructor is not called implicitly. CS2311 OBJECT ORIENTED PROGRAMMING - V Sem 24 25 CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE (ii) With example, explain how functions are used with default arguments. The function can assign a default value to the arguments and for that, there will be no matching argument in the function call. The compiler searches for the exact match and then check with the default arguments. Example: float amount(float principal, int period, float rate=0.15); For this function call can be: amount(1000,2); We can also call as amount(2000,3, 0.12); in which rate value is over-written. Default arguments can be given only to the trailing arguments. Example: int mul(int i, int j=9, int k=10); int mul(int i=5, int j=6, int k=7); int mul(int i=1, int j, int k=3); //illegal 26 CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE int mul(int 1=2, int j); //illegal It provides greater flexibility to the programmers is cases like, constant bank interest for all account holders. Advantages: 1. We can add parameters to the existing functions. 2. Used to combine similar functions into one. 11. With program, illustrate how static data members and member functions are implemented. static Data Members Static variables are normally used to maintain values common to the entire class. Some special characteristics are: 1. It is initialized to zero when the first object is created. No other initialization permitted. 2. Only one copy of that member is created for the entire class and shared by all objects. 27 CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE 3. It is visible only within the class, but its lifetime is the entire program. The type and scope of each static member variable must be defined outside the class definition, as the static data members are stored separately. They are associated with the class itself, and so said to be class variables. In the above program, every time count value is incremented because a single copy of count value is available. While defining a static variable, some initial value can be assigned. Example: int item::count=10; Static Member Functions Used to access the static data members. It can be called using the class name. class-name :: function-name; 28 CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE 29 CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE 30 CS2311 OBJECT ORIENTED PROGRAMMING - V Sem EEE – M.Sathya Asst.Prof./CSE