Tuesday, March 15, 2011

COMPREHENSIVE GIDE FOR PLACEMENT PART--3


9.            What is the output of the following program?
void main(){
            vector<int> vec1,vec2;
                        vec1.push_back(12);
            vec1.push_back(13);
                        vec2.push_back(12);
            vec2.push_back(13);
                        cout << (vec1<vec2);
}
Answer:
0
Explanation:
The values contained in both the containers are equal. Therefore the comparison returns 0. Each container supports a set of comparison operators. The comparison is based on a pair-wise comparison of the elements of the two containers. If all the elements are equal and if both the containers contain the same number of elements, the two containers are equal; otherwise, they are unequal. A comparison of the first unequal element determines the less-than or greater-than relationship of the 2 containers.

10.        Consider the following lines of code:
list<int> aList;
list<int>::iterator anIterator(&aList);
what can  you say about the relationship between ‘aList’ and ‘anIterator’?
Answer:
            The class iterator is a friend of class list.
Explanation:
Iterators are always friend functions.

11.        #include <list>
#include <algorithm>
#include <iostream>
using namespace std;
void main()
{
list<int> ilist;
list<int>::iterator iiter;
for (int i=0;i<10;i++) ilist.push_back(i);
iiter = find(ilist.begin(),ilist.end(),3);
if ( *(iiter+1) ==4) cout <<"yeah ! found";
}
Output:
Compile –time error:
Explanation:
The code won’t compile because , iterators associated with list containers do not support the operator + used in the expression (*(iter+1) ==4 ), because iterators associated with list are of type bi-directional iterator, which doesn’t support the + operator.

Exercise:
1) Determine the output of the following 'C++' Codelet.
            class base{ 
            public :
                                    out() {
                                    cout<<"base "; 
                                    } 
            };
                        class deri : public base{
            public : out(){
            cout<<"deri ";
            }  
            };
                        void main(){
            deri dp[3];
                                    base *bp = (base*)dp;
                        for (int i=0; i<3;i++)
                                                (bp++)->out();
}

2)      Is there anything wrong with this C++ class declaration?
class something{
                        char *str;
                        public:
                                                something(){
                        st = new char[10];
}
~something(){
                                    delete str;
                                                  }
             };

3)      Is there anything wrong with this C++ class declaration?
                        class temp{
int value1;
mutable int value2;
public:
                        void fun(int val) const{
                        ((temp*) this)->value1 = 10;
                        value2 = 10;
                        }
};

12.        Name the four parts of a declaration.
Ø  A set of specifiers
Ø  A base type
Ø  A declarator
Ø  An optional initializer

13.        Differentiate between declaration and definition in C++.
                        A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program.
            A declaration is a definition unless:
Ø  it declares a function without specifying its body,
Ø  it contains an extern specifier and no initializer or function body,
Ø  it is the declaration of a static class data member without a class definition,
Ø  it is a class name definition,
Ø  it is a typedef declaration.
            A definition is a declaration unless:
Ø  it defines a static class data member,
Ø  it defines a non-inline member function.

14.        Differentiate between initialization and assignment
            Initialization is the process that creates the first value of an object. Assignment on the other hand is an operation that usually changes the value of an object.  Assignment is expressed using the token '=' but sometimes initialization can also be indicated with that symbol.
                       int a=12;   // Initialization
                       a=13;       // Assignment
            Initialization can also occur without the '=' token, as well. For example,
                        int a(12);
            For classes, you can define your own initialization procedure by providing constructors and your own assignment operation by providing constructors and your own assignment operation by providing an operator '=' will not be called for initialization is expressed using the '=' symbol.

15.        Find five different C++ constructs for which the meaning is undefined an for which the meaning is implementation defined.
Undefined behavior in C++
1. Access outside the bounds of an array.
            int a[10];
            int *p=&a[10];
2. Use of a destroyed object
            int &r=*new int;
            delete &r;
            r=r+1;
3. Attempting to reinterpret variables
            int i;
            *(float*)&i=1.0;       
            //Access through undeclared type
4. Casting to a type that is not the real type of the source object
            struct B {int i;}
            struct D:B{}
            B *bp=new B;
            D* dp=static_cast <D*> (bp);   //Invalid cast
5. Casting away constness of an object that was defined const
void f(int const &r)
           {
                  const_cast <int&>(r)=2;
           }
           int const i=3;
           f(i);                   // Invalid

Five implementation-defined constructs in C++
1.      Size of certain types:
                        sizeof(int);
2. Output of type_info :: name()
            std::cout<<typeid(double).name()
3. The effect of bitwise operators
            int mistery=~0;
4. The extreme values of fundamental types
           int mx = numeric_limits <int> =max()
