Pages

180 [Latest] C++ Interview Questions and Answers

Hiried C++ Interview Questions and Answers PDF

Write A Program That Will Convert An Integer Pointer To An Integer And Vice-versa.
The following program demonstrates this.
#include<stdio.h>
#include<iosream>
#include<conio.h>
void main( )
{
    int i = 65000 ;
    int *iptr = reinterpret_cast ( i ) ;
    cout << endl << iptr ;
    iptr++ ;
    cout << endl << iptr ;
    i = reinterpret_cast ( iptr ) ;
    cout << endl << i ;
    i++ ;
    cout << endl << i ;
}

What Is Meant By Const_cast?
The const_cast is used to convert a const to a non-const. This is shown in the following program:
#include
void main( )
{
     const int a = 0  ;
     int *ptr = ( int * ) &a ; //one way
     ptr = const_cast_ ( &a ) ; //better way
}
Here, the address of the const variable a is assigned to the pointer to a non-const variable. The const_cast is also used when we want to change the data members of a class inside the const member functions. The following code snippet shows this:
class sample
{
    private:
    int data;
    public:
      void func( ) const
      {
        (const_cast (this))->data = 70 ;
      }
};

What Is Meant By Forward Referencing And When Should It Be Used?
Forward referencing is generally required when we make a class or a function as a friend.Consider following program:
class test
{
    public:
        friend void fun ( sample, test ) ;
} ;

class sample
{
    public:
        friend void fun ( sample, test ) ;
} ;

void fun ( sample s, test t )
{
    // code
}

void main( )
{
    sample s ;
    test t ;
    fun ( s, t ) ;
}
On compiling this program it gives error on the following statement of test class. It gives an error that sample is undeclared identifier. friend void fun ( sample, test ) ; This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample.
class sample;
Tricky C++ Interview Questions And Answers

Write My Own Zero-argument Manipulator That Should Work Same As Hex?
This is shown in following program.
#include
ostream& myhex ( ostream &o )
{
  o.setf ( ios::hex) ;
  return o ;
}
void main( )
{
  cout << endl << myhex << 2000 ;
}

We All Know That A Const Variable Needs To Be Initialized At The Time Of Declaration. Then How Come The Program Given Below Runs Properly Even When We Have Not Initialized P?
#include<iostream>
Void Main( )
{
      Const Char *p ;
      P = "a Const Pointer" ;
      Cout << P ;
}
The output of the above program is 'A const pointer'. This is because in this program p is declared as 'const char*' which means that value stored at p will be constant and not p and so the program works properly.

Refer To A Name Of Class Or Function That Is Defined Within A Namespace?
There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example:
namespace name1
{
    class sample1
    {
         // code
    } ;
}
namespace name2
{
     class sample2
     {
         // code
     } ;
}
using namespace name2 ;
void main( )
{
      name1::sample1 s1 ;
      sample2 s2 ;
}
Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.

Is It Possible To Provide Default Values While Overloading A Binary Operator?
No!. This is because even if we provide the default arguments to the parameters of the overloaded operator function we would end up using the binary operator incorrectly. This is explained in the following example:
sample operator + ( sample a, sample b = sample (2, 3.5f ) )
{
}

void main( )
{
    sample s1, s2, s3 ;
    s3 = s1 + ; // error
}

Carry Out Conversion Of One Object Of User-defined Type To Another?
To perform conversion from one user-defined type to another we need to provide conversion function. Following program demonstrates how to provide such conversion function.
class circle
{
    private :
       int radius ;
       public:
          circle ( int r = 0 )
          {
             radius = r ;
          }
} ;
class rectangle
{
     private :
        int length, breadth ;
        public :
           rectangle( int l, int b )
           {
              length = l ;
              breadth = b ;
           }
           operator circle( )
           {
               return circle ( length ) ;
           }
} ;
void main( )
{
    rectangle r ( 20, 10 ) ;
    circle c;
    c = r ;
}
Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment operator in the class circle which accepts the object of type rectangle. Since there is no such overloaded assignment operator, the conversion operator function that converts the rectangle object to the circle object is searched in the rectangle class. We have provided such a conversion function in the rectangle class. This conversion operator function returns a circle object. By default conversion operators have the name and return type same as the object type to which it converts to. Here the type of the object is circle and hence the name of the operator function as well as the return type is circle.

Write Code That Allows To Create Only One Instance Of A Class?
This is shown in following code snippet.
#include
class sample
{
    static sample *ptr ;
    private:
    sample( )
    {
    }
    public:
    static sample* create( )
    {
       if ( ptr == NULL )
          ptr = new sample ;
          return ptr ;
     }
} ;
sample *sample::ptr = NULL ;
void main( )
{
    sample *a = sample::create( ) ;
    sample *b = sample::create( ) ;
}
Here, the class sample contains a static data member ptr, which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.

Write Code To Add Functions, Which Would Work As Get And Put Properties Of A Class?
This is shown in following code.
#include

class sample
{
   int data ;
   public:
      __declspec ( property ( put = fun1, get = fun2 ) )
      int x ;
      void fun1 ( int i )
      {
         if ( i < 0 )
            data = 0 ;
         else
            data = i ;
       }
       int fun2( )
       {
          return data ;
       }
} ;

