OOP Concepts Test Questions Set 1

1)   A copy constructor is called

a. when an object is returned by value
b. when an object is passed by value as an argument
c. when compiler generates a temporary object
d. all the above
Answer  Explanation 

ANSWER: all the above

Explanation:
Copy constructor is a type of constructor which is used for creating a new object that is an exact copy of the existing object. In general compiler creates a copy constructor for each and every class on its own but in special case( when object has pointers involved) copy constructor is created by the programmer. It is called in all the above cases.


2)   Which property of Object Oriented Programming is exhibited by the code:

#include< iostream>
class quest
             {
                public:
            float add( float a, float b)
            {
              cout << “The sum is:”;
               reurn(a+b); }   }
           int add( int a, int b, int c)
           {
  cout << ”The sum is:”;
               return(a+b+c);
             }

          int add( int a, int b=0)
           {
              cout << ”The sum is:”;
              return(a+b);
               }
            };
           int main( )

           {
  quest q
              q. add( 50.5, 48.2)
              q. add( 42, 56, 82)
              q. add( 23)
               return 0;
              }


a. Compile time polymorphism
b. Run time polymorphism
c. Both
d. none
Answer  Explanation 

ANSWER: Compile time polymorphism

Explanation:
The property of function overloading is also known as Compile time polymorphism. Here in this code we see how a function is overloaded using different datatype, different number of arguments and default argument. Function overloading is a concept which allows the use of same function name to different functions for performing same or different task in the same class.


3)   Give output of the following:

#include <iostream>
            using namespace std;

class exam
            {     private:
                  int x, y, z;
               public:
               int testcase( )

             {
                x=50; y=20; z=30;
                 }
               friend int add( exam e);
             };

            int add( exam e)
             {

                   return int( e.x+ e.y+ e.z);
                    }
              int main( )
           {
  exam a;
  a.testcase( );
              cout << add(a);
              return 0;

               }


a. 0
b. compile time error
c. 100
d. none
Answer  Explanation 

ANSWER: compile time error

Explanation:
This code shows usage of a friend function and how a friend function has access to private members of a class. Generally a function defined outside the class cannot access the private and protected members of the class but by declaring a function as friend function the class gives it permission to access its private and protected data.


4)   Why is user defined copy constructor required?

a. there is no implicit copy constructor in C++
b. when pointers are involved implicit copy constructor does not give correct result
c. both a and b
d. none
Answer  Explanation 

ANSWER: when pointers are involved implicit copy constructor does not give correct result

Explanation:
C++ has an implicit copy constructor which is called by compiler to keep a copy of the object. In case where pointers are present in the code and programmer is not using user defined copy constructor then a problem occurs. The problem is that whenever a copy constructor is called( implicit or user defined) the copy destructor is also called to delete the copy at the end of scope. Implicit copy constructor copies an object bit by bit so pointer address will be copied causing in two different objects sharing same memory location. When the first object calls the destructor to deallocate the pointer no problem occurs but when second object does so it tries to deallocate a pointer that does not exist anymore and the application stops working. In order to prevent situations like this user defined copy constructor is called.


5)   Virtual keyword is used

a. to remove static linkages
b. to call function based on kind of object it is being called for
c. to call the methods that don't exist at compile time
d. all the above
Answer  Explanation 

ANSWER: all the above

Explanation:
All the options are correct as virtual is the keyword used with function of base class then all the functions with same name in derived class, having different implementations are called instead of base class function being called each time.

Compiler creates vtables for each class with virtual function so whenever an object for the virtual classes is created compiler inserts a pointer pointing to vtable for that object. Hence when the function is called the compiler knows which function is to be called actually.

Example:

class geom
{

public:

virtual void show( )
{
cout << ” the area is: x” << endl;
}
};

class rect: public geom
{
void show( )
{
cout << ”the area is: y” << endl;
}
};
int main( )
{
geom* a;
rect b;
a= &b;
a - > show( );
}

output:
the area is: y


6)   Dynamic dispatch is a feature that

a. selects which polymorphic operation to call at run time
b. selects which polymorphic operation to call at compile time
c. Both a and b
d. None
Answer  Explanation 

ANSWER: selects which polymorphic operation to call at run time

Explanation:
Dynamic dispatch also known as message passing is a process of selecting a procedure to run in response to a method call by looking for the method (function) in the table associated with the object, at run time. It distinguishes an object from a module which has fixed implementations for all instances i.e. static dispatch. Dynamic dispatch has usage in Object oriented programming languages when different classes have different implementations of same function call due to inheritance.