5. The number of temporary copies
           struct s
          {
                    s(s const&)
                   {  
                             std::cout<<"copy\n ";
                    }
           }
           s f( )     
           {
                 s a;
                 return a;
            }
            int main()
           {
                f();return 0;
           }

16.        When is a volatile qualifier is required to be used?
            In certain cases, you don't want the compiler to produce optimizations. When dealing with variables that are accessible both from an interrupt servicing routine (ISR) and by the regular code, the compiler should not make any assumptions about the value of a variable from one line of code to the next. Similarly, in a multiprocessing environment, there may be other processors that have access to shared memory variables, thereby making changes to them without warning. In such cases that involve memory mapped hardware devices, you need the volatile qualifier. Volatile qualifier prevents any optimizations done on the names they qualify, making the program possible to be used in such environments.

17.        What is the use of qualifier 'mutable'?
The mutable qualifier is used to indicate that a particular member of a structure or class can be altered even if a particular structure or class variable is a const.
            Example: 
struct data
{
      char name[30];
      mutable int noOfAccesses;
      ..........
};
.........
const data d1{"some string ",0,.......};
strcpy(d1.name,"another string"); // not allowed
d1.noOfAccesses++;                     // allowed
The const qualifier to d1 prevents a program from changing d1's members, but the mutable qualifier to the accesses member shields accesses from that restriction.

18.        In c++ by default, all functions have external storage class, they can be shared across files. What are the functions to which the above statement proves false.
            Inline functions and functions qualified with the keyword static have internal linkage and are confined to the defining file.

19.        What is the ODR?
The requirement that global objects and functions either have only one definition or have exactly the same definition many times in a program is called the one definition rule(ODR).

20.        When do implicit type conversions occur?
Ø  In an arithmetic expression of mixed types. These are known as arithmetic conversions. 
Ø  In the assignment of an expression of one type to an object of another
Ø  When passing arguments to functions
Ø  Function return types.
           
21.        List the predefined conversions available in C++.
C++ supplies certain conversions for all types, and these apply to all classes as well. These include,
Ø  The trivial conversions between a class and a reference to that class.
Ø  The trivial conversion between an array of class objects and a pointer to
                         that class.
Ø  The trivial conversion from a class instance to a const class object.
Ø  The standard conversion from a pointer to a class object to the type void*.
            The compiler uses these conversions implicitly in matching argument and parameter types. 
           
22.        Define namespace.
It is a feature in c++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

32.        Is there any space(memory) associated with namespaces?
No, because namespaces simply deal with names and no space is allocated for a name within a namespace. It is a way by which variables with same name but with different usage are accommodated into a single program.

33.        What are using declarations?
It is possible to make a member of a namespace visible within a program. Using Declarations does this. For example:
namespace  MySpace{
char * FileName;
char * FileBuffer[300];
}
using MySpace::FileName;
void main(){
cin >>FileName;
}
In this example we have a namespace that consists of two data members. But we have decided to use only one of those data members. We have specified that we want to use only the member FileName.

34.        What are using directives?
Whenever we want to make all the members of a namespace visible within a given program, we use a using directive. This gives a direction to the compiler that it has to look into this namespace  for name resolution.
using namespace MySpace;
void main(){
cin >>FileName;
}
Here all the data members of the namespace MySpace are visible within the program.

35.        When does a name clash occur?
A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.

36.        How can a '::' operator be used as unary operator?
                        The scope operator can be used to refer to members of the global namespace. Because the global namespace doesn’t have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name.

37.        ANSI C++ introduces four version of casts, for four different conversions. What   are they and give their purpose.
The new casting syntax introduced are const_cast, static_cast, dynamic_cast and reinterpret_cast.
            The general syntax for ANSI C++ style casting is :
            toTypeVar = xxx_cast < toType > ( fromTypeVar );
            This casting syntax helps programmer to identify the casting that are done in program, and its purpose easily than in C, where it can be easily missed.
            const_cast is to be used to remove the const or volatileness involved with that object.
            char *str = "something";
            strlen( const_cast< const char * > str );
            // strlen requires const char * as its argument.
            It can also be used to remove the volatileness of the object, but that requirement arises very rarely.
            static_cast shall be used in all the cases where C casts are normally used.
            char *a;
            int * b = static_cast < int * > (a);
            This converts from char * to int * and this reqires static_cast.       
            dynamic_cast is used for traversing up and down in inheritance hierarchy.
            Base *bp = new Base();
            Deri *dp = dynamic_cast < Deri * > (bp);
            It should be noted that this is applicable only to 'safe casts', the types that contain the virtual functions.
            reinterpret_cast is the cast that can be applied for pointers (particularly function pointers) 
            int foo();
            void (*fp)() = reinterpret_cast< void (*)() > (foo);
            fp();
           