void main( )
{
    sample a ;
    a.x = -99 ;
    cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the given integer value into data, whereasfun2( ) returns the current value of data. To set these functions as properties of a class we havegiven the statement as shown below:
 __declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the value in data. On the other hand, the last statement would cause fun2( ) to get called to return the value of data.

Write A Program That Implements A Date Class Containing Day, Month And Year As Data Members. Implement Assignment Operator And Copy Constructor In This Class.
This is shown in following program:
#include

class date
{
     private :
        int day ;
        int month ;
        int year ;
     public :
        date ( int d = 0, int m = 0, int y = 0 )
        {
            day = d ;
            month = m ;
            year = y ;
        }
        // copy constructor
        date ( date &d )
        {
            day = d.day ;
            month = d.month ;
            year = d.year ;
        }
        // an overloaded assignment operator
        date operator = ( date d )
        {
            day = d.day ;
            month = d.month ;
            year = d.year ;
            return d ;
        }
        void display( )
        {
            cout << day << "/" << month << "/" << year ;
        }
} ;
void main( )
{
        date d1 ( 25, 9, 1979 ) ;
        date d2 = d1 ;
        date d3 ;
        d3 = d2 ;
        d3.display( ) ;
}

When Should I Use Unitbuf Flag?
The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character is output as soon as it is inserted into an output stream. The same can be done using unbuffered output but unit buffering provides a better performance than the unbuffered output.

What Are Manipulators?
Manipulators are the instructions to the output stream to modify the output in various ways. The manipulators provide a clean and easy way for formatted output in comparison to the formatting flags of the ios class. When manipulators are used, the formatting instructions are inserted directly into the stream. Manipulators are of two types, those that take an argument and those that don't.

Differentiate Between The Manipulator And Setf( ) Function?
The difference between the manipulator and setf( ) function are as follows:
The setf( ) function is used to set the flags of the ios but manipulators directly insert the formatting instructions into the stream. We can create user-defined manipulators but setf( ) function uses data members of ios class only. The flags put on through the setf( ) function can be put off through unsetf( ) function. Such flexibility is not available with manipulators.

How To Get The Current Position Of The File Pointer?
We can get the current position of the file pointer by using the tellp( ) member function of ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions of put pointer and get pointer respectively.

What Are Put And Get Pointers?
These are the long integers associated with the streams. The value present in the put pointer specifies the byte number in the file from where next write would take place in the file. The get pointer specifies the byte number in the file from where the next reading should take place.

What Does The Nocreate And Noreplace Flag Ensure When They Are Used For Opening A File?
nocreate and noreplace are file-opening modes. A bit in the ios class defines these modes. The flag nocreate ensures that the file must exist before opening it. On the other hand the flag noreplace ensures that while opening a file for output it does not get overwritten with new one unless ate or app is set. When the app flag is set then whatever we write gets appended to the existing file. When ate flag is set we can start reading or writing at the end of existing file.

What Is The Limitation Of Cin While Taking Input For Character Array?
To understand this consider following statements,
       char str[5] ;
cin >> str ;
While entering the value for str if we enter more than 5 characters then there is no provision in cin to check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using get( ) function. For example, consider following statement,cin.get ( str, 5 ) ; On executing this statement if we enter more than 5 characters, then get( ) takes only first five characters and ignores rest of the characters. Some more variations of get( ) are available, such as shown below:
get ( ch ) - Extracts one character only get ( str, n ) - Extracts up to n characters into str get ( str, DELIM ) - Extracts characters into array str until specified delimiter (such as '\n'). Leaves delimiting character in stream.
get ( str, n, DELIM ) - Extracts characters into array str until n characters or DELIM character, leaving delimiting character in stream.

Mention The Purpose Of Istream Class?
The istream class performs activities specific to input. It is derived from the iosclass. The most commonly used member function of this class is the overloaded >> operator which canextract values of all basic types. We can extract even a string using this operator.

Would The Following Code Work?
 #include<iosteram.>
Void Main( )
 {
 Ostream O ;
 O << "dream. Then Make It Happen!" ;
}
No This is because we cannot create an object of the iostream class since its constructor and copy constructorare declared private.

Can We Use This Pointer Inside Static Member Function?
No! The this pointer cannot be used inside a static member function. This is because a static member function is never called through an object.

What Is Strstream?
strstream is a type of input/output stream that works with the memory. It allows using section of the memory as a stream object. These streams provide the classes that can be used for storing the stream of bytes into memory. For example, we can store integers, floats and strings as a stream of bytes. There are several classes that implement this in-memory formatting. The class ostrstream derived from ostream is used when output is to be sent to memory, the class istrstream derived from istream is used when input is taken from memory and strstream class derived from iostream is used for memory objects that do both input and output.

When The Constructor Of A Base Class Calls A Virtual Function, Why Doesn't The Override Function Of The Derived Class Gets Called?
While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example.
#include

class base
{
   protected :
     int i ;
     public :
       base ( int ii = 0 )
       {
           i = ii ;
           show( ) ;
       }

       virtual void show( )
       {
            cout << "base's show( )" << endl ;
       }
} ;

class derived : public base
{
      private :
        int j ;
      public :
        derived ( int ii, int jj = 0 ) : base ( ii )
        {
           j = jj ;
           show( ) ;
        }
       void show( )
       {
           cout << "derived's show( )" << endl ;
       }
} ;
                             
void main( )
{
   derived dobj ( 20, 5 ) ;
}
The output of this program would be:
base's show( )
derived's show(

Can I Have A Reference As A Data Member Of A Class? If Yes, Then How Do I Initialise It?
Yes, we can have a reference as a data member of a class. A reference as a data member of a class is initialised in the initialisation list of the constructor. This is shown in following program.
#include
class sample
{
   private :
     int& i ;
     public :
       sample ( int& ii ) : i ( ii )
       {
       }
       void show( )
       {
         cout << i << endl ;
       }
} ;

void main( )
{
  int j = 10 ;
  sample s ( j ) ;
  s.show( ) ;
}
Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a reference to an object passed to the constructor as a value. If we do so, then the reference i would refer to the function parameter (i.e. parameter ii in the constructor), which would disappear as soon as the function returns, thereby creating a situation of dangling reference.

Why Does The Following Code Fail?
#include<iostream.>
#include<string.h>
Class Sample
{
Private :char *str ;
Public : Sample ( Char *s )
{
Strcpy ( Str, S ) ;
}
~sample( )
{
Delete Str ;
}
} ;
Void Main( )
{
Sample S1 ( "abc" ) ;
}
Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor.
sample ( char *s )
{
   str = new char[strlen(s) + 1] ;
   strcpy ( str, s ) ;
}
Here, first we have allocated memory of required size, which then would get deal located through the destructor.

Assert( ) Macro...
We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro expands to an if statement. If test evaluates to 0, assert prints an error message and calls abort to abort the program.
#include
#include
void main( )
{
   int i ;
   cout << "\nEnter an integer: " ;
   cin >> i ;
   assert ( i >= 0 ) ;
   cout << i << endl ;
}

Why Is That Unsafe To Deal Locate The Memory Using Free( ) If It Has Been Allocated Using New?
This can be explained with the following example:
#include
class sample
{
  int *p ;
  public :
     sample( )
     {
       p = new int ;
     }

     ~sample( )
     {
        delete p ;
     }
} ;

void main( )
{
  sample *s1 = new sample ;
  free ( s1 ) ;
  sample *s2 = ( sample * ) malloc ( sizeof ( sample ) ) ;
  delete s2 ;
}
The new operator allocates memory and calls the constructor. In the constructor we have allocated memory on heap, which is pointed to by p. If we release the object using the free( ) function the object would die but the memory allocated in the constructor would leak. This is because free( ) being a C library function does not call the destructor where we have deal located the memory.
As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence p holds a garbage address. Now if the memory is deal located using delete, the destructor would get called where we have tried to release the memory pointed to by p. Since p contains garbage this may result in a runtime error.

Can We Distribute Function Templates And Class Templates In Object Libraries?
No! We can compile a function template or a class template into object code (.obj file). The code that contains a call to the function template or the code that creates an object from a class template can get compiled. This is because the compiler merely checks whether the call matches the declaration (in case of function template) and whether the object definition matches class declaration (in case of class template). Since the function template and the class template definitions are not found, the compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the matching definitions for the function call or a matching definition for object creation. In short the expanded versions of templates are not found in the object library. Hence the linker reports error.

Differentiate Between An Inspector And A Mutator ?
An inspector is a member function that returns information about an object's state (information stored in object's data members) without changing the object's state. A mutator is a member function that changes the state of an object. In the class Stack given below we have defined a mutator and an inspector.
class Stack
{
   public :
   int pop( ) ;
   int getcount( ) ;
}
In the above example, the function pop( ) removes top element of stack thereby changing the state of an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it simply counts the number of elements in the stack without changing the stack.

