Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • C++ Interview Questions and Answers Part 3

    • 0
    • 4
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 323
    Comment on it

    In the previous part, C++ Interview Questions and Answers Part 1 and Part 2, we have explained some basic questions of C++. This part is in continuation with the previous C++ Interview Questions and Answers tutorial. In this part of the tutorial we will proceed with more questions based on further concepts of C++.

    1. How many storage classes are available in C++?

    2. A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ program. These specifiers precede the type that they modify.

    Following storage classes are available in C++:

    • auto
    • The auto storage class is the default storage class for all local variables.
    void modifyVal(void)
    {  
         auto int a = 1 ;   a++;   
         cout<< a ;   
    }
    int main()
    {   
        modifyVal();  
         modifyVal();   
        modifyVal();   
        modifyVal();   
        return 0;
    } 
    Output:-2 2 2 2
    

    In the above example, every time the method modifyVal is invoked, memory is allocated for variable a and de allocated at the end of the method. So it's output will be same.

    • register
    • The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). This is used for frequently accessed variables like counters, to improve performance. Note that, declaring a variable as register does not mean that they will be stored in the register. It depends on the hardware and implementation.
        int main()
        {   
            register int i;  
             int arr[5] = {5,6,7,8,9};              
            for (i=0;i<10;i++)   
            {     
                  cout<< arr[i ];       
             }      
            return 0;
        } 
    
    Output:- 5 6 7 8 9
    

    The variable i might be stored on the CPU register and due to which the access of i in the loop will be faster.

    • static
    • The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. When we use static keyword with global variables, they will have internal linkage, that means it cannot be accessed by other source files. But when we use static keyword in case of a class member, it will be shared by all the objects of a class instead of creating separate copies for each object.
    void modifyVal(void)
    {   
        static int i = 1 ;  
         i++;  
          cout<< i ;    
    } 
    int main()
    {  
         modifyVal();  
         modifyVal();   
        modifyVal();  
         modifyVal();  
         return 0;
    }
    
     Output:-2 3 4 5
    

    As there will be the existance of static variable i till the end of program, it will retain it's value across the method invocations.

    • extern
    • The extern storage class is used to give a reference of a global variable that is visible to all the program files. It is used to tell compiler that the symbol is defined in another files and not in the current one and use to linked externally. Since no storage is allocated for extern variable as part of declaration, they cannot be initialized while declaring. FIRST FILE: int count; extern void write_extern( ); main() { count=5; write_extern(); } SECOND FILE: extern int count; void write_extern(void) { std::cout<< Count is <
    • mutable
    • This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.
     class Sample
        {    
            public:        Test(): a(1), b(1) {};        
            mutable int a;        
            int b;
        }; 
        int main()
        {   
         const Sample object;   
         object.a = 123;    //object.y = 123;    /*      * The above line if uncommented, will create compilation error.     */       
        cout<< "A:"<< object.a << ", B:" << object.b;    
        return 0;
        } 
    
       Output:-X:123, Y:1
    

    In the above example, the value of member variable a can be change though it's part of an object is declared as const. It is due to the variable a is declared as mutable. But if we try to modify the value of variable y, compiler will throw error.

    Here is the summary of c++ storage class specifiers below

    C++ storage specifier Storage location Scope Of variable Life time
    auto Memory (RAM) Local With in function
    static Memory (RAM) Local Life time is from when the flow reaches the first declaration to the termination of program.
    register CPU register Local With in function
    extern Memory (RAM) Global Till the end of main program
    1. What is 'Copy Constructor' and when it is called?

    2. Copy constructor is a special constructor of a class which is used to create copy of an object. If you don't define the constructor in the class then compiler will call the default copy constructor. If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor.
    class Sample 
    {           
         public:                int* s;             
           Sample();                // Copy constructor declaration                
        Sample(Sample&obj);      
      };         
    Sample::Sample()
    {            
        s = new int();            
        *s= 5;        
    }         
    
    Sample::Sample(Sample &obj)
    {          
          s = new int();            //create a new object for the pointer   
              *s = *(obj.s);  // Now manually assign the value  
              cout<<"Copy constructor...\n";       
     }
    
    1. What is realloc() and free()? What is difference between them?

    • void* realloc (void* ptr, size_t size)
    • The realloc() function is used to change the size of allocated area. The first argument specifies the address of an area that is currently allocated to the size in bytes of the modified second argument. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an invalid pointer, then defined behaviour may occur depending the implementation. Undefined behaviour may occur if the ptr has previously been deallocated by free(), or dealloc() or ptr do not match a pointer returned by an malloc(), calloc() or realloc().
    • void free (void* ptr)
    • This free() function is used to deallocate a block of memory that use to be allocated using malloc(), calloc() or realloc(). If ptr is null, this function does nothing.
    1. What is difference between shallow copy and deep copy? Which is default?

    2. [This question is frequently asked in the interviews, not just c++ interviews, but also in the java interviews] When a shallow copy is done, all the fields of the source object is copied to target object as it is. It means that if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not the desired result.
      In case of deep copy, it does not copy the pointer, rather the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, custom copy constructor need to be created and assignment operator should be overridden.
    1. What do you mean by persistent and non-persistent objects?

    2. Persistent objects are those objects which can be serialized and written to disk, or any other stream. The objects can be serialized before stopping the application and can be de-serialized on restart. ( Drawing applications usually use serializations.) The objects that can not be serialized are called non-persistent objects. ( Usually database objects are not serialized )
    1. Is it possible to get the source code back from binary file?

    2. It is possible to generate the source code from binary. This process is known as reverse engineering. Now, various reverse engineering tools are available. As most of the information will be lost due to compiler optimization and other interpretations, therefore they will not able to regenerate the exact code.

    In the next session, we will continue with other important C++ questions asked by Interviewer.

  • Reference :-

    http://www.tutorialspoint.com/
    http://a4academics.com/

Comment on it

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: