Technical Question c c++

download Technical Question c c++

of 17

Transcript of Technical Question c c++

  • 8/22/2019 Technical Question c c++

    1/17

    Q6=what is the difference between a pointer and a reference?

    A reference must always refer to some object and, therefore, must always be initialized;

    pointers do not have such restrictions. A pointer can be reassigned to point to differentobjects while a reference always refers to an object with which it was initialized.Q1=Deep Copy and Shallow Copyn

    "A shallow copy creates a new instance of the same type as the original object, and then copies the

    non-static fields of the original object. If the field is a value type, a bit-by-bit copy of the field is

    performed. If the field is a reference type, the reference is copied but the referred object is not;

    therefore, the reference in the original object and the reference in the clone point to the same object. In

    contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields

    in the object."

    class A

    {

    string s;

    };

    A a;

    A b;

    a=b; //deep copy

    Q2=-#define mul(x) x * xint main()

    {

    int i=3;printf("%d \n", mul(++i));

    printf("%d", i);

    return(0);

    }

    Q3= what will be the output of 'X' in following code and how?

    x= (i++ + ++i + i++ + i++ + ++i);

    Q4=Abstract class and interface

    Abstract Class:1. Abstract Class Can contain Abstract Methods and Non-

    Abstract Methods.3.Abstract Class may contain constructor but interface does

    not contain constructor.

    4. you can define variables in abstract class but this is notallowed in interfaces.

    5. In the abstract class we can define the member function

    but in interface we can not define only declare the

    function.5. An abstract class contain abstract method and non-

    abstract method, but In interface all method are implictlyabstract.

    Interface:

    1. Interface is nothing but Pure Abstract Class i.e.Interface can contain only the function declaration.

    2. All the members of the interface are Public by Default

    and you cannot provide any access modifiers.

  • 8/22/2019 Technical Question c c++

    2/17

    3. When a class is inherited from the interface, the

    inherited class should provide actual implementations for

    the inherited members.

    Q5=Method overloading

    Ans==defining multiple funs with same name known as overloading. These are differed

    as number, arguments order.Q==how many ways we can pass variable to a function?Ans== void fun(int,int);

    fun(a,b); //callvoid &fun(int&,int&);

    fun(a,b);

    void fun(int *,int*);

    fun(&a,&b);

    Q6=What is constructor or ctor?

    Constructor creates an object and initializes it. It also creates vtable for virtual functions.

    It is different from other methods in a class.

    Q7=what is copy constructor?Constructor which initializes its object member variables (by shallow copying) with

    another object of the same class. If you don't implement one in your class then compilerimplements one for you.

    for example:

    Boo Obj1(10); // calling Boo constructorBoo Obj2(Obj1); // calling boo copy constructor

    Boo Obj2 = Obj1;// calling boo copy constructor

    Q6=When are copy constructors called?

    Copy constructors are called in following cases:a) when a function returns an object of that class by value

    b) when the object of that class is passed by value as an argument to a function

    c) when you construct an object based on another object of the same classd) When compiler generates a temporary object

    Q6=what is assignment operator?

    Default assignment operator handles assigning one object to another of the same class.Member to member copy (shallow copy)

    Q6=what are all the implicit member functions of the class? Or what are all the

    functions which compiler implements for us if we don't define one.??

    default ctorcopy ctor

    assignment operator

    default destructoraddress operator

    Q6=What is conversion constructor?

    Constructor with a single argument makes that constructor as conversion ctor and it canbe used for type conversion.

    for example:

    class Boo

    {

  • 8/22/2019 Technical Question c c++

    3/17

    public:

    Boo( int i );

    };Boo BooObject = 10 ; // assigning int 10 Boo object

    Q6=What is conversion operator??

    class can have a public method for specific data type conversions.for example:

    class Boo

    {double value;

    public:

    Boo(int i )

    operator double(){

    return value;

    }

    };Boo BooObject;

    double i = BooObject; // assigning object to variable i of type double. now conversionoperator gets called to assign the value.

    Q6=What is diff between malloc()/free() and new/delete?

    malloc allocates memory for object in heap but doesn't invoke object's constructor toinitiallize the object.

    new allocates memory and also invokes constructor to initialize the object.

    malloc() and free() do not support object semantics

    Does not construct and destruct objectsstring * ptr = (string *)(malloc (sizeof(string)))

    Are not safe

    Does not calculate the size of the objects that it constructReturns a pointer to void

    int *p = (int *) (malloc(sizeof(int)));

    int *p = new int;Are not extensible

    new and delete can be overloaded in a class

    "delete" first calls the object's termination routine (i.e. its destructor) and then releases the

    space the object occupied on the heap memory. If an array of objects was created usingnew, then delete must be told that it is dealing with an array by preceding the name with

    an empty []:-

    Int_t *my_ints = new Int_t [10];delete []my_ints;

    Q6=what is the diff between "new" and "operator new" ?

    "operator new" works like malloc.

    Q6=What is difference between template and macro??

    There is no way for the compiler to verify that the macro parameters are of compatible

    types. The macro is expanded without any special type checking.

  • 8/22/2019 Technical Question c c++

    4/17

    If macro parameter has a post incremented variable ( like c++ ), the increment is

    performed two times.

    Because macros are expanded by the preprocessor, compiler error messages will refer tothe expanded macro, rather than the macro definition itself. Also, the macro will show up

    in expanded form during debugging.

    for example:Macro:

    #define min(i, j) (i < j ? i : j)

    template:template

    T min (T i, T j)

    {

    return i < j ? i : j;}

    Q6=What are C++ storage classes?

    autoregister

    staticextern

    auto: the default. Variables are automatically created and initialized when they are

    defined and are destroyed at the end of the block containing their definition. They are notvisible outside that block

    register: a type of auto variable. a suggestion to the compiler to use a CPU register for

    performance

    static: a variable that is known only in the function that contains its definition but is neverdestroyed and retains its value between calls to that function. It exists from the time the

    program begins execution

    extern: a static variable whose definition and placement is determined when all objectand library modules are combined (linked) to form the executable code file. It can be

    visible outside the file where it is defined.

    Q6=What are storage qualifiers in C++ ?

    They are..

    const

    volatile

    mutableConst keyword indicates that memory once initialized, should not be altered by a

    program.

    volatile keyword indicates that the value in the memory location can be altered eventhough nothing in the program

    code modifies the contents. for example if you have a pointer to hardware location that

    contains the time, where hardware changes the value of this pointer variable and not theprogram. The intent of this keyword to improve the optimization ability of the

    compiler.

    mutable keyword indicates that particular member of a structure or class can be altered

    even if a particular structure variable, class, or class member function is constant.

  • 8/22/2019 Technical Question c c++

    5/17

    struct data

    {

    char name[80];mutable double salary;

    }

    const data MyStruct = { "Satish Shetty", 1000 }; //initlized by complierstrcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error

    MyStruct.salaray = 2000 ; // complier is happy allowed

    Q6=What is reference ??

    reference is a name that acts as an alias, or alternative name, for a previously defined

    variable or an object.

    prepending variable with "&" symbol makes it as reference.

    for example:int a;

    int &b = a;

    Q6=What is passing by reference?

    Method of passing arguments to a function which takes parameter of type reference.for example:

    Void swap (int & x, int & y){

    int temp = x;

    x = y;y = temp;

    }

    Int a=2, b=3;

    swap( a, b );Basically, inside the function there won't be any copy of the arguments "x" and "y"

    instead they refer to original variables a and b. so no extra memory needed to pass

    arguments and it is more efficient.

    Q6=When do use "const" reference arguments in function?

    a) Using const protects you against programming errors that inadvertently alter data.

    b) Using const allows function to process both const and non-const actual arguments,while a function without const in the prototype can only accept non constant arguments.

    c) Using a const reference allows the function to generate and use a temporary variable

    appropriately.

    Q6=When are temporary variables created by C++ compiler?

    Provided that function parameter is a "const reference", compiler generates temporary

    variable in following 2 ways.

    a) The actual argument is the correct type, but it isn't Lvaluedouble Cube(const double & num)

    {

    num = num * num * num;return num;

    }

    double temp = 2.0;

    double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;

  • 8/22/2019 Technical Question c c++

    6/17

    b) The actual argument is of the wrong type, but of a type that can be converted to the

    correct type

    long temp = 3L;double value = cuberoot ( temp); // long to double conversion

    Q6=What is virtual function?

    When derived class overrides the base class method by redefining the same function, thenif client wants to access redefined the method from derived class through a pointer from

    base class object, then you must define this function in base class as virtual function.

    class parent{

    void Show()

    {

    cout

  • 8/22/2019 Technical Question c c++

    7/17

    class Boo

    {

    void foo() = 0;}

    Boo MyBoo; // compilation error

    Q6=what is Memory alignment??The term alignment primarily means the tendency of an address pointer value to be a

    multiple of some power of two. So a pointer with two byte alignment has a zero in theleast significant bit. And a pointer with four byte alignment has a zero in both the two

    least significant bits. And so on. More alignment means a longer sequence of zero bits in

    the lowest bits of a pointer.

    Q6=what problem does the namespace feature solve?Multiple providers of libraries might use common global identifiers causing a name

    collision when an application tries to link with two or more such libraries. The

    namespace feature surrounds a library's external declarations with a unique namespace

    that eliminates the potential for those collisions.namespace [identifier] { namespace-body }

    A namespace declaration identifies and assigns a name to a declarative region.The identifier in a namespace declaration must be unique in the declarative region in

    which it is used. The identifier is the name of the namespace and is used to reference its

    members.

    Q6=What is the use of 'using' declaration?

    A using declaration makes it possible to use a name from a namespace without the scope

    operator.

    Q6=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 thecontents 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 someordering 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. Something like apointer.

    Q6=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.

    Q6=What do you mean by Stack unwinding?

    It is a process during exception handling when the destructor is called for all local objects

    in the stack between the place where the exception was thrown and where it is caught.

    Q6=Name the operators that cannot be overloaded??

    sizeof, ., .*, .->, ::, ?:

  • 8/22/2019 Technical Question c c++

    8/17

    Q6=what is a container class? What are the types of container classes?

    A container class is a class that is used to hold objects in memory or external storage. A

    container class acts as a generic holder. A container class has a predefined behavior and awell-known interface. A container class is a supporting class whose purpose is to hide the

    topology used for maintaining the list of objects in memory. When a container class

    contains a group of mixed objects, the container is called a heterogeneous container;when the container is holding a group of objects that are all the same, the container is

    called a homogeneous container.

    Q6=what is inline function??

    The __inline keyword tells the compiler to substitute the code within the function

    definition for every instance of a function call. However, substitution occurs only at the

    compiler's discretion. For example, the compiler does not inline a function if its address

    is taken or if it is too large to inline.

    Q6=what is overloading??

    With the C++ language, you can overload functions and operators. Overloading is the

    practice of supplying more than one definition for a given function name in the same

    scope.- Any two functions in a set of overloaded functions must have different argument lists.

    - Overloading functions with argument lists of the same types, based on return type alone,is an error.

    Q6=What is Overriding?

    To override a method, a subclass of the class that originally declared the method mustdeclare a method with the same name, return type (or a subclass of that return type), and

    same parameter list.

    The definition of the method overriding is:

    Must have same method name. Must have same data type.

    Must have same argument list.

    Overriding a method means that replacing method functionality in child class. To implyoverriding functionality we need parent and child classes. In the child class you define

    the same method signature as one defined in the parent class.

    Q6=what is "this" pointer?

    The this pointer is a pointer accessible only within the member functions of a class,

    struct, or union type. It points to the object for which the member function is called.

    Static member functions do not have a this pointer.

    When a nonstatic member function is called for an object, the address of the object ispassed as a hidden argument to the function. For example, the following function call

    myDate.setMonth( 3 );

    can be interpreted this way:setMonth( &myDate, 3 );

    The object's address is available from within the member function as the this pointer. It is

    legal, though unnecessary, to use the this pointer when referring to members of the class.

    Q6=How virtual functions are implemented C++?

    Virtual functions are implemented using a table of function pointers, called the vtable.

    There is one entry in the table per virtual function in the class. This table is created by

    the constructor of the class. When a derived class is constructed, its base class is

  • 8/22/2019 Technical Question c c++

    9/17

    constructed first which creates the vtable. If the derived class overrides any of the base

    classes virtual functions, those entries in the vtable are overwritten by the derived class

    constructor. This is why you should never call virtual functions from a constructor:because the vtable entries for the object may not have been set up by the derived class

    constructor yet, so you might end up calling base class implementations of those virtual

    functionsQ6=What is name mangling in C++??The process of encoding the parameter types with the function/method name into a

    unique name is called name mangling. The inverse process is called demangling.For example Foo::bar(int, long) const is mangled as `bar__C3Fooil'.

    For a constructor, the method name is left out. That is Foo::Foo(int, long) const is

    mangled as `__C3Fooil'.

    Q6=How are prefix and postfix versions of operator++() differentiated?

    The postfix version of operator++() has a dummy parameter of type int. The prefix

    version does not have dummy parameter.

    Q6=what is the difference between const char *myPointer and char *const my

    Pointer?Const char *myPointer is a non constant pointer to constant data; while char *const

    myPointer is a constant pointer to non constant data.

    Q6=How can I handle a constructor that fails?

    Throw an exception. Constructors don't have a return type, so it's not possible to use

    return codes. The best way to signal constructor failure is therefore to throw an exception.

    Q6=How can I handle a destructor that fails?

    Write a message to a log-file. But do not throw an exception.

    The C++ rule is that you must never throw an exception from a destructor that is being

    called during the "stack unwinding" process of another exception. For example, ifsomeone says throw Foo(), the stack will be unwound so all the stack frames between the

    throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding.

    During stack unwinding, all the local objects in all those stack frames are destructed. Ifone of those destructors throws an exception (say it throws a Bar object), the C++

    runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch

    (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch(Bar e) { handler? There is no good answer -- either choice loses information.

    So the C++ language guarantees that it will call terminate() at this point, and terminate()

    kills the process. Bang you're dead.

    Q6=what is Virtual Destructor?

    Using virtual destructors, you can destroy objects without knowing their type - the correct

    destructor for the object is invoked using the virtual function mechanism. Note thatdestructors can also be declared as pure virtual functions for abstract classes.

    if someone will derive from your class, and if someone will say "new Derived", where

    "Derived" is derived from your class, and if someone will say delete p, where the actualobject's type is "Derived" but the pointer p's type is your class.

    Need to add something

    Q6=Can you think of a situation where your program would crash without reaching

    the breakpoint which you set at the beginning of main()?

  • 8/22/2019 Technical Question c c++

    10/17

    C++ allows for dynamic initialization of global variables before main() is invoked. It is

    possible that initialization of global will invoke some function. If this function crashes the

    crash will occur before main() is entered.

    Q6=Can you overload a function based only on whether a parameter is a value or a

    reference?No. Passing by value and by reference looks identical to the caller.

    Q6=What are the differences between a C++ struct and C++ class?

    The default member and base class access specifiers are different.The C++ struct has all the features of the class. The only differences are that a struct

    defaults to public member access and public base class inheritance, and a class defaults to

    the private access specifier and private base class inheritance.

    Q6=What does extern "C" int func(int *, Foo) accomplish?

    It will turn off "name mangling" for func so that one can link to code compiled by a C

    compiler.

    Q6=How do you access the static member of a class?

    ::Q6=What is multiple inheritance(virtual inheritance)? What are its advantages anddisadvantages?

    Multiple Inheritance is the process whereby a child can be derived from more than one

    parent class. The advantage of multiple inheritance is that it allows a class to inherit the

    functionality of more than one base class thus allowing for modeling of complexrelationships. The disadvantage of multiple inheritance is that it can lead to a lot of

    confusion(ambiguity) when two base classes implement a method with the same name.

    Q6=What are the access privileges in C++? What is the default access level?

    The access privileges in C++ are private, public and protected. The default access levelassigned to members of a class is private. Private members of a class are accessible only

    within the class and by friends of the class. Protected members are accessible by the class

    itself and it's sub-classes. Public members of a class can be accessed by anyone.

    Q6=What is a nested class? Why can it be useful?

    A nested class is a class enclosed within the scope of another class. For example:

    // Example 1: Nested class//

    class OuterClass

    {

    class NestedClass{

    // ...

    };// ...

    };

    Nested classes are useful for organizing code and controlling access and dependencies.Nested classes obey access rules just like other parts of a class do; so, in Example 1, if

    NestedClass is public then any code can name it as OuterClass::NestedClass. Often

    nested classes contain private implementation details, and are therefore made private; in

  • 8/22/2019 Technical Question c c++

    11/17

    Example 1, if NestedClass is private, then only OuterClass's members and friends can use

    NestedClass.

    When you instantiate as outer class, it won't instantiate inside class.

    Q6=What is a local class? Why can it be useful?

    local class is a class defined within the scope of a function -- any function, whether a

    member function or a free function. For example:// Example 2: Local class

    //

    int f(){

    class LocalClass

    {

    // ...};

    // ...

    };

    Like nested classes, local classes can be a useful tool for managing code dependencies.

    Q6=Can a copy constructor accept an object of the same class as parameter, instead

    of reference of the object?

    No. It is specified in the definition of the copy constructor itself. It should generate anerror if a programmer specifies a copy constructor with a first argument that is an object

    and not a reference

    Q6=How to access two dimension array through pointer?

    Ans: int arr[3][2]={{10,100,{20,200},{30,300}};We know that arr=arr[0]=*(arr+0)

    arr[1] = *(arr+1)

    arr[i] = *(arr+i)similarly in two dimension arr[0][1]=*(arr[0]+1)= *(*(arr[0]+1))

    arr[j][k]= *(arr[j]+k)= *(*(arr[j]+k))

    Q6=How to create array of objects dynamically and how to access 5th object?Ans:

    Q6= what is singleton class?

    Ans:

    What is encapsulation??

    Containing and hiding information about an object, such as internal data structures andcode. Encapsulation isolates the internal complexity of an object's operation from the rest

    of the application. For example, a client component asking for net revenue from a

    businessobject need not know the data's origin.

    What is inheritance?

    Inheritance allows one class to reuse the state and behavior of another class. The derivedclass inherits the properties and method implementations of the base class and extends it

  • 8/22/2019 Technical Question c c++

    12/17

    byoverriding methods and adding additional properties and methods.

    What is Polymorphism??

    Polymorphism allows a client to treat different objects in the same way even if they werecreated from different classes and exhibit different behaviors. You can use

    implementation

    inheritance to achieve polymorphism in languages such as C++ and Java. Base classobject's

    pointer can invoke methods in derived class objects. You can also achieve polymorphism

    inC++ by function overloading and operator overloading.

    from other methods in a class.

    double i = BooObject; // assigning object to variable i of type double. now conversion

    operator gets called to assign the value.

    Q.Differentiate between a template class and class template.?

    Ans:

    ===========================================

    Assume I have a linked list contains all of the alphabets from A to Z.I want to find the letter Q in the list, how does you perform the search to find the Q?

    Ans:

    How do you find out if a linked-list has an end? (i.e. the list is not a cycle)

    You can find out by using 2 pointers. One of them goes 2 nodes each time. The secondone

    goes at 1 nodes each time. If there is a cycle, the one that goes 2 nodes each time will

    eventually meet the one that goes slower. If that is the case, then you will know the

    linked-list is a cycle.

    How do you link a C++ program to C functions?

    Ans:By using the extern "C" linkage specification around the C function declarations.

    Explain the scope resolution operator.

    Ans:It is used to define some members which has a global position to get it into local.

    What is a modifier?Ans::public,private,protected. Which is used to modify the function reality.

    When does a name clash occur?

    Ans::when a class is defined more than one palce

    What is an incomplete type?

    Ans::Which has a definition but no declaration like a struct student s1.

    What is an adaptor class or Wrapper class?

    Ans:: A class that has no functionality of its own. Its member functions hide the use of a thirdparty software component or an object with the non-compatible interface or a non-object-oriented implementation.What are macros? What are the advantages and disadvantages?Ans:: Macros are pre processor.The advantage of usingmacrosis that it

    savesmemoryand time. With the use of macros the compilation will become faster-processor but the dis adv is it increases its size in the program and doesnt effect type

    checking.What is static identifier?

  • 8/22/2019 Technical Question c c++

    13/17

    Ans::static data members and static member functions.Where are the auto variables stored?

    Ans::stores in stack.Difference between arrays and linked list?

    Ans:: Array is lenear linked list is nonlinear. Array is contigious allocated memory and linked listis randomly allocated memory. Linked list consists of data nodes, each pointing to the next in the

    list. An array consists of contiguous chunks memory of predetermined size. Linked lists are quiteflexible. They can grow to any...What are enumerations?

    Ans::

    Describe about storage allocation and scope of global, extern, static, local and register

    variables?

    Ans::l ocal sored in stack.global extern in heap and register in register.

    Difference between strdup and strcpy?

    Ans:: strcpy - copy a string to a location YOU created (you create the location, make sure that the

    source string will have enough room there and afterwards use strcpy to copy)

    strdup - copy a string to a location that will be created by the function. The function will allocate

    space, make sure that your string will fit there and copy the string. Will return a pointer to the

    created area.

    What is recursion?Ans::The fun calls to itself.

    What is a NULL Macro? What is the difference between a NULL Pointer and a NULL

    Macro?

    Ans::Null macro is #define NULL o

    It means the macro NULL will be replaced by 0 while preprocessing

    Butthe NULLpointermeans it points to nowhere i.e. contains 0.

    It contains 0 means it may be dangerous to use suchpointerwithout assigning proper

    address to it otherwise NULLpointermay try to access reset address may cause theprogram to crash.What is near, far and huge pointers? How many bytes are occupied by them?

    Ans:: Far pointer is a pointer variable. It is just like near pointer. But if we use largememory models then we can use these far pointers. Because these far pointers occupy 4

    bytes of memory.near and far .for big operation we use huge pointer.it is 32 byteAre the expressions arr and *arr same for an array of integers?

    Ans:yes

    Does mentioning the array name gives the base address in all the contexts?

    Ans::no its the base address

    Explain one method to process an entire string as one unit?

    Ans::We can try by using pointer

    Are the variables argc and argv are local to main?

    Ans::Yes they are local to main()

    ====================================================

    What do the functions atoi(), itoa() and gcvt() do?

    Ans::atoi()convert string to integer

    Itoa-convert integer to string

    Gcvt-convert to double to string

  • 8/22/2019 Technical Question c c++

    14/17

    How would you use qsort() function to sort the name stored in an array of pointers to

    string?

    Ans:: It is same as you would sort an array of integers using qsort. Only difference is thatyou would have to do string comparison.How would you use the functions memcpy(), memset(), memmove()?

    Ans:: memset()the bytes in a block of memory to a particular value, use memset(). The function prototype is

    void * memset(void *dest, int c, size_t count);memcpy()--

    memcpy() copies bytes of data between memory blocks, sometimes calledbuffers. This functiondoesn't care about the type of data being copied--it simply makes an exact byte-for-byte copy.

    The function prototype is

    void *memcpy(void *dest, void *src, size_t count);memmove()

    memmove() is very much like memcpy(), copying a specified number of bytes from one memoryblock to another. It's more flexible, however, because it can handle overlapping memory blocks

    properly. Because memmove() can do everything memcpy() can do with the added flexibility of

    dealing with overlapping blocks, you rarely, if ever, should have a reason to use memcpy(). Theprototype is

    void *memmove(void *dest, void *src, size_t count);

    What is the difference between the functions rand(), random(), srand() and randomize()?

    Ans:: Rand() uses multiplicative congruential random number generator with period232 to returnsuccessive pseudo-random numbers in the range 0 to RAND_MAX.

    Return Value: Rand returns the generated pseudo-random number.

    RANDOM(): Random returns a random number between 0 and (num-1).random(num) is a macro defined

    in STDLIB.H.

    RANDOMIZE(): Randomize initializes the random number generator with a random value. Because

    randomize is implemented as a macro that calls the time function prototyped in TIME.H, you shouldinclude TIME.H when you use this routine

    SRAND(): The random number generator is reinitialized by calling srand with an argument value of 1.The

    generator can be set to a new starting point by calling srand with a given seed number.

    What is the difference between main() in C and main() in C++?

    Ans::return type is void and in c++ return type is int defeultWhat is the order of initalization for data?

    Ans::

    What is a constructor initializer list?Ans::how a constructor intitilaize its data menber

    Whenmustyou use a constructor initializer list?

    Ans::static data member see in net.

    What does it mean to declare a estructor asstatic?

    Ans:: you CANT declare destructor as static, as you

    CANT declare constructor as static, both are responsible for

    destroying and creating OBJECTS while static storage means

  • 8/22/2019 Technical Question c c++

    15/17

    that methods/members do not belong to any objects but to the

    whole class.

    What is placement?

    Ans:: means how using new and delete.

    Explain what happens when an exception is thrown in C++.

    Ans:: t depends on whether or not we have any code that catches the exception.What happens if an exception is not caught?

    Ans:: An uncaught exception would cause the program to terminateWhat happens if an exception is throws from an object's constructor?

    Ans::ans that construction has failed, the object never existed, its lifetime never began.

    Indeed, the only way to report the failure of construction -- that is, the inability to

    correctly build a functioning object of the given type -- is to throw an exception. Adestructor will never be called if the constructor didn't succeed.What happens if an exception is throws from an object's destructor?

    Ans::tter how the destructor terminates, the object does not exist anymore. Thus, in the

    case of the destructor, we are forced to complete the job no matter what.What is exception handling?Ans:: Exception handlingis a mechanism that separates code that detects and handles

    exceptional circumstances from the rest of your program.The exception handling mechanism is made up of the following elements:

    try blocks: a block of code that may throw an exception that you want to handle

    with special processing

    catch blocks or handlers: a block of code that is executed when a try blockencounters an exception

    throw expression: indicates when your program encounters an exception

    exception specifications: specify which exceptions (if any) a function may throw

    unexpected() function: called when a function throws an exception not specified by

    an exception specification

    terminate() function: called for exceptions that are not caught

    Eg..#include

    usingnamespace std;

    int main () { try{

    throw 20;}

    catch (int e)

    {cout

  • 8/22/2019 Technical Question c c++

    16/17

    1. you can catch various types of errors (you aren't restricted to a single error class),

    2. different levels of code can catch different exceptions,

    3. you don't have to worry about checking errors unless you want to ignore or handle a

    particular case,

    4. code is generally more readable (the 'return' value is reclaimed and the need for checkingerror states is reduced),

    5. exception-safe coding is more maintainable (return-anywhere safe as well) by more people,and

    6. much of the work that may be required in using API functions in an exception-safe manner

    can be hidden by good programmers in good class wrappers to be used by all.

    Disadvantages

    The disadvantage of exceptions is that you need to enable exception handling in the

    compiler with the penalty of the overhead in creating bunches of extra stack frames, andall code where exceptions can be thrown must be written in an exception safe manner

    What is a template?

    A template describes a set of related classes or set of related functions in which a list of

    parameters in the declaration describe how the members of the set vary. The compilergenerates new classes or functions when you supply arguments for these parameters; this

    process is called template instantiation. This class or function definition generated from atemplate and a set of template parameters is called a specialization.

    What is an iterator?

    Iterators are used to access members of the container classes, and can be used in a similarmanner to pointers. For example, one might use an iterator to step through the elements

    of avector. There are several different types of iterators:

    What is an algorithm (in terms of the STL/C++ standard library)?The algorithms of STL can be divided into two groups by their memory access

    pattern:scanningalgorithms and random access algorithms. Scanning algorithms work

    with Input, Output, Forward, and Bidirectional iterators only. Since random accessoperations are not allowed with these kinds of iterators, the algorithms inherently exhibit

    strong spatial locality of reference. Random access

    algorithms requireRandomAccess iterators, hence may perform many random I/Os4. Forsuch algorithms, STXXL provides specialized I/O-efficient implementations that work

    with STL-user layer external memory containers

    What is std::auto_ptr?

    auto_ptr owns a dynamically allocated object and performs automatic cleanup when the

    object is no longer needed. Here's a simple example of code that's unsafe

    without auto_ptr:// Example 1(a): Original code

    //

    void f(){

    T* pt( new T );

    /*...more code...*/

    http://www.cppreference.com/cppvector/index.htmlhttp://www.cppreference.com/cppvector/index.htmlhttp://i10www.ira.uka.de/dementiev/stxxl/report/footnode.html#foot648http://i10www.ira.uka.de/dementiev/stxxl/report/footnode.html#foot648http://www.cppreference.com/cppvector/index.htmlhttp://i10www.ira.uka.de/dementiev/stxxl/report/footnode.html#foot648
  • 8/22/2019 Technical Question c c++

    17/17

    delete pt;

    }

    Most of us write code like this every day. If f() is a three-line function that doesn't doanything exceptional, this may be fine. But if f() never executes the delete statement,

    either because of an early return or because of an exception thrown during execution of

    the function body, then the allocated object is not deleted and we have a classic memoryleak.

    A simple way to make Example 1(a) safe is to wrap the pointer in a "smarter" pointer-like

    object that owns the pointer and that, when destroyed, deletes the pointed-at objectautomatically. Because this smart pointer is simply used as an automatic object (that is,

    one that's destroyed automatically when it goes out of scope), it's reasonably called an

    "auto" pointer:

    // Example 1(b): Safe code, with auto_ptr//

    void f()

    {

    auto_ptr pt( new T );/*...more code...*/

    } // cool: pt's destructor is called as it goes out// of scope, and the object is deleted automatically

    What are the debugging methods you use when came across a problem?Ans: Debugging with tools like :

    GDB, DBG, Forte, Visual Studio.

    Analyzing the Core dump.

    Using tusc to trace the last system call before crash.

    Putting Debug statements in the program source code.

    How do you know that your class needs a virtual destructor?Ans: If your class has at least one virtual function, you should make a destructor for this

    class virtual. This will allow you to delete a dynamic object through a pointer to a base

    class object. If the destructor is non-virtual, then wrong destructor will be invoked duringdeletion of the dynamic object.