Namespaces:
The C++ language provides a single global namespace. This can cause problems with global name clashes. For instance, consider these two C++ header files: // file1.h float f ( float, int ) ; class sample { ... } ; // file2.h class sample { ... } ; With these definitions, it is impossible to use both header files in a single program; the sample classes will clash.A namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier thus avoids the possibility that a name will conflict with names declared elsewhere in the program. It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier. For example:
// file1.h
namespace file1
{
   float f ( float, int ) ;
   class sample { ... } ;
}
// file2.h
namespace file2
{
    class sample { ... } ;
}
Now the class names will not clash because they become file1::sample and file2::sample, respectively.

Declare A Static Function As Virtual?no. The Virtual Function Mechanism Is Used On The Specific Object That Determines Which Virtual Function To Call. Since The Static Functions Are Not Any Way Related To Objects, They Cannot Be Declared As Virtual.
No. The virtual function mechanism is used on the specific object that determines which virtual function to call. Since the static functions are not any way related to objects, they cannot be declared as virtual.

Can User-defined Object Be Declared As Static Data Member Of Another Class?
Yes. The following code shows how to initialize a user-defined object.
#include
class test
{
  int i ;
  public :
    test ( int ii = 0 )
    {
      i = ii ;
    }
} ;
class sample
{
  static test s ;
} ;
test sample::s ( 26 ) ;
Here we have initialized the object s by calling the one-argument constructor. We can use the same convention to initialize the object by calling multiple-argument constructor.

What Is A Forward Referencing And When Should It Be Used?
Consider the following program:
class test
{
   public :
     friend void fun ( sample, test ) ;
} ;

class sample
{
   public :
     friend void fun ( sample, test ) ;
} ;

void fun ( sample s, test t )
{
   // code
}

void main( )
{
   sample s ;
   test t ;
   fun ( s, t ) ;
}
This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of the class sample before the definition of class test. The following statement is the forward reference of class sample. Forward referencing is generally required when we make a class or a function as a friend.

What Is Virtual Multiple Inheritance?
A class b is defined having member variable i. Suppose two classes d1 and d2 are derived from class b and a class multiple is derived from both d1 and d2. If variable i is accessed from a member function of multiple then it gives error as 'member is ambiguous'. To avoid this error derive classes d1 and d2 with modifier virtual as shown in the following program.
#include
class b
{
  public :
    int i ;
  public :
    fun( )
    {
      i = 0 ;
    }
} ;
class d1 : virtual public b
{
  public :
    fun( )
    {
      i = 1 ;
    }
} ;
class d2 : virtual public b
{
  public :
    fun( )
    {
      i = 2 ;
    }
} ;
class multiple : public d1, public d2
{
  public :
    fun( )
    {
      i = 10 ;
    }
} ;
void main( )
{
   multiple d ;
   d.fun( ) ;
   cout << d.i ;
}

Can We Use This Pointer In A Class Specific, Operator-overloading Function For New Operator?
No! The this pointer is never passed to the overloaded operator new() member function because this function gets called before the object is created. Hence there is no question of the this pointer getting passed to operator new( ).

How To Allocate Memory Dynamically For A Reference?
No! It is not possible to allocate memory dynamically for a reference. This is because, when we create a reference, it gets tied with some variable of its type. Now, if we try to allocate memory dynamically for a reference, it is not possible to mention that to which variable the reference would get tied.

Write Code To Make An Object Work Like A 2-d Array?
Take a look at the following program.
#include
class emp
{
  public :
    int a[3][3] ;
    emp( )
    {
      int c = 1 ;
      for ( int i = 0 ; i <= 2 ; i++ )
      {
         for ( int j = 0 ; j <= 2 ; j++ )
         {
           a[i][j] = c ;
           c++ ;
         }
       }
     }
     int* operator[] ( int i )
     {
       return a[i] ;
     }
} ;
void main( )
{
  emp e ;
  cout << e[0][1] ;
}
The class emp has an overloaded operator [ ] function. It takes one argument an integer representing an array index and returns an int pointer. The statement cout << e[0][1] ; would get converted into a call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that represents the base address of the zeroeth row. Next the statement would get expanded as base address of zeroeth row[1] that can be further expanded as *( base address + 1 ). This gives us a value in zeroth row and first column.

What Are Formatting Flags In Ios Class?
The ios class contains formatting flags that help users to format the stream data. Formatting flags are a set of enum definitions. There are two types of formatting flags:On/Off flagsFlags that work in-group The On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( )function. To set the On/Off flags, the one argument setf( ) function is used. The flags working in groups are set through the two-argument setf( ) function. For example, to left justify a string we can set the flag as,
cout.setf ( ios::left );
cout << "KICIT Nagpur";
To remove the left justification for subsequent output we can say,
cout.unsetf ( ios::left );
The flags that can be set/unset include skipws, showbase, showpoint, uppercase, showpos, unitbufand stdio. The flags that work in a group can have only one of these flags set at a time.

What Is The Purpose Of Ios::basefield In The Following Statement?
cout.setf ( Ios::hex, Ios::basefield );
This is an example of formatting flags that work in a group. There is a flag for each numbering system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If we set the hex flag as setf ( ios::hex ) then we will set the hex bit but we won't clear the dec bit resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This call first clears all the bits and then sets the hex bit.

Can We Get The Value Of Ios Format Flags?
Yes! The ios::flags( ) member function gives the value format flags. This function takes no arguments and returns a long ( typedefed to fmtflags) that contains the current format flags.

Is There Any Function That Can Skip Certain Number Of Characters Present In The Input Stream?
Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown below:
istream& ignore ( int n = 1, int d =EOF );
Sometimes it happens that some extra characters are left in the input stream while taking the input such as, the '\n' (Enter) character. This extra character is then passed to the next input and may pose problem.
To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to fflush ( stdin ) used in C language. This function ignores the first n characters (if present) in the input stream, stops if delimiter d is encountered.