38.        When can you tell that a memory leak will occur?
A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory.

39.        What  is an activation record?
The entire storage area of a function is known as the activation record. This is allocated from the program’s run-time stack. This contains all the information related with the function, such as the value of the parameters passed, the value of the various local variables etc.

40.        Differentiate between a deep copy and a shallow copy?
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.

41.        Which is the parameter that is added implicitly to every non-static member function in a class?
                        ‘this’ pointer

42.        Give few important properties of ‘this’ pointer
A)    The ‘this’ pointer is an implicit pointer used by the system.
B)     The ‘this’ pointer is a constant pointer to an object.
C)    The object pointed to by the ‘this’ pointer can be de-referenced and modified.

43.        What is a dangling pointer?
A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

44.        What is an opaque pointer?
A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files.

45.        What is a smart pointer?
                        A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
            Example: 
                        template <class X> class smart_pointer{
                        public:
                                    smart_pointer();                          // makes a null pointer
                                    smart_pointer(const X& x)            // makes pointer to copy of x
                                    X& operator *( );
                                    const X& operator*( ) const;
                                    X* operator->() const;
                                    smart_pointer(const smart_pointer <X> &);
                                    const smart_pointer <X> & operator =(const smart_pointer<X>&);
                                    ~smart_pointer();
                        private:
                                    //...
                        };
                        This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
            smart_pointer <employee> p= employee("Harris",1333);
                        Like other overloaded operators, p will behave like a regular pointer,
                                    cout<<*p;
                                    p->raise_salary(0.5);

46.        How will you decide whether to use pass by reference, by pointer and by value?
                        The selection of the argument passing depends on the situation.
            If a function uses passed data without modifying it,
Ø  If the data object is small, such as a built-in data type or a small structure then pass it by value.
Ø  If the data object is an array, use a pointer because that is the only choice. Make the pointer a pointer to const.
Ø  If the data object is a good-sized structure, use a const pointer or a const reference to increase program efficiency. You save the time and space needed to copy a structure or a class design, make the pointer or reference const.
Ø  If the data object is a class object, use a const reference. The semantics of class design often require using a reference. The standard way to pass class object arguments is by reference.
A function modifies data in the calling function,
Ø  If the data object is a built-in data type, use a pointer. If you spot a code like fixit(&x), where x is an int, its clear that this function intends to modify x.
Ø  If the data object is an array, use the only choice, a pointer.
Ø  If the data object is a structure, use a reference or a pointer.
Ø  If the data object is a class object, use a reference.
           
47.        Describe the main characteristics of static functions.
                        The main characteristics of static functions include,
Ø  It is without the a this pointer,
Ø  It can't directly access the non-static members of its class
Ø  It can't be declared const, volatile or virtual.
Ø  It doesn't need to be invoked through an object of its class, although for convenience, it may.             

48.        Will the inline function be compiled as the inline function always? Justify.
                        An inline function is a request and not a command. Hence it won't be compiled as an inline function always.
                        Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.

49.        Define a way other than using the keyword inline to make a function inline.
                        The function must be defined inside the class.

50.        What is name mangling?
                        Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.
            Example:
                        In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration:
                        class Bar{
                        public:
                                    int ival;
                                    ...
                        };
                        ival becomes something like:
                                    // a possible member name mangling
                                    ival__3Bar
                        Consider this derivation:
                        class Foo : public Bar { 
                        public:
                                    int ival;
                                    ...
                        }
                        The internal representation of a Foo object is the concatenation of its base and derived class members.
                        // Pseudo C++ code
                        // Internal representation of Foo
                        class Foo{
                        public:
                                    int ival__3Bar;
                                    int ival__3Foo;
                                    ...
                        };
                        Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).  

51.        Name the operators that cannot be overloaded.   
sizeof    .          .*         .->       ::           ?:

52.        List out the rules for selecting a particular function under function overloading.
Ø  An exact match is better than a trivial adjustment.
Ø  A trivial adjustment (e.g. adding const qualification and/or decaying an array to a pointer to its first element) is preferred over an integral promotion.
Ø  Integral promotion - such as conversion from char to int - beat other standard conversions.
Ø  Standard conversions are better than user defined conversions.
Ø  Matching ellipsis arguments is the worst kind of match.

53.        What is the dominance rule?
           The dominance rule states that if two classes contain the function searched for, and  if one class is derived from the another, the derived class dominates.

54.        List out the factors for distinguishing overloaded functions
Ø    The functions must contain a different number of arguments,
Ø    At least one of the arguments must be different.
The return type of a function is not a factor in distinguishing overloaded functions.