For example there are three classes. Class X- the base class, Class Y and Class Z- the derived class and all of them have a function call- show( ), then dynamic dispatch selects which implementation of function to call at run time.


7)   Encapsulation helps

a. information hiding
b. in providing low coupling
c. in providing high cohesion
d. All the above
Answer  Explanation 

ANSWER: All the above

Explanation:
Encapsulation works on providing interactions through function calling only. Using keyword private or protected stops the use of data members outside class. The data thus remains accessible to functions inside class. Encapsulation is also called information hiding as it restricts the use of data inside class. Coupling is the degree of interdependence between different blocks( modules) of program code. Low coupling helps in keeping data safe inside the class. Coupling contrasts cohesion as with high cohesion comes reliability and reusability in a code.


8)   The keyword 'this' is used

a. As reference to current object
b. Explicit constructor invocation
c. In open recursion
d. All the above
Answer  Explanation 

ANSWER: All the above

Explanation:
In object oriented programming the keyword 'this' is used to refer to objects, classes or any other entity that is part of currently running code. Different languages use it in different ways.

In some languages, 'this' is the only way to access data and methods in current object. The concept, however, is similar in all languages using 'this'.It is usually a fixed reference or pointer which refers to current object. In some languages it is used explicitly while others use lexical scoping( range of functionality) to use it implicitly to make symbols within their class visible. The dispatch semantics of 'this' that method calls on 'this'are dynamically dispatched which means that these methods can be overriden by derived classes or objects.


9)   An Abstract class

a. allows normal method declaration within
b. can be instantiated
c. Must have abstract methods with implemetation within
d. none
Answer  Explanation 

ANSWER: allows normal method declaration within

Explanation:
Abstraction is the process of hiding implementation details and showing only functionality to the user. Classes that are declared with keyword abstract are called abstract classes. It cannot have any instances. It can carry normal functions declaration and definition along with abstract functions though the abstract methods(functions) cannot be defined inside the abstract class.For defining abstract methods subclasses are needed. Any class that extends the abstract class must implement all abstract methods declared by the super class.


10)   Function Templates can have

a. Explicit instantiation definition with template argument for all parameters
b. explicit instantiation of declaration with template argument for all parameters
c. Both a and b
d. None
Answer  Explanation 

ANSWER: Both a and b

Explanation:
A function template cannot be defined as a type or a function in itself. There is no such coding available that contains only template definitions generated from a source file. A template must have real instance i.e. template arguments must be determined such that the compiler generates an actual function. Here both first and second options are correct. An explicit formation of instance definition forces instantiation of member functions. For instantiating a function template all template arguments must be known.


11)   Function templates are considered equivalent when

a. Declared in same scope
b. Having same name
c. Having identical return type and parameter list
d. All of the above
Answer  Explanation 

ANSWER: All of the above

Explanation:
Function overloading performs similar operations on different data types. Thus if similar operations are to be executed on all data types, function templates gives an easy solution for the same. Function template is defined with keyword 'template' followed by a parameter list. Each parameter has typename and can be of built-in or user defined type. Also, the number of parameters must not exceed eight. All the given options in the question above are hence true.


12)   Pure virtual function is used

a. to give meaning to derived class function
b. to give meaning to base class function
c. to initialize all functions
d. None
Answer  Explanation 

ANSWER: to give meaning to base class function

Explanation:
When we use virtual keyword our base class function becomes meaningless as it has no use. It only helps in calling all derived class functions of same name. If base class function is initialized with =0, it is known that function has no body and thus the virtual function of base class becomes pure virtual function.

For example:

class geom
{
public:
virtual void show( )=0;
};

class rect: public geom
{
void show( )
{
cout << " the area is : y" << endl;
}
}


13)   Use of preprocessor directive in OOP

a. for conditional compilation
b. for macro expansion
c. error and warning reporting
d. all the above
Answer  Explanation 

ANSWER: all the above

Explanation:
Preprocessor is a program that processes an input to produce an output which is used as another programs input. The preprocessor directives are generally invoked by the compiler to process before compilation. The preprocessor directive are capable of performing simple textual substitutions, macro expansion, conditional compilation, warning and error reporting. It begins with special character # followed by directive name. Preprocessor directive statement does not end with a semi colon. Few examples of preprocessor directives are:

#include, #define, #undef, #if, #elif, #else, #endif, #line etc. It is used in various OOP languages like C, C++, C#. It has no use in Java.


14)   Abstract class vs Interface

