C++ Tips

  • Class is collection of data members and member fn.
  • Object is a instance of a class
  • Abstraction is hiding unessential things and reveal the essential things.
  • Encapsulation is wrapping up data and functions into a single unit Abstraction implies encapsulation.(Relationship between Abstraction and Encapsulation)
  • Inheritance is a process of crating new class form existing class.  The new class is called Derived class and the old class is called Base class Inheritance is mainly used to code reusability.In multiple inheritance occur an ambiguity error. But multilevel inheritance not occur an ambiguity error.
  • Composite is a opposite of Inheritance. It’s used to related between two distinct classes (unrelated classes).
  • Function overloading  function having same name with different signature in same class.
  • Operator overloading means to work on a different operand.
  • Function overriding function having same name with same signature in different class.
  • Polymorphism is ability to assure  several distinct forms(tasks). There are two type of polymorphism is available

                        i. static or compile time Polymorphism 
                      (Operator overloading and   function overloading)
ii.Dynamic or run time Polymorphism ( Virtual function)

  • Virtual functions work in overridden technique. Virtual fn is mainly used to, base class pointer can access derived class functions.
  • Abstract class means, a class which contain at least one pure virtual function. In abstract class cannot create an object.
  • Pure virtual function is a virtual function with expression equal to zero in declaration part.
  • Macro is a single line replacement of set of statements.
  • Inline is a keyword , its appear before function name. This function is faster than normal function. Inline function is a single line replacement of set of statements.

        Both (macro and inline function) functions are replaced a set of   
        statement. The statements are replaced in Pre-compilation Time 
        (Before compilation).

  • Inline functions are used in Type checking like normal function.  But macro won’t (Difference)
  • In structure , the default access specifies is Public.  But class , is Private (Difference)
  •  In structure,  the data members are associated in separate memory.  But Union, data members are shared in common memory. The size of union = Largest data member size in union (Difference).
  • New is operator, it’s overloaded, it’s call constructor automatically.  But malloc() is not overloaded and it’s cannot call constructor. But both are allocate memory.(Difference)
  • Malloc() and calloc() both are allocate memory. But malloc() allocate memory and store(initialize) the garbage value. But calloc() allocate memory, its allocate integer type then initialize zero its string initialize NULL value. (Difference)
  • Delete statement delete the all elements in an array, but the destructor call only the first element.delete[] statement delete the all element in an array, the destructor call each and every element in an array.(Difference)
  • Delete is a operator, it can be overload. Its call destructor call automatically. Delete operator mainly used to de-allocate memory. 
  • New is a operator , its overload operator. Its call constructor automatically. New operator mainly used to allocate memory.
  • Constructor is call automatically, whenever an object is created then the constructor is call.  Constructor is overload, it cannot return a value, and return type. 
  • Destructor is a call automatically, whenever an object is destroyed then the destructor will call.Its can’t overloaded, its cannot return a value and return type.
  • this pointer is a constant pointer. Its can use only non static member function. Its cannot used in static member function, because the static function share in all object but the this pointer points the current object.

      Explain this:

Ø   int (*p)[10]         ------     Pointer to array , first preference in pointer
Ø   int  *p[10]           ------     Array of pointer to int value , first      preference in array
Ø   int *f()                ------     function pointer
Ø   int (*f)()              ------     pointer to function

Which is the best sorting method?

There is no sorting method that is universally superior to all others. The programmer must carefully examine the problem and the desired results before deciding the particular sorting method. Some of the sorting methods are given below:

Bubble sort : When a file containing records is to be sorted then Bubble sort is the best sorting method when sorting by address is used.
Bsort : It can be recommended if the input to the file is known to be nearly sorted.
Meansort : It can be recommended only for input known to be very nearly sorted.
Quick Sort : In the virtual memory environment, where pages of data are constantly being swapped back and forth between external and internal storage. In practical situations, quick sort is often the fastest available because of its low overhead and its average behavior.
Heap sort : Generally used for sorting of complete binary tree. Simple insertion sort and straight selection sort : Both are more efficient than bubble sort. Selection sort is recommended for small files when records are large and for reverse situation insertion sort is recommended. The heap sort and quick sort are both more efficient than insertion or selection for large number of data.
Shell sort :  It is recommended for moderately sized files of several hundred elements.
Radix sort : It is reasonably efficient if the number of digits in the keys is not too large.

Is it possible that one try block can have multiple catch blocks?

There can be more than one exception handler (or catch block) for one try block, because it might so happen that in one single try block there can be different types of exceptions that can be thrown. 

This is shown in the following code snippet:
try
{
// statement that throws divide-by-zero exception
// statement that throws array out-of-bound exception
}
catch ( divide_error id1 ){ // code }
catch ( out_of_bound_error id2 ){ // code } 

Is it possible to throw an exception through a constructor?

Yes, we can! We cannot return any error value from the constructor, as the constructor doesn’t have any return type. In such situation, by throwing an exception we can pass value to catch block. 

This is shown in the following example:
#include <iostream.h>
class sample
{
     public:
           sample ( int i )
           {
                 if ( i == 0 ) throw "error"; 
           } 
};
void main( )
{
     try
     {
          sample s ( 0 );
     }
     catch ( char * str ) 
     {
          cout << str; 
     }

How can we copy the contents of one file to another in one shot?

#include <fstream.h>
void main( )
{
     char source [ 67 ], target [ 67 ];
     char ch;
     cout << endl << "Enter source filename";
     cin >> source;
     cout << endl << "Enter target filename";
     cin >> target;
     ifstream infile ( source );
     ofstream outfile ( target );
     outfile << infile.rdbuf( );
}
Here all the copying is done through the single statement
outfile << infile.rdbuf( );

The function rdbuf( ) returns the address of the strstreambuf where the values are stored. 

How to allocate memory for a multidimensional array dynamically?

Many times we need to allocate memory for a multidimensional array dynamically. Because of complexity of pointers many find this difficult.

Following program allocates memory for a 3 x 3 array dynamically, copies contents of a 3 x 3 array in it and prints the contents using the pointer.

#include <iostream.h>
#include <new.h>
int a[ ][3] = {
                      1, 2, 3,
                      4, 5, 6,
                      7, 8, 9
                  };
void main( )
{
     int **p;
     p = new int *[3] ;
     for ( int i = 0 ; i < 3 ; i++ )
            p[i] = new int[3];
     for ( i = 0 ; i < 3 ; i++ )
       for ( int j = 0 ; j < 3 ; j++ )
            p[i][j] = a[i][j] ; 
     for ( i = 0 ; i < 3 ; i++ )
     {
       for ( j = 0 ; j < 3 ; j++ )
            cout << p[i][j] ;
      cout << "\n" ;
     }
}

How do I change a data member of the const object?

To change the data members of the const object the data members are declared as mutable in the class. 

This is shown in the following example:
#include <iostream.h>
class sample
{
    private :
          mutable int i;
    public :
          sample( int ii = 0 )
          { 
                i = ii; 
          }
          void fun( ) const
          {
                i++;
                cout<< i; 
          } 
};
void main( )
{
     const sample s ( 15 ) ;
     s.fun( ); 
}

Here, the object s is const and hence only const functions can operate upon it. When the const function fun( ) gets called to operate upon object s, the data member i is incremented. Ideally the data member should not be changed, as object is defined const. But we can change the data member i because it is declared as mutable in the class sample

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. 

How do I write code that allows to create only one instance of a class?

#include <iostream.h>
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.