55.        Define the intersection rule for overloaded operators.
For overloaded functions with more than one parameter, argument matching is more complex. So, the intersection rule was adopted which uses the following procedure:
1. For each argument in the invocation, determine the set of function definitions that contain the best matches for that argument's type.
2. Take the intersection of these sets, and if the result is not a single definition, then the call is ambiguous.
3. The resulting definition must also match at least one argument better than every other definition.

56.        List out the argument matching rules for overloaded function selection within the same type.
1. No conversions are necessary. Functions returning no argument conversions are the best candidates.
            2. Argument promotions are necessary. One or more arguments are promoted along the path
            char -->int--> float-->double-->long-->double
            3. Arguments’ conversions are necessary. One or more arguments are converted according to standard or user defined conversions.

57.        List out the functions that are not (and can't be) inherited in C++.
Ø  Constructors,
Ø  Destructors,
Ø  User defined new operators,
Ø  User defined assignment operators,
Ø  Friend relationships.

58.        Declaring a static member function with the const keyword doesn't make sense. Why?
            The purpose of the const keyword is to prevent the modification of the values through ‘this’ and makes the following invisible declaration:
            const example *const this;
            The static member functions are not passed with an invisible ‘this’ pointer when they are called. So it doesn’t make any sense to declare a static member function as const. 

59.        Can an operator member function be virtual?
            It is possible to declare an operator member function to be virtual, because the mechanics of invoking a member operator function and a regular member function are the same.

60.        Can an assignment operator function be declared as friend?
            No, an assignment operator can be declared only as a member function, never as a friend.

61.        Can a constructor be declared as static?
            A static member function can be used without referring to a specific object, using only a class name. They have no ‘this’ pointer, so they cannot access class member data unless they are passed a ‘this’ pointer explicitly.
            We can't declare constructors to be static. If a constructor was allowed to be static, it could be invoked without a ‘this’ pointer and therefore would not be able to build specific objects from raw storage.
           
62.        List out the differences between the constructors and destructors
Ø  destructors can be virtual whereas constructors can’t,
Ø  you cannot pass arguments to destructors,
Ø  there can be one destructor can be declared for a given class,
Ø  constructors cannot be called explicitly like the way a normal function is called using their qualified name whereas a destructor can be.

63.        Describe some unique features of constructors and destructors.
            1. They do not have return value declaration.
            2. They cannot be inherited.
            3. Their addresses cannot be extracted.

64.        What are the situations under which a copy constructor is used?
Ø  When a new object is initialized to an object of the same class.
Ø  When an object is passed to a function by value.
Ø  When a function returns an object by value.
Ø  When the compiler generates a temporary object.

65.        What are candidate functions?
Let us consider that we have a set of overloaded functions. The set of all these functions are known as candidate functions, because whenever a overloaded function is met in the program they are the candidates for that particular function invocation. In other words, they are the set of functions considered for a resolving a function call. For example:
void f();
void f(int){/*do something*/};
void f(double){ /*do something*/};
void main(){
f(5.6);              
}
In this example the functions f() ,f(int) and f(double) are the candidate functions .

66.        What are viable functions?
Viable functions are the ones that can possibly be resolved into a function call; they are a subset of candidate functions. For example:
void f();
void f(short){/*do something*/};
void f(double){ /*do something*/};
void main(){
f(5.6);// two viable functions f(short) and f(double).
}
In this case there are 2 viable functions f(short) and f(double), because we can have a standard conversion by which float can be converted to an short or float getting promoted to type double by promotion. But in this case the value 5.6 is promoted to a value of type double and is passed to that function.

67.        When is the bad_alloc exception thrown?
We know that ‘new operator is used to allocate space for new objects. If the new operator could not find the space needed to allocate memory for the object, then the allocator throws a bad_alloc exception.

68.        What is placement new?
                        When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it.
           class Widget{
            public :
                        Widget(int widgetsize);
                        ...
                        Widget* Construct_widget_int_buffer(void *buffer,int widgetsize){
                                    return new(buffer) Widget(widgetsize);
                        }
                        };
                        This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

69.        Which operators are called as insertion and extraction operators? Why?
           The C++ operator >> is called the extraction operator, used to extract characters from an input stream and the operator << is called the insertion operator, used to extract text into an output stream.

70.        List out the iostream manipulators
           Dec             --         Display a numeric values in decimal notation.
           endl             --         Output a newline char and flush the stream
           ends            --         Output a null character
           flush            --         Flush the stream buffer
           hex              --         Display numeric values in hexadecimal notation
           oct              --         Display numeric values in octal notation
           ws               --         Skip over leading white space.

71.        What is a parameterized type?
A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters.

72.        List some characteristics of templates that macros do not have.
            As opposed to macros, templates:
Ø  have linkage for their instantiations,
Ø  obey scoping rules (template maybe visible only inside a namespace),
Ø  Templates can be overloaded or specialized,
Ø  there can be pointers to function template specializations,
Ø  can be recursive.

73.        What is the use of ‘autoptr’ template?
Each use of ‘new should be paired with a use of ‘delete’. This can lead to problems if a function in which new is used terminates early through an exception being thrown. Using an autoptr object to keep track of an object created by automates the activation of delete.
            Example:
            void model(string &str)
            {
                        string *ps=new string(str);
                    ..........
                    if(weird_thing())
                              throw exception();
                        str=*ps;
                    delete ps;
                     return;                                                                                 
            }
If the exception is thrown, the delete statement isn't reached and there is a memory leak. The auto_ptr template defines a pointer-like object that is intended to be assigned an address obtained by new. When an auto_ptr object expires, its destructor uses delete to free the memory.
To create an auto_ptr object, include the memory header file, which includes the auto_ptr template. The template includes the following:
            template<class x>class auto_ptr{
            public:
                   explicit auto_ptr(x *p=0) throw();
            .......};
Thus asking for an auto_ptr of type x gives you an auto_ptr of type x.
               auto_ptr<double>pd(new double);   //auto_ptr to double
               auto_ptr<string>ps(new string);      //auto_ptr to string
 32.        How would you classify friends to templates.
Ø  Non template friends.
Ø  Bound template friends, meaning that the type of the class determines the type of the friend when a class is instantiated.
Ø  Unbound template friends, meaning that all instantiations of the friend are friends to each instantiation of the class.

33.        Differentiate between a template class and class template.
Template class:
A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.
Class template:
A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

34.        What is meant by template specialization?
Some cases the general template definition may not fit for a particular data type. For example, let us consider a situation where we are writing a generic function for comparing two values.
Example:
template <class T>  T max (T t1,T t2) {
return T1>T2?T1:T2;
}
But this template definition won’t suit for character strings. So we must have a separate function which implements this function for character strings.
template <char *> char * max(char * a,char *b ){
return ( strcmp(a,b,)>0?a:b);
}

35.        What are Iterators in STL?
Iterators are generalized pointers that may be used to traverse through the contents of a sequence (for example, an STL container or a C++ array).  Iterators provide data access for both reading and writing data in a sequence. They serve as intermediaries between containers and generic algorithms.  A C++ pointer is an iterator, but an iterator is not necessarily a C++ pointer. Iterators, like pointers can be dereferenced, incremented and decremented. At any point in time, an iterator is positioned at exactly one place in one collection, and remains positioned there until explicitly moved.
        Container Classes                                                      Generic Algorithms       
          
                                                           
Iterator




36.        How does the allocation of space take place in a vector?
Initially the size and capacity of a vector are initialized to 0 during declaration. On inserting the first element, the capacity increases to 256, if the vector’s elements are of integer type, 128 if they are of type double, 85 if the elements are of type  string. As for as classes are concerned, the capacity after initial insertion is 1, because the size and processing needed for copying or creating a new object of a class is comparatively higher than that for all the above said types. The size of a vector doubles with each reallocation. For example for a vector of type int, during the first reallocation the size allocated is 512 bytes and during the next reallocation it grows to 1024 and so on.

37.        What is an Iterator class?
                        A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators:           
Ø   input iterators,
Ø  output iterators,
Ø  forward iterators,
Ø  bidirectional iterators,
Ø   random access.
An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class.
The simplest and safest iterators are those that permit read-only access to the contents of a container class. The following code fragment shows how an iterator might appear in code:
           cont_iter:=new cont_iterator();
                        x:=cont_iter.next();
           while x/=none do
                 ...
                 s(x);
                 ...
                 x:=cont_iter.next();
          end;
                        In this example, cont_iter is the name of the iterator. It is created on the first line by instantiation of cont_iterator class, an iterator class defined to iterate over some container class, cont. Succesive elements from the container are carried to x. The loop terminates when x is bound to some empty value. (Here, none)In the middle of the loop, there is s(x) an operation on x, the current element from the container. The next element of the container is obtained at the bottom of the loop.
           
38.        What is stack unwinding?
It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught. For example:
class ExpObj
{
private:
int Errno;
public:
            ExpObj(int Eno):Errno(Eno) {};
void ShowError()
            {
            cout << "The error number is " <<Errno;
            }
};

void sum(int x,int y)
{
            if ( x<0 || y<0)   
throw ExpObj(200);
int s = x+y;
cout << "Sum "<<s;
}
void main()
{
int i=12000, j=-100;
            try
            {
                        sum(i,j);
}
            catch (ExpObj &Exp)
{
                        Exp.ShowError();
}         
}
In this example, the exception is thrown in the function ‘sum’ and there is neither a try block, nor a catch bolock in the function. The control is shifted to search in the calling function, looking for an exception handler. If one such handler is found, program continues execution. If no such handler is found, the program terminates. This process of searching for exception handler in the calling functions resulting in the discarding of stack frames and subsequent calling of destructors for the local objects is known as ‘stack unwindling’.

Exercise
1.      Justify the use of virtual constructors and destructors in C++.
2.      Each C++ object possesses the 4 member fns,(which can be declared by the programmer explicitly or by the implementation if they are not available). What are those 4 functions?
3.      Inheritance is also known as -------- relationship. Containership as   ________ relationship.
4.      When is it necessary to use member-wise initialization list  (also known as header initialization list) in C++?
5.      Which is the only operator in C++ which can be overloaded but NOT inherited.


Section-II Java           

Note: All the programs are tested under JDK 1.3 Java compiler.

1.      class ArrayCopy{
public static void main(String[] args){
int ia1[] = { 1, 2 };
int ia2[] = (int[])ia1.clone();
            System.out.print((ia1 == ia2) + " ");
            ia1[1]++;
System.out.println(ia2[1]);
}
}
Answer:
false  2
Explanation:
The clone function creates a new object with a copy of the original object. The == operator compares for checking if the both refer to the same object and returns false (a boolean value) because they are different objects. When concatenated with a string it prints ‘false’ instead of 0.
Since ia1 and ia2 are two different array objects the change in the values stored in ia1 array object doesn’t affect the object ia2.

2.            import javautil.StringTokenizer;
class STTest {
public static void main(String args[])  {
String s = "9 23 45.4 56.7";
            StringTokenizer st = new StringTokenizer(s);
            while (st.hasMoreTokens())
System.out.println(st.nextToken());
}
}
Answer:          9
            23
            45.4
            56.7
            Explanation:
The StringTokenizer parses the given string to return the individual tokens. Here the String  ‘s’ has four white-spaces that act as a separators, resulting in the printing of those individual tokens.

3.            class ConvertTest {
public static void main (String args[]){
String str;
str = "25";
int i = Integer.valueOf(str).intValue();
            System.out.println(i);
            str = "25.6";
            double d = Double.valueOf(str).doubleValue(); 
            System.out.println(d);
} 
}
Answer:         
25   25.6
Explanation:
This program just explains how the static member funntions of the classes Integer and Double can be used  to convert the string values that have numbers to the get primitive data-type values.
 
4.            class StaticTest {
public static void main(String[] args) {
int i = getX();
}
public int getX() {
return 3;
}
}
Answer:         
            Compiler Error : Cannot access a non-static member
Explanation:
The static method, main(), belongs to the class. However,getX() belongs to an object in the class. The compiler doesn't know on which object it's invoking the getX() method.There are a couple of ways around this problem. You could declare that getX() as static; that is:
                         public static int getX()
Alternately, you can instantiate an object in the StaticTest class in the main() method and invoke that object's getX() method, like this:  
public static void main(String[] args) {
                        StaticTest st = new StaticTest();
int i = st.getX();
}

5.            class Test {
public static void main(String[] args) {
                                    String s1 = new String("Hello World");
String s2 = new String("Hello World");
if (s1 == s2)
System.out.println("The strings are the same.");
else
System.out.println("The strings are different.");
          }
}
Answer:         
The strings are different.
            Explanation:
When used on objects, == tests whether the two objects are the same       object, not whether they have the same value.
To compare two objects for equality, rather than identity, you should       use the equals() method.

6.            class Test {
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = "Hello World";
            if (s1 == s2)
System.out.println("The strings are the same");
            else
System.out.println("The strings are different");
                                    }
                        }