When Should Overload New Operator On A Global Basis Or A Class Basis?
We overload operator new in our program, when we want to initialize a data item or a class object at the same place where it has been allocated memory. The following example shows how to overload new operator on global basis.
#include
#include
void * operator new ( size_t s )
{
   void *q = malloc ( s ) ;
   return q ;
}
void main( )
{
  int *p = new int ;
  *p = 25 ;
  cout << *p ;
}
When the operator new is overloaded on global basis it becomes impossible to initialize the data members of a class as different classes may have different types of data members. The following example shows how to overload new operator on class-by-class basis.
#include
#include
class sample
{
  int i ;
  public :
     void* operator new ( size_t s, int ii )
     {
       sample *q = ( sample * ) malloc ( s ) ;
       q -> i = ii ;
       return q ;
     }
} ;
class sample1
{
   float f ;
   public :
   void* operator new ( size_t s, float ff )
   {
     sample1 *q = ( sample1 * ) malloc ( s ) ;
     q -> f = ff ;
     return q ;
   }
 } ;
void main( )
{
  sample *s = new ( 7 ) sample ;
  sample1 *s1 = new ( 5.6f ) sample1 ;
}
Overloading the operator new on class-by-class basis makes it possible to allocate memory for an object and initialize its data members at the same place.

How To Give An Alternate Name To A Namespace?
An alternate name given to namespace is called a namespace-alias. namespace-alias is generally used to save the typing effort when the names of namespaces are very long or complex. The following syntax is used to give an alias to a namespace.
namespace myname = my_old_very_long_name ;

Define A Pointer To A Data Member Of The Type Pointer To Pointer?
The following program demonstrates this...
#include
class sample
{
  public :
    sample ( int **pp )
    {
      p = pp ;
    }
    int **p ;
} ;
int **sample::*ptr = &sample::p ;
void main( )
{
  int i = 9 ;
  int *pi = &i ;
  sample s ( Ï€ ) ;
  cout << ** ( s.*ptr ) ;
}

Using A Smart Pointer Can We Iterate Through A Container?
Yes. A container is a collection of elements or objects. It helps to properly organize and store the data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate through a container using a smart pointer.
#include
class smartpointer
{
  private :
     int *p ; // ordinary pointer
     public :
     smartpointer ( int n )
     {
       p = new int [ n ] ;
       int *t = p ;
       for ( int i = 0 ; i <= 9 ; i++ )
         *t++ = i * i ;
     }
     int* operator ++ ( int )
     {
       return p++ ;
     }
     int operator * ( )
     {
       return *p ;
     }
} ;
void main( )
{
   smartpointer sp ( 10 ) ;
   for ( int i = 0 ; i <= 9 ; i++ )
     cout << *sp++ << endl ;
}
Here, sp is a smart pointer. When we say *sp, the operator * ( ) function gets called. It returns the integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It increments p to point to the next element in the array and then returns the address of this new location.

Is It Possible For The Objects To Read And Write Themselves?
Yes! This can be explained with the help of following example:
#include
#include
class employee
{
  private :
     char name [ 20 ] ;
     int age ;
     float salary ;
     public :
     void getdata( )
     {
       cout << "Enter name, age and salary of employee : " ;
       cin >> name >> age >> salary ;
     }
     void store( )
     {
       ofstream file ;
       file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ;
       file.write ( ( char * ) this, sizeof ( *this ) ) ;
       file.close( ) ;
     }
     void retrieve ( int n )
     {
       ifstream file ;
       file.open ( "EMPLOYEE.DAT", ios::binary ) ;
       file.seekg ( n * sizeof ( employee ) ) ;
       file.read ( ( char * ) this, sizeof ( *this ) ) ;
       file.close( ) ;
     }
     void show( )
     {
       cout << "Name : " << name
       << endl << "Age : " << age
       << endl << "Salary :" << salary << endl ;
     }
} ;
void main( )
{
   employee e [ 5 ] ;
   for ( int i = 0 ; i <= 4 ; i++ )
   {
     e [ i ].getdata( ) ;
     e [ i ].store( ) ;
   }
   for ( i = 0 ; i <= 4 ; i++ )
   {
     e [ i ].retrieve ( i ) ;
     e [ i ].show( ) ;
   }
}
Here, employee is the class whose objects can write and read themselves. The getdata( ) function has been used to get the data of employee and store it in the data members name, age and salary. The store( ) function is used to write an object to the file. In this function a file has been opened in append mode and each time data of current object has been stored after the last record (if any) in the file.Function retrieve( ) is used to get the data of a particular employee from the file. This retrieved data has been stored in the data members name, age and salary. Here this has been used to store data since it contains the address of the current object. The function show( ) has been used to display the data of employee.

Why Is It Necessary To Use A Reference In The Argument To The Copy Constructor?
If we pass the copy constructor the argument by value, its copy would get constructed using the copy constructor. This means the copy constructor would call itself to make this copy. This process would go on and on until the compiler runs out of memory. This can be explained with the help of following example:
class sample
{
   int i ;
   public :
   sample ( sample p )
   {
     i = p.i ;
   }
} ;
void main( )
{
   sample s ;
   sample s1 ( s ) ;
}
While executing the statement sample s1 ( s ), the copy constructor would get called. As the copy construct here accepts a value, the value of s would be passed which would get collected in p. We can think of this statement as sample p = s. Here p is getting created and initialized. Means again the copy constructor would get called. This would result into recursive calls. Hence we must use a reference as an argument in a copy constructor.

What Is C++?
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.
C++ used for:
C++ is a powerful general-purpose programming language. It can be used to create small programs or large applications. It can be used to make CGI scripts or console-only DOS programs. C++ allows you to create programs to do almost anything you need to do. The creator of C++, Bjarne Stroustrup, has put together a partial list of applications written in C++.

What Is A Modifier In C++?
A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as 'mutators'. Example: The function mod is a modifier in the following code snippet:
class test
{
int  x,y;
public:
test()
{
x=0; y=0;
}
void mod()
{  x=10;
y=15;
}
};

What Is An Accessor In C++?
An accessor is a class operation that does not modify the state of an object in C++. The accessor functions need to be declared as const operations.

Differentiate Between A Template Class And Class Template In C++?
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.

When Does A Name Clash Occur In C++?
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.

Define Namespace In C++?
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.

What Is The Use Of 'using' Declaration In C++?
A using declaration in C++ makes it possible to use a name from a namespace without the scope operator.

What Is An Iterator Class In C++?
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.

What Is An Incomplete Type In C++?
Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification.
int *i=0x400    //i points to address 400
*i=0;          //set the  value of memory location pointed by i.
Incomplete types are otherwise called uninitialized pointers.

What Is A Dangling Pointer In C++?
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. The following code snippet shows this:
class Sample
{
public:int *ptr; Sample(int i)
{
ptr = new  int(i);
}
~Sample()
{
delete ptr;
}
void PrintValO
{
cout« "The value is " « *ptr;
}
};
void SomeFunc(Sample  x)
{
cout« "Say i am in someFunc " « endl;
}
int main()
{
Sample si = 10;
SomeFunc(sl);
sl.PrintVal();
}
In the above example when PrintVal() function is called it is called by the pointer that has been freed by the destructor in SomeFunc.

