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:
// 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
           sample ( int i )
                 if ( i == 0 ) throw "error"; 
void main( )
          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
                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;
            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 ;
         sample( ){}
         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. 

Most Commonly Used Git Commands

usage: git [--version] [--exec-path[=<path>]] [--html-path] [--man-path] [--   info-path] [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
[-c name=value] [--help] <command> [<args>]

The most commonly used git commands are:
add            Add file contents to the index
bisect         Find by binary search the change that introduced a bug
branch        List, create, or delete branches
checkout     Checkout a branch or paths to the working tree
clone          Clone a repository into a new directory
commit       Record changes to the repository
diff             Show changes between commits, commit and working tree, etc
fetch           Download objects and refs from another repository
grep           Print lines matching a pattern
init              Create an empty git repository or reinitialize an existing one
log              Show commit logs
merge         Join two or more development histories together
mv              Move or rename a file, a directory, or a symlink
pull              Fetch from and merge with another repository or a local branch
push            Update remote refs along with associated objects
rebase         Forward-port local commits to the updated upstream head
reset           Reset current HEAD to the specified state
rm              Remove files from the working tree and from the index
show           Show various types of objects
status          Show the working tree status
tag              Create, list, delete or verify a tag object signed with GPG

Git: Installation & Setup


1) Ubuntu,debian
           sudo apt-get install git-core
2) Fedora,red hat
           yum install git
3) Windows
4) Mac OS

Setting up Git:

When you first start using Git, there are a few things you will likely want to get setup before you start. Git records your name and email address when you create commits, so you need to tell Git what those are. 

You can use the git config command to set those. If you pass --globalit will save the values in the ‘~/.gitconfig’ file so they are the default for all of your repositories.

User Configuration:

          $ git config --global user.name "Your Name" 
          $ git config --global user.email "YourMail@gmail.com"

Push configuration:

The following command configure Git so that the git push command pushes always all branches which are connected to a remote branch (configured as remote tracking branches) to your Git remote repository. This makes is typical easier to ensure that all relevant branches are pushed.

# set default so that all changes are always pushed to the repository 
         $ git config --global push.default "matching"

Avoid merge commits for pulling:

If you pull in changes from a remote repository, Git by default creates merge commits. This typically undesired and you can avoid this via the following setting.

# set default so that you avoid unnecessary commits 
        $ git config --global branch.autosetuprebase always

Color Highlighting:

       $ git config --global color.ui true 
       $ git config --global color.status auto 
       $ git config --global color.branch auto

Setting the default editor:

       $  git config --global core.editor vim

What is Git?

Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

Git allows groups of people to work on the same documents (often code) at the same time, and without stepping on each other's toes. It's a distributed version control system.

Git is a distributed system, everyone has their own copy of the source codes.

Distributed version control system:
A distributed version control system has not necessary a central server which stores the data.

The user can copy an existing repository. This copying process is typically called cloning in a distributed version control system.

Typically there is a central server for keeping a repository but each cloned repository is a full copy of this repository. The decision which of the copies is considered to be the central server repository is a pure convention and not tied to the capabilities of the distributed version control itself.

Every local copy contains the full history of the collection of files and a cloned repository has the same functionality as the original repository.

Every repository can exchange versions of the files with other repositories by transporting these changes. This is typically done via the selected central server repository.