Answer:
The strings are the same.
            Explanation:
Note that these two are string literals and not Strings. The compiler recognizes that the two string literals have the same value and it performs a simple optimization of only creating one String object. Thus s1 and s2 both refer to the same object and are therefore equal. The Java Language Specification requires this behavior. However, not all compilers get this right so in practice this behavior here is implementation dependent.

7.            public class works{ 
public static int some;
            static {
                        some = 100;
            System.out.println("Inside static");
            }
            public static void main( String args[] ) {
                        new works();
System.out.println( "Inside main" );
            }
            works() {
            System.out.println( "some = " + some );
            }
}
            Answer:
            Inside static
some =  100
Inside main
            Explanation:
Static blocks are executed before the invocation of main(). So at first the “Inside static” is printed. After that the main function is called. It creates the object of the same type. So it leads to the printing of ‘some =  100’. Finally the println inside the main() is executed to print ‘Inside main’.    

8.            public class func{
int g(){
System.out.println("inside g");
int h(){
System.out.println("inside h");
return 1;
}
return 0;
}
public static  void  main(String[] args){
int c;
c=g();
}
            Answer:
    error :  ";" expected at - int h()
Explanation:
Java doesn’t allow function declared within a function declaration (nested functions). Hence the error.

9.            When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Exception: True or False?
Answer:
            False.
Explanation:
When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Throwable

10.        class Test {
public static void main(String[] args) {
Button b;
b.setText("Hello");
}
}
Answer:
Runtime Error : NullPointerException
Explanation:
A NullPointerException is thrown when the system tries to access a object that points to a null value (objects are initalised to null).
This code tries to call setText() on ‘b’. ‘b’ does not refrence any object, so the exception is thrown. You must allocate space for the reference to point to an object like this:
Button b = new Button("hello");
            // Or
Button b;
b = new Button();
b.setText("hello");
This creates a reference (‘b’) of type Button, then asssigns it to a new instance of Button (new Button("hello")).

11.        class Test {
            void Test() {
                                    System.out.println("Testing") ;
            }
                        public static void main(String argv[]) {
                Test ex = new Test() ;
            }
}
Answer:
            Compiler Error : ‘void’ before Test()
Explanation:
Constructor doesn’t have any return type; so even void shouldn't be specified as return type.

12.        class Test {
int some=10 ;
void Test() {
                              this(some++) ;
      }
void Test(int i) {
                              System.out.println(some);
}
                  public static void main( String argv[] ) {
                              new Test();
             }
 }
Answer:
            Compiler Error : Cannot use ‘this’ inside the constructor
Explanation:
‘this’ is a special one that it refers to the same object. But ‘this’ can be used only after creation of the object. It can’t be used within a constructor.  This leads to the issue of the error.

16.       class Test {
            public int some;
            public static void main(String argv[]) {
                int i = new Test().some;     
                System.out.println(i) ;
            }
}
Answer:
0
Explanation:
All member variables are initialised during creation of the object. In the statement:
int i = new Test().some;           
a new object of type ‘Test’ is created and the value of member ‘j’ in that object is referenced (the object created is not assigned to any reference) unig the ‘.’ (dot) operator.

13.        What does this code do?
int f = 1+ (int)(Math.random()*6);
This code always assigns an integer to variable f in the range between 1 and 6.

14.        All programs can be written in terms of three types of control structures: What are those three?
Sequence,selection and repetition.

15.        Is !(x<y) the same as (x>=y) in Java ?
In the case that x and y are of float or double, the value of x or y could be NaN and the results would be different in that case.

16.        What are peer "classes"?
Peer classes exist mainly for the convenience of the people who wrote the     Java environment. They help in translating between the AWT user interface     and the native (Windows, OpenWindows, Mac etc.) interfaces. Unless you're     porting Java to a new platform you shouldn't have to use them.

17.        What are concrete classes?
The classes from which objects are instantiated are called concrete classes (as opposed to abstract classes from which objects cannot be created).

18.        Which methods in Java are implcitly treated as final methods?
Methods that are declared static and that are declared as private.

19.        Java's finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. True or False?
True.

20.        Explain why you should place exception handlers furthermost from the root of the exception hierarchy tree first in the list of exception handlers.
An exception hander designed to handle a specialized "leaf" object may be preempted by another handler whose exception object type is closer to the root of the exception hierarchy tree if the second exception handler appears earlier in the list of exception handlers.

21.        What method of which class would you use to extract the message from an exception object?
The getMessage() method of the Throwable class.

22.        What are"deprecated APIs"?
A deprecated API is a object or method that is not recommended to be used and is an indication that it may be removed from the API list in future. The programs that use such APIs still work fine but not recommended to be used for this reason. 






 









Section I – UNIX Commands

1.            What is relative path and absolute path.
            Absolute path : Exact path from root directory.
                        Relative path  : Relative to the current path.

2.            Explain kill() and its possible return values.
There are four possible results from this call:
·        ‘kill()’ returns 0. This implies that a process exists with the given PID, and the system would allow you to send signals to it. It is system-dependent whether the process could be a zombie.
·        ‘kill()’ returns -1, ‘errno == ESRCH’ either no process exists with the given PID, or security  enhancements are causing the system to deny its existence. (On       some systems, the process could be a zombie.)
·        ‘kill()’ returns -1, ‘errno == EPERM’ the system would not allow you to kill the specified process. This means that either the process exists (again, it could be a zombie) or draconian security enhancements are present (e.g. your process is not allowed to send signals to *anybody*).
·        ‘kill()’ returns -1, with some other value of ‘errno’ you are in trouble! The most-used technique is to assume that success or failure with ‘EPERM’ implies that the process exists, and any other error implies that it doesn't.
An alternative exists, if you are writing specifically for a system (or all those systems) that provide a ‘/proc’ filesystem: checking for the existence of ‘/proc/PID’ may work.

3.            What is a pipe and give an example?
A pipe is two or more commands separated by pipe char '|'. That tells the shell to arrange for the output of the preceding command to be passed as input to the following command.
Example : ls -l | pr
The output for a command ls is the standard input of pr.
When a sequence of commands are combined using pipe, then it is called pipeline.

4.            How to terminate a process which is running and the specialty on command kill 0?
            With the help of kill command we can terminate the process.
                        Syntax: kill pid
            Kill 0 - kills all processes in your system except the login shell.

5.            What is redirection?
 Directing the flow of data to the file or from the file for input or output.
Example :  ls > wc

6.            What are shell variables?
Shell variables are special variables, a name-value pair created and maintained by the shell.
Example: PATH, HOME, MAIL and TERM

7.            How to switch to a super user status to gain privileges?
Use ‘su’ command. The system asks for password and when valid entry is made the user gains super user (admin) privileges.

8.            How does the kernel differentiate device files and ordinary files?
                        Kernel checks 'type' field in the file's inode structure.

9.            What is the significance of '&' at the end of any command?
            To make the process run as a background process.

10.        How many prompts are available in a UNIX system?
Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).