Differentiate Between The Message And Method In C++?
Message in C++ :
1. Objects communicate by sending messages to each other.
2. A message is sent to invoke a method in C++.
Method in C++ :
3. Provides response to a message.
4. It is an implementation of an operation in C++.

What Is An Adaptor Class Or Wrapper Class In C++?
A class that has no functionality of its own is an Adaptor class in C++. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non-object-oriented implementation.

What Is A Null Object In C++?
It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

What Is Class Invariant In C++?
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

What Do You Mean By Stack Unwinding In C++?
Stack unwinding in C++ 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.

Define Pre-condition And Post-condition To A Member Function In C++?
Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold. For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.
Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false. For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.

What Are The Conditions That Have To Be Met For A Condition To Be An Invariant Of The Class?
o The condition should hold at the end of every constructor.
o The condition should hold at the end of every mutator (non-const) operation.

What Are Proxy Objects In C++?
Objects that stand for other objects are called proxy objects or surrogates.
template <class t=""> class Array2D
{
public:
class Array ID
{
public:
T&operator[](int index);
const T&operator[](int index)const;
};
Array ID operator[] (int index);
const Array ID operator[] (int index) const;
};
The following then becomes legal:
Array2D<float>data(l0,20); cout«data[3][6]; // fine
Here data[3] yields an ArraylD object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array 2D class need not be aware of the presence of the ArraylD class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each ArraylD object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, ArraylD is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist.

Name Some Pure Object Oriented Languages?
pure object oriented languages are Smalltalk, Java, Eiffel, Sather.

What Is A Node Class In C++?
A node class is a class that,
0. relies on the base class for services and implementation.
1. provides a wider interface to the users than its base class.
2. relies primarily on virtual functions in its public interface.
3. depends on all its direct and indirect base class.
4. can be understood only in the context of the base class.
5. can be used as base for further derivation.
6. can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.

What Is An Orthogonal Base Class In C++?
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

What Is A Container Class? What Are The Types Of Container Classes In C++?
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 a well-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.

How Do You Write A Function That Can Reverse A Linked-list In C++?
void reverselist(void)
{  if(head==0)
return;
if(head-<next==0)
return;
if(head-<next==tail)
{
head-<next = 0;
tail-<next =  head;
}  else
{
node* pre = head;
node* cur = head-<next;
node* curnext = cur-<next; head-<next =  0; cur-<next = head;
for(; curnext !=0;)
{
cur-<next = pre;
pre = cur;
cur = curnext;
curnext = curnext-<next;
}
curnext-<next = cur;
}
}

What Is Polymorphism In C++?
Polymorphism in C++ is the idea that a base class can be inherited by several classes. A base class pointer can point to its child class and a base class array can store different child class objects.

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 second one 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 Can You Tell What Shell You Are Running On Unix System?
You can do the Echo $RANDOM. It will return a undefined variable if you are from the C-Shell, just a return prompt if you are from the Bourne shell, and a 5 digit random numbers if you are from the Korn shell. You could also do a ps -1 and look for the shell with the highest P(K).

What Is Boyce Codd Normal Form?
A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a->b, where a and b is a subset of R, at least one of the following holds:
o a->b is a trivial functional dependency (b is a subset of a).
o a is a superkey for schema R.

What Is Pure Virtual Function?
A class is made abstract by declaring one or more of its virtual functions to be pure. A pure virtual function is one with an initializer of = 0 in its declaration.
Write A Struct Time Where Integer M, H, S Are Its Members
struct Time
{
int m;
int h;
int s;
};

How Do You Traverse A Btree In Backward In-order?
0. Process the node in the right subtree.
1. Process the root.
2. Process the node in the left subtree.

What Is The Two Main Roles Of Operating System?
o As a resource manager.
o As a virtual machine.

In The Derived Class, Which Data Member Of The Base Class Are Visible?
In the public and protected sections.

What Is The Difference Between Realloc() And Free()?
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur.
The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

What Is Function Overloading And Operator Overloading?
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.
Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

What Is The Difference Between Declaration And Definition?
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.:
void stars () // declarator
{
for(intj=10;j > =0;j—) //function body
cout«*;
cout« endl; }

What Are The Advantages Of Inheritance In C++?
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.

How Do You Write A Function That Can Reverse A Linked-list?
void reverselist(void)
{
if(head==0)
return;
if(head->next==0)
return;
if(head->next==tail)
{
head->next = 0;
tail->next = head;
}  else
{
node* pre = head;
node* cur = head->next;
node* curnext = cur->next;
head->next = 0; cur-> next = head;
for(; curnext !=0;)
{
cur->next  = pre;
pre  = cur;
cur  = curnext;
curnext = curnext->next;
}
curnext->next = cur;
}
}

What Do You Mean By Inline Function?
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Write A Program That Ask For User Input From 5 To 9 Then Calculate The Average?
#include  &quot;iostream.h&quot; intmain()
{
intMAX = 4;
int total = 0;
int average; int  numb;
for  (int i=0; KMAX; i++) {
cout«
&quot;Please  enter your input between 5 and 9: &quot;;
cin  » numb;
while  (numb&lt;5 || numb&gt;9) {
cout« &quot;Invalid input, please re-enter: &quot;;
cin  » numb;
}
total = total + numb;
}
average  = total/MAX;
cout« &quot;The average number is: &quot;
« average « &quot;n&quot;;
 return 0;
}
Write A Short Code Using C++ To Print Out All Odd Number From 1 To 100 Using A For Loop
for( unsigned int i = 1; i < = 100; i++ )
if( l & 0x00000001 )
cout«i«",";

What Is Public, Protected, Private In C++?
o Public, protected and private are three access specifiers in C++.
o Public data members and member functions are accessible outside the class.
o Protected data members and member functions are only available to derived classes.
o Private data members and member functions can't be accessed outside the class. However there is an exception can be using friend classes.

Write A Function That Swaps The Values Of Two Integers, Using Int* As The Argument Type?
void swap(int* a, int*b)
{
intt;
t=*a;
*a = *b;
*b = t;
}

What Is Virtual Constructors/destructors?
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object. There is a simple solution to this problem declare a virtual base-class destructor.
This makes all derived-class destructors virtual even though they don't have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.

What Is The Difference Between An Array And A List?
o Array:  is collection of homogeneous elements.
o List :is collection of heterogeneous elements.
o  Array: memory allocated is static and continuous.
o  List:  memory allocated is dynamic and Random.
o Array:  User need not have to keep in track of next memory allocation.
o List:  User has to keep in Track of next location where memory is allocated.
Does C++ Support Multilevel And Multiple Inheritance?
Yes.

What Is A Template In C++?
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:
template <class indetifier> functiondeclaration; template <typename indetifier> functiondeclaration;
The only difference between both prototypes is the use of keyword class or typename, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Define A Constructor - What It Is And How It Might Be Called (2 Methods).
constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized.
Ways of calling constructor:
0. Implicitly: automatically by complier when an object is created.
1. Calling the constructors explicitly is possible, but it makes the code unverifiable.