a. A class may inherit only one abstract class but may inherit several interfaces.
b. An abstract class can provide complete and default code but an interface has no code
c. both a and b
d. none
Answer  Explanation 

ANSWER: both a and b

Explanation:
Abstract class and interface are generally confused to be the same but they are actually not the same. An abstract class cannot have its own instance but can have functions declared and defined inside it( normal functions). Abstract methods(functions) can only be declared inside an abstract class so in order to complete the functionality we need a subclass where the abstract functions can be defined(implemented). The functions which are only declared inside abstract class and not defined i.e. having incomplete functionality are written with keyword abstract and if an abstract class has only incomplete functions within then it is same as an Interface. Interface is not a class but an entity and it just has definition of functions with no implement ion. It is basically created to be overridden by implemented classes.


15)   Constructor chaining is

a. subclass constructor calling super class constructor
b. super class constructor calling subclass constructor
c. both
d. none
Answer  Explanation 

ANSWER: subclass constructor calling super class constructor

Explanation:
In Inheritance subclass or derived class inherits properties of super class or parent class. Constructor chaining is the property by which a constructor in derived class(s) can call constructor of parent class(s). In constructor chaining, when an object of derived class is created its constructor is called which further calls the constructor method of parent class. The keyword super in java helps in passing arguments to super class constructor. The creation of subclass object starts with initialization of class(s) above it in inheritance chain. There could be any number of classes in the inheritance chain. Every constructor function will call up the chain till the top most class is reached.

For Example:

public class animal
{
private string str;
public animal( string str)
{
this.name= name;
system.out.println(“I am an Animal”);
}
}
public class lion extends animal
{
public lion( string str)
{
super(str);
system.out.println(“I am a lion”);
}
}


16)   Invoking methods characteristics

a. methods can be invoked in any order and calling method should be in same class as worker method
b. Worker method and calling method can be invoked in same way
c. Any method can call any method

Answer  Explanation 

ANSWER: methods can be invoked in any order and calling method should be in same class as worker method

Explanation:
Methods can be invoked in any order. Methods do not need to be completed in the order in which they are listed in the class where they are declared. The way you invoke a worker class is different based on whether they are present in same class or different class there is no limit in number of method calls that a calling method can make. The calling method and worker can be in same class or different class. There are privately defined methods and so cannot be called by method in any other class.


17)   Which Java.Lang contains only static methods?

a. Math ,System
b. Number,Exception
c. There is no such class
d. none
Answer  Explanation 

ANSWER: Math ,System

Explanation:
System and Math are only two classes that do not have any method that does operation on the object of any class where they are used. Hence it has all methods as static. System class contains utility methods for handling operating system specific task and they do not operate on object instance. For example the getproperties() method of the System class gets the information about computer. The math class uses the utility methods for math operations. Such as exponential,logarithmic,random etc. All other classes have method/methods which operate on object of the class.


18)   Overloaded methods in java

a. Compiler uses method signature to determine which method to invoke. They may have different functionality
b. They are not available in fundamental classes
c. They have the same name and signature

Answer  Explanation 

ANSWER: Compiler uses method signature to determine which method to invoke. They may have different functionality

Explanation:
To invoke the overloaded methods the compiler compares the method signature in the method invocation against the method signature in the class. Overloaded methods are widely used in the fundamental pre-written class libraries in java. Java class can have several methods with same name but different arguments so that the signature is different.


19)   Fallthrough in a switch case statement

a. prevents the next case after the matching block to be executed
b. Allows the next case after the matching block to be executed
c. no fallthorugh occurs in switch case
d. none
Answer  Explanation 

ANSWER: Allows the next case after the matching block to be executed

Explanation:
When break statement is not present in the switch case code block, after executing the matching block the execution continues to execute the next case(fallthrough). Thus fallthrough is a situation which allows multiple values to match the same point without any special syntax. In practice, the break statement after execution of the required code(matching block) exits the switch block. This prevents the fallthrough. C# is a language that has made usage of break statement in coding , a mandatory. Compilation of code without break statement throws error and hence prevents fallthrough.


20)   Break statement in switch case

a. prevents from fallthrough
b. causes an exit from innermost loop
c. both a and b
d. none
Answer  Explanation 

ANSWER: both a and b

Explanation:
Break statement is an important statement which alters the normal flow of a program. It helps in exiting the switch case block . It is frequently used to terminate the processing of a particular case within the switch statement. Control passes to the statement that follows the terminated statement.

It also prevents fallthrough which occurs in the absence of break in the switch case. Fallthrough is a situation that leads to execution of all the cases which is possible in absence of break statement