11.        Name the data structure used to maintain file identification?
                        ‘inode’, each file has a separate inode and a unique inode number.

12.        What is the purpose of 'ps' command and its columns?
·        To display process status of all the processes currently running in the system.
·        Columns include UID, PID, PPID, STATUS, COMMAND, TTY and TIME.
·        Various STATUS type are S - sleeping, R - Running, I - Intermediate.

13.        Is it possible to count number char, line in a file; if so, How?
                        Yes, wc-stands for word count.
wc -c for counting number of characters in a file.
            wc -l for counting lines  in a file.

14.        Is ‘du’ a command? If so, what is its use?
Yes, it stands for ‘disk usage’. With the help of this command you can find the disk capacity and free space of the disk.

15.        What is the use of the command "ls -x chapter[1-5]"
ls stands for list; so it displays the list of the files that starts with 'chapter' with suffix '1' to '5', chapter1, chapter2, and so on.

16.        Is it possible to restrict incoming message?
            Yes, using the ‘mesg’ command.

17.        Is it possible to create new a file system in UNIX?
                        Yes, ‘mkfs’ is used to create a new file system.

18.        What will the following command do?
$ echo *
It is similar to 'ls' command and displays all the files in the current
            directory.

19.        What is the purpose of 'FINGER', 'NICE' and 'TOUCH' command?
            FINGER          : displays information about all the users logged in.
                        NICE               : sets priority of a process range of the NICE value 0 - 39.