You Have Two Pairs: New() And Delete() And Another Pair : Alloc() And Free(). Explain Differences Between Eg. New() And Malloc()
0. "new and delete" are preprocessors while "malloc() and free()" are functions, [we dont use brackets will calling new or delete].
1. no need of allocate the memory while using "new" but in "malloc()" we have to use "sizeof()".
2. "new" will initlize the new memory to 0 but "malloc()" gives random value in the new alloted memory location [better to use calloc()]

What Is The Difference Between Class And Structure In C++?
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

What Is Rtti In C++?
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many homegrown versions with a solid, consistent approach.

What Is Encapsulation In C++?
Packaging an object's variables within its methods is called encapsulation.

What Is A C++ Object?
Object is a software bundle of variables and related methods. Objects have state and behavior.
Describe Private, Protected And Public - The Differences And Give Examples.
class Point2D{ int x; int y;
public int color;
protected bool pinned;
public Point2D():x(0),y(0){} //default(no argument) constructor
};
Point2D MyPoint;
You cannot directly access private data members when they are declared (implicitly) private:
MyPoint.x = 5;          // Compiler will issue a compile ERROR
//Nor yoy can see them:
int xdim = MyPoint.x;  // Compiler will issue a compile ERROR
On the other hand, you can assign and read the public data members:
MyPoint.color = 255;      //no problem
int col = MyPoint.color; // no problem
With protected data members you can read them but not write them:
bool isPinned = MyPoint.pinned; // no problem.

Stl Containers - What Are The Types Of Stl Containers?
There are 3 types of STL containers:
0. Adaptive containers like queue, stack.
1. Associative containers like set, map.
2. Sequence containers like vector, deque.

Rtti - What Is Rtti In C++?
RTTI stands for "Run Time Type Identification". In an inheritance hierarchy, we can find out the exact type of the objet of which it is member. It can be done by using:
0. dynamic id operator.
1. typecast operator.

Assignment Operator - What Is The Diffrence Between A "assignment Operator" And A "copy Constructor"?
In assignment operator, you are assigning a value to an existing object. But in copy constructor, you are creating a new object and then assigning a value to that object.
For example:
complex cl,c2;
cl=c2;           //this is assignment
complex c3=c2;  //copy constructor.

If You Hear The Cpu Fan Is Running And The Monitor Power Is Still On, But You Did Not See Anything Show Up In The Monitor Screen. What Would You Do To Find Out What Is Going Wrong?
I would use the ping command to check whether the machine is still alive(connect to the network) or it is dead.

Can You Be Able To Identify Between Straight- Through And Cross- Over Cable Wiring? And In What Case Do You Use Straight- Through And Cross-over?
Straight-through is type of wiring that is one to connection, Cross- over is type of wiring which those wires are got switched We use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross¬over cable when connect between two NIC Adapters or sometime between two hubs.

What Are The Defining Traits Of An Object-oriented Language?
The defining traits of an object-oriented langauge are:
o encapsulation,
o inheritance,
o polymorphism.

What Methods Can Be Overridden In Java?
In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.

In C++, What Is The Difference Between Method Overloading And Method Overriding?
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

What Is The Difference Between Mutex And Binary Semaphore?
semaphore is used to synchronize processes, where as mutex is used to provide synchronization between threads running in the same process.

Are There Any New Intrinsic (built-in) Data Types?
Yes. The ANSI committee added the bool intrinsic type and its true and false value keywords.

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.
This solution assumes that two library vendors don't use the same namespace identifier, of course.

Describe Run-time Type Identification?
The ability to determine at run time the type of an object by using the typeid operator or the dynamiccast operator.

What Is The Standard Template Library (stl)?
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

What Is An Explicit Constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. It's purpose is reserved explicitly for construction.

What Is A Mutable Member?
One that can be modified by the class even when the object of the class or the member function doing the modification is const.

When Is A Template A Better Solution Than A Base Class?
When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the genericity) to the designer of the container or manager class.

Explain The Isa And Hasa Class Relationships. How Would You Implement Each In A Class Design?
A specialized class "is" a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee "has" a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

When Should You Use Multiple Inheritance?
There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

What Is The Difference Between A Copy Constructor And An Overloaded Assignment Operator?
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

What Is A Conversion Constructor C++?
A constructor that accepts one argument of a different type.

What Is A Default Constructor In C++?
Default constructor WITH arguments
class B {
public:
B(int m=0):n(m){}
int n;
};
int main(int argc, char *argv[])
{ Bb;
return 0;
}

How Does Throwing And Catching Exceptions Differ From Using Setjmp And Longjmp?
The throw operation calls the destructors for automatic objects instantiated since entry to the try block.

How Many Ways Are There To Initialize An Int With A Constant?
There are two ways for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
int foo = 123;
int bar (123);

What Are The Differences Between A C++ Struct And C++ Class?
The default member and base-class access specifiers are different.

Explain The Scope Resolution Operator?
It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

How Do You Link A C++ Program To C Functions?
By using the extern "C" linkage specification around the C function declarations.

How Do I Initialize A Pointer To A Function?
This is the way to initialize a pointer to a function
void fun(int a)
{
void main()
{
void (*fp)(int);
fp=fun;
fp(i);
}
}

What Does Extern Mean In A Function Declaration In C++?
It tells the compiler that a variable or a function exists, even if the compiler hasn't yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

How Do I Declare An Array Of N Pointers To Functions Returning Pointers To Functions Returning Pointers To Characters?
If you want the code to be even slightly readable, you will use typedefs.
typedef char* (*functiontype_one)(void);
typedef functiontypeone (*functiontype_two)(void);
functiontype_two myarray[N]; //assuming N is a const integral

What Is The Auto Keyword Good For In C++?
Local variables occur within a scope; they are "local" to a function. They are often called automatic variables because they automatically come into being when the scope is entered and automatically go away when the scope closes. The keyword auto makes this explicit, but local variables default to auto auto auto auto so it is never necessary to declare something as an auto auto auto auto.

What Is The Difference Between Char A[] = "string"; And Char *p = "string";?
In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.

What Can I Safely Assume About The Initial Values Of Variables Which Are Not Explicitly Initialized?
It depends on complier which may assign any garbage value to a variable if it is not initialized.

What Does Extern Mean In A Function Declaration?
Using extern in a function declaration we can make a function such that it can used outside the file in which it is defined.
An extern variable, function definition, or declaration also makes the described variable or function usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.
If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.

What Is The Best Way To Declare And Define Global Variables?
The best way to declare global variables is to declare them after including all the files so that it can be used in all the functions.

How Do You Decide Which Integer Type To Use?
It depends on our requirement. When we are required an integer to be stored in 1 byte (means less than or equal to 255) we use short int, for 2 bytes we use int, for 8 bytes we use long int.
A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte or 4-byte integer (though not necessarily), a long is a 4-byte integer, and a long long is a 8-byte integer.

Anything Wrong With This Code?
t*p = 0;
Delete P;
Yes, the program will crash in an attempt to delete a null pointer.

Anything Wrong With This Code?
t *p = Newt[10];
Delete P;
Everything is correct, Only the first element of the array will be deleted", The entire array will be deleted, but only the first element destructor will be called.

What Problems Might The Following Macro Bring To The Application?
#define sq(x) x*x

What Is An Html Tag?
An HTML tag is a syntactical construct in the HTML language that abbreviates specific instructions to be executed when the HTML script is loaded into a Web browser. It is like a method in Java, a function in C++, a procedure in Pascal, or a subroutine in FORTRAN.

Why Are Arrays Usually Processed With For Loop?
The real power of arrays comes from their facility of using an index variable to traverse the array, accessing each element with the same expression a[i]. All the is needed to make this work is a iterated statement in which the variable i serves as a counter, incrementing from 0 to a. length -1. That is exactly what a loop does.

What Is Polymorphism In C++? Explain With An Example?
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object. Example: function overloading, function overriding, virtual functions. Another example can be a plus '+' sign, used for adding two integers or for using it to concatenate two strings.

What Do You Mean By Pure Virtual Functions?
A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to zero.
class Shape
{
public: virtual void draw() = 0;
};

What Is A Scope Resolution Operator?
A scope resolution operator (::), can be used to define the member functions of a class outside the class.

What Is The Difference Between An External Iterator And An Internal Iterator? Describe An Advantage Of An External Iterator?
An internal iterator is implemented with member functions of the class that has items to step through. .An external iterator is implemented as a separate class that can be "attach" to the object that has items to step through. .An external iterator has the advantage that many difference iterators can be active simultaneously on the same object.

What Are Virtual Functions In C++?
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

What Is Abstraction In C++?
Abstraction is of the process of hiding unwanted details from the user.

Which Recursive Sorting Technique Always Makes Recursive Calls To Sort Subarrays That Are About Half Size Of The Original Array?
Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in 0(n log n) time.

What Is Friend Function In C++?
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

What Is A C++ Class?
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.

Suppose That Data Is An Array Of 1000 Integers. Write A Single Function Call That Will Sort The 100 Elements Data [222] Through Data [321]?
quicksort((data + 222),100);

What Is The Difference Between An Object And A Class?
Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.
o A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
o The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
o  An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

What Are 2 Ways Of Exporting A Function From A Dll?
1 .Taking a reference to the function from the DLL instance.
2. Using the DLL 's Type Library.

What Do You Mean By Binding Of Data And Functions?
Encapsulation.

What Is The Word You Will Use When Defining A Function In Base Class To Allow This Function To Be A Polimorphic Function?
virtual.

What Is Virtual Class And Friend Class?
Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.

What Is Boyce Codd Normal Form In C++?
A relation schema R is in BCNF with respect to a set F of functional dependencies if for all functional dependencies in F+ of the form a-> , where a and b is a subset of R, at least one of the following holds:
o a- > b is a trivial functional dependency (b is a subset of a).
o a is a superkey for schema R.