TOUCH           : creates empty files as specified and can also be used to change a file's modified time without modifying the file.

20.        What is the purpose of 'nohup' command?
A Set of processes are preceded by the command ‘nohup’ along with a output file. Even if the user is logged off the process is not killed and the resulted is evaluated and stored in output file.

21.        Write a command to display a file’s contents in various formats?
                        $od -cbd file_name
            c - character, b - binary (octal), d-decimal, od=Octal Dump.

22.        Which command is used to delete all files in the current directory and all  its sub-directories?
                        rm -r *

23.        Write a command to kill the last background job?
                        Kill $!

24.        What is the difference between cat and more command?
Cat displays file contents. If the file is large the contents scroll off the screen before we view it. So command 'more' is like a pager which displays the contents page by page.

25.        What is the use of ‘grep’ command?
‘grep’ is a pattern search command. It searches for the pattern, specified in the command line with appropriate option, in a file(s).
Syntax :           grep <options> <pattern> <filename(s)>

Example :        grep 99mx mcafile


26.        What difference between cmp and diff commands?
cmp - Compares two files byte by byte and displays the first mismatch
diff - tells the changes to be made to make the files identical

27.        Explain the steps that a shell follows while processing a command.
After the command line is terminated by the <enter> key, the shel goes ahead  with processing the command line in one or more passes. The sequence is well defined and assumes the following order.
Parsing: The shell first breaks up the command line into words, using spaces and the delimiters, unless quoted. All consecutive occurrences of a space or tab are replaced here with a single space.
Variable evaluation:  All words preceded by a $ are avaluated as variables, unless quoted or escaped.
Command substitution:  Any command surrounded by backquotes is executed by the shell which then replaces the standard output of the command into the command line.
Wild-card interpretation: The shell finally scans the command line for wild-cards (the characters *, ?, [, ]). Any word containing a wild-card is replaced by a sorted list of filenames that match the pattern. The list of these filenames then forms the arguments to the command.
PATH evaluation: It finally looks for the PATH variable to determine the sequence of directories it has to search in order to hunt for the command.

No comments:

Post a Comment