What Is A Copy Constructor And When Is It Called?
A copy constructor is a method that accepts an object of the same class and copies it's data members to the object on the left part of assignement:
class Point2D{ int x; int y;
public int color;
protected bool pinned;
public Point2D() : x(0),y(0){} //default (no argument)constructor
public Point2D( const Point2D & );
};
Point2D::Point2D( const Point2D & p )
{
this->x = p.x; this->y = p.y;
this->color = p.color;
this->pinned = p.pinned;
}
main()
{
Point2D MyPoint;
MyPoint.color  = 345;
Point2D AnotherPoint = Point2D( MyPoint);
// now AnotherPoint has color = 345

What Do You Mean By Inheritance?
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Can We Define A Constructor As Virtual In C++?
No, we cannot define constructors as virtual because constructors have the same name as their classes and no two constructors of base-derived classes can have the same name. So, when we initialize an object of the base or derived class with the help of virtual constructors, the base constructor is invoked instead of the derived constructor. Therefore, it is not possible to define a constructor as virtual.

Can We Declare A Base-class Destructor As Virtual?
Yes, we can declare a base-class destructor as virtual that makes all derived-class destructors as virtual even if they do not have the same name as base-destructor. The problem arises when the derived class's pointer refers to a base class. For this reason, the base class destructor should be declared as virtual so that the appropriate destructor is called on calling the delete method of the base class object.

How Does A Copy Constructor Differs From An Overloaded Assignment Operator?
A copy constructor uses the value of an argument to construct a new object. We can use an overload assignment operator to assign the value of an existing object of the same class to another existing object in that class.

Define The Process Of Error-handling In Case Of Constructor Failure?
If the constructor does not have the return statement, then it indicates failure in handling the error by throwing an exception.

What Is A Default Constructor?
A zero-argument constructor or a constructor in which all the arguments have default values is called a default constructor.
For example:
A Al; // default constructor called.

Define The Process Of Handling In Case Of Destructor Failure?
In order to handle a failed destructor, you need to write a message to a log file; however, do not throw an exception. There is a rule in C++ that exception cannot be thrown from a destructor, which is called when the process of "stack unwinding" occurs in other exceptions. For example, if someone says throw waste files(), the stack frames between the throw waste files() and the catch (waste files) will get popped. This is known as stack unwinding. It is the process of destroying all the local objects related to those stack frames and calling destructors in case of throwing of an exception by one of those destructors. For example, if an object named Bar is thrown, then the C++ runtime system is in a neutral situation means either to avoid the Bar and end up in the catch (waste files) or ignore the function Foo and look for a catch (Bar) handler. It will call in the terminate () process to end the program.

What Is A Virtual Destructor?
Virtual destructors help in destroying objects without knowing their type. With the help of the virtual function mechanism, the appropriate destructor for the object is invoked. In the case of abstract classes, destructors can also be declared as pure virtual functions. For example, class A derives from class B. Then, on calling the derived class dynamically at the execution time, the destructor will first call the derived class that is class A, and then the base class that is class B.
It is important to note that theVirtual keyword, when used with the destructor, ensures the calling of all the derived and base class destructors and therefore helps in the proper execution and closing of the program.

Can You Explicitly Call A Destructor On A Local Variable?
No, the destructor is called when the block closes in which the local variable was created.
If a destructor is called explicitly twice on the same object, the result ends in an undefined behavior because the local variable gets destroyed when the scope ends.

What Are Shallow And Deep Copies?
A shallow copy is used to copy actual values of the data. It means, if the pointer points to dynamically allocated memory, the new object's pointer in the copy still points to items inside the old objects and the returned object will be left pointing to items that are no longer in scope. A copy of the dynamically allocated objects is created with the help of a deep copy. This is done with the help of an assignment operator, which needs to be overloaded by the copy constructor.

What Do You Understand By Zombie Objects In C++?
In a situation, where an object is created in a class, a constructor fails before its full execution. It is very difficult to ensure about the execution of the constructor whether the constructor would return a value or not. Objects that are no more required for an application are called zombie objects. These zombie objects occupy a space in the memory and wait for their termination.

Should The This Pointer Can Be Used In The Constructor?
o We can use the this pointer in the constructor in the initialization list and also in the body. However, there is a feeling that the object is not fully formed so we should not use this pointer. Let's understand the use of the this pointer with the help of the following example. The declared data members of a base class and/or the declared data members of the constructor's own class can be accessed by the constructor {body} and/or a function called from the constructor. This is possible because of the full construction of constructor's body at the time of execution. The preceding example always works.
o The override in the derived class is not possible for a function called from the constructor and the {body} of a constructor which is independent of calling the virtual member function by the explicit use of the this pointer.
o Please make sure that the initialization of other data member has already been done before passing the data member to another data member's initializer in this object. With the help of some straightforward language rules (independent of the specific compiler that you are using), you can confirm about the determination of initialization of data members.
o Without the prior knowledge of these rules, there is no use of passing any data member from the this object.

What Do You Understand By A Pure Virtual Member Function?
A virtual function with no body structure is called a pure virtual member function. You can declare a pure virtual member function by adding the notation =0 to the virtual member function declaration. For example, area () is a virtual function, but when it is declared as shown in the following expression, it becomes a pure virtual member function: virtual int area () =0;
To avoid a compilation error, all the classes need to implement pure virtual classes that are derived from the abstract class.

How Can Virtual Functions In C++ Be Implemented?
When a class has at least one virtual function, the compiler builds a table of virtual function pointers for that class. This table, commonly called the v-table, contains an entry for each virtual function in the class. The constructor of the class is used to create this table. Each object of the class in memory includes a variable called the vptr, which points to the class's common vtbl. The _rst (which creates the vtable) is constructed by the base classes after the construction of the derived classes. The derived class constructor overwrites the entries of the vtable, if its constructor overrides any virtual function of the base class. Therefore, you need not call every function from a constructor just to avoid the error prone scenario of calling the Base class constructor instead of the derived class constructor (which fails to set the entries of objects of vtable).

What Do You Understand By Pure Virtual Function? Write About Its Use?
A pure virtual function in a base class must have a matching function in a derived class. A program may not declare an instance of a class that has a pure virtual function. A program may not declare an instance of a derived class if that derived class has not provided an overriding function for each pure virtual function in the base. If you want programmers to override certain functions in a class, such as those that need information customized for a particular installation, you should make these functions pure virtual.

How The Virtual Functions Maintain The Call Up?
The call is maintained through vtable. Each object includes a variable known as vptr, which points to the class's common vtable. It contains an entry for every virtual function. On calling the function, vtable calls the appropriate function using vptr.

Write A Note About Inheritance?
Inheritance is a mechanism that allows the object of one class to utilize the form and model or behavior of another class. A class derived from the base class inherits attributes, functions, or methods that implement the base class to the derived class and also extends the derived class by overriding functions and adding new additional attributes and functionalities.

What Is The Need Of Multiple Inheritance?
The multiple inheritance allows you to define a new class that inherits the characteristics of several base classes which are not related to each other. The vehicle class encapsulates the data and behavior that describe vehicles along with other information, such as date of purchase, life, and maintenance schedules. Classes that support specific kinds of vehicles, such as trucks, airplanes, and cars are also derived from the vehicle class. The asset class encapsulates the data and behavior of the organization's assets, including acquiring date, and depreciation schedule data for accounting purposes. A company car, being both a vehicle and an asset, is represented by a class that derives from both base classes.

How Can You Say That A Template Is Better Than A Base Class?
In case of designing a generic data type to manage objects of other data types which are unknown to their container class, a template is preferred over a base class. A template can contain more than one data type parameter, making it possible to build parameterized data types of considerable complexity. The class template also allows the declaration of more than one object in the same program.

Explain The Concept Of Multiple Inheritance (virtual Inheritance). Write About Its Advantages And Disadvantages?
Multiple inheritance is defined as the ability of a derived class to inherit the characteristics of more than one base class. For example, you might have a class zoo which inherits various animal classes. The advantage of multiple inheritance is that you can create a single derived class from several base classes. It helps in understanding the logic behind these complex relationships.

The multiple inheritance is not preferred by the programmers because with multiple base classes, there are chances of conflicts while calling a method in the sub class that exists in both the base classes. For example, if you have a class named zoo that inherits both the Anaconda and Zebra classes, then each base class might define a different version of the method walk, which creates a conflicting situation.

Describe Inheritance And Non-inheritance Of A Derived Class?
Using inheritance, you can derive all the data members and all the other common functions of the base class and still retain the functionality of the common methods of the base class. For example, the animal class with eat, sleep and breathe methods comprises the base class because they are common to all animals. Now, a new class Elephant with a method trumpet is derived from the class animal. With the help of inheritance, the Elephant class inherits the trumpet method and still retains the eat, sleep, and breathe methods from the base class, animal.

Therefore, you can add new methods to an existing class with the retaining of common methods. There are few methods that are not inherited on creating a derived class which includes constructors, destructors, and assignment operator methods of their base classes.

Write A Note About The Virtual Member Function?
A virtual function is a member function of the base class and relies on a specific object to determine which implementation of the function is called. However, a virtual function can be declared a friend of another class. If a function is declared virtual in a base class, you can still access it directly using the :: operator. Note that if you do not override a virtual member function in a derived class, a call to that function uses the function implementation defined in the base class.

Should The Member Functions Which Are Made Public In The Base Class Be Hidden?
As the public member functions of the base class are necessary to implement the public interface of the class, the member functions which are made public in the base class should never be hidden. When you are designing a class, make the derived data members private because a private member of the derived class is accessed through the protected or public member functions of the base class.

Can Circle Be Called An Ellipse?
Yes, a circle can be called an ellipse. Let's understand this concept with the help of an example, if ellipse has a member function named as setsize with the widthQ of the object as x and its height() as y. There are two kinds of relationships that exist between a circle and an ellipse:
o Circle and ellipse can be made as two different classes :
In this case, ellipse can be derived from AsymmetricShape class and has a member function named as setSize(x,y). On the contrary, circle can be derived from SymmetricalShape class and has a member function named as setSize(size). Therefore, they both are unrelated in its member functions as well as in their derivations.
o  Circle and ellipse can be derived from a base class :
In this case, circle and ellipse both can be inherited from the class Oval because class Oval can only have setSize(size) member function which sets the height() and widthQto the size of the object.

Latest C++ Interview questions Interview Questions for freshers and Experienced pdf

No comments:

Post a Comment