Showing posts with label CPP. Show all posts
Showing posts with label CPP. Show all posts

C++; Singleton Design Pattern

Singleton is a creational design pattern.
Provide one and only instance of an object.

#include using namespace std; 
class MySingleton 
{ 
      public: static MySingleton* iInstance; 
      public: static MySingleton* GetInstance(); 
      private: MySingleton(); 
}; 
MySingleton* MySingleton::iInstance = NULL; 
MySingleton::MySingleton() 
{ 
      cout << "Inside construtor ..." << endl; 
} 
MySingleton* MySingleton::GetInstance() 
{
      if ( iInstance == NULL ) 
      {  
           iInstance = new MySingleton(); 
      } 
     return iInstance; 
} 

void main() 
{ 
     MySingleton* obj; 
     obj = MySingleton::GetInstance(); 
}

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

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

Abstract class

Abstract class - a class that can only be used as a base class for some other class. A class is abstract if it has at least one pure virtual function.

Object can’t be created in Abstract class.

Class data

{      
      public: 
             virtual void display()=0; // pure virtual fn declaration 
}; 
Class item : public data
{ 
     public:      
            void display() // pure virtual fn definition 
            {
                   cout<<”Pure Virtual fn calling”;
            }
};

Virtual Destructor in C++

• Pointer is of type Base class and object created using ‘new’ operator is of type Derived class. So, at the time of object creation, constructor invocation is from Base class to Derived class. 

• But while deleting pointer Base, compiler cannot tell that Derived class instance is destroyed. Note that ‘delete’ calls the destructor for the class. 

•This problem can be solved by declaring the destructor of the base class as ‘virtual’. In this way, the destructor will be invoked through virtual function table.

Example:

#include<iostream.h>
class Base

{       public: 
      Base()
      {
            cout<<“Base:Constructor”<<endl;
      } 
    ~Base(){
            cout<<“Base:Destructor”<<endl;
      } 
};
class Derived:public Base 
{ 
      Derived(){
            cout<<“Derived:Constructor”<<endl;
      } 
      ~Derived(){
           cout<<“Derived:Destructor”<<endl;
      } 
}; 
main()
{ 
      Base *base=new Derived; 
      delete base;
}

Output:
Base:Constructor 
Derived:Constructor 
Base:Destructor


After changing Base class destructor as below:
virtual ~Base()

{
    cout<<“Base:Destructor”<<endl;
}

Output: 

Base:Constructor 
Derived:Constructor 
Derived:Destructor 
Base:Destructor 

References in C++

• Reference is an implicit pointer to a variable.
• Creating references: 

        int &r;
• Initializing:
        int i=10;
        int &r=i;
• To access value of a variable using reference
       cout<<r;
• But you cannot use ++, -- like pointers to move references to next location
• References are also const pointers and cannot be reassigned.
       r=&j; is not possible.
• The real need for a reference variable can be felt when we pass by reference variables.

Namespaces in C++

•Namespace is simply a declarative area.
•The purpose of namespace is to localize names of identifiers to avoid name collisions.
•Elements declared in one namespace are separate from elements declared in another.
•Namespace is an important concept for library developer.
•If you include two libraries both having same function prototype, then compiler will be unable to detect which one you are referring to when you invoke it.

Syntax:
•Creating a namespace :
    namespace name{ //declarations}
•Anything defined within a namespace statement is within the scope of that namespace
•Using:
  using namespace name;
 (to include only a particular namespace defined in a library)
•using name::member
 (to include only a particular member of the namespace defined in a library)

Exception Handling in C++

Exception:

An unwanted state during the execution of the program. It can also be defined as “errors at run-time”. 
For example, 
Dividing a number by zero.

Whenever there is an exception in the program, the programmer has two possible solutions: 

a)Resumption- fix the problem and continue
b)Termination-Abort the process and return

In C++,
the Resumption model is supported by the function call mechanism, and 
the Termination model is supported by the exception-handling mechanism

Exception Handling:

“Exception Handling” allows us to manage the exception gracefully. 
Using Exception Handling technique we can avoid abnormal termination of the program and continue with the normal flow or the program, or even move the control to other parts of the program.

Exceptions are handled using try catch statements.

General syntax: 
try{ 

statements;
. . . . . 
} 

catch(type1 arg){statements;}

catch(type2 arg){statements;}

•We can have more than one catch statement associated with a try.


Exception Handling Example:

#include<iostream.h>
void main()
{ 
      int j; 
      cin>>j; 
      try
      { 
            if(j==0) throw j; 
               int i=20/j; 
      }catch(int j){ 
            cout<<"Divide by zero"; 
      }catch(...){ 
            cout<<"Caught Exception"; 
      }
}

Output: 
Divide by zero

Re-throwing an Exception:

A re-throw is indicated by a throw without an operand. 

Example;
try{ 
      //code which throws error 
}catch(Error e){ 
      throw; //re-throw 
} 
If a re-throw is attempted when there is no exception to throw , terminate() will be called. 
terminate(), by default, calls abort() to stop the program. But we can specify our own termination handler.

Custom Exception Class:

#include<iostream.h> 
#include<string.h> 

class MyException

{           char *msg; 
          public: 
                  MyException(){
                          msg="MyException";
                  } 
                  MyException(char *m) 
                  {
                          msg=m;
                  } 
                  char* getMessage(){ 
                          return msg;
                  } 

};

void main() 
{ 
       int age; 
       try{ 
              cout<<"Enter your age"; 
              cin>>age; 
              if(age>18) 
                     cout<<"Ready to vote"; 
              else{ 
                     MyException e("You are Minor!!"); 
                     throw e;
              } 
       } 
       catch(MyException e) 
       { 
              cout<<"Exception"<<e.getMessage(); 
       }
}

Function Overloading in C++

Function overloading is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters.

You can only overload functions only on the basis of:

  • Type of arguments
  • Number of arguments
  • Sequence of arguments &
  • Qualifiers like const and volatile.
Consider the following function:
        int Add(int x, int y)
       {
                return x+ y;
       }
This trivial function adds two integers. However, what if we also need to add two floating point numbers? This function is not at all suitable.Again we have to write one more function with float variables.
One way to work around this issue is to define multiple functions with slightly different names:
      int AddI(int x, int y)
     {
              return x+ y;
     }
     double AddD(double x, double y)
     {
             return x+ y;
     }

Function overloading provides a better solution
We now have two version of Add():
      int Add(int nX, int nY); // integer version
      double Add(double dX, double dY); // floating point version

Which version of Add() gets called depends on the arguments used in the call — if we provide two ints, C++ will know we mean to call Add(int, int). If we provide two floating point numbers, C++ will know we mean to call Add(double, double). In fact, we can define as many overloaded Add() functions as we want, so long as each Add() function has unique parameters.

Making a call to an overloaded function results in one of three possible outcomes:
1) A match is found. The call is resolved to a particular overloaded function.
2) No match is found. The arguments can not be matched to any overloaded function.
3) An ambiguous match is found. The arguments matched more than one overloaded function.


When an overloaded function is called, C++ goes through the following process to determine which version of the function will be called:

1) First, C++ tries to find an exact match. This is the case where the actual argument exactly matches the parameter type of one of the overloaded functions. For example:
          void Print(char *szValue);
          void Print(int nValue);

          Print(0); // exact match with Print(int)


Although 0 could technically match Print(char*), it exactly matches Print(int). Thus Print(int) is the best match available.

2) If no exact match is found, C++ tries to find a match through promotion.

To summarize,

  • Char, unsigned char, and short is promoted to an int.
  • Unsigned short can be promoted to int or unsigned int, depending on  
       the size of an int.

  • Float is promoted to double
  • Enum is promoted to int

For example:

         void Print(char *szValue);
         void Print(int nValue);
        
         Print('a'); // promoted to match Print(int)

In this case, because there is no Print(char), the char ‘a’ is promoted to an integer, which then matches Print(int).

3) If no promotion is found, C++ tries to find a match through standard conversion. 


Standard conversions include:

  • Any numeric type will match any other numeric type, including unsigned (eg. int to float)
  • Enum will match the formal type of a numeric type (eg. enum to float)
  • Zero will match a pointer type and numeric type (eg. 0 to char*, or 0 to float)
  • A pointer will match a void pointer

For example:
         void Print(float fValue);
         void Print(struct sValue);

         Print('a'); // promoted to match Print(float)


In this case, because there is no Print(char), and no Print(int), the ‘a’ is converted to a float and matched with Print(float).

Note that all standard conversions are considered equal. No standard conversion is considered better than any of the others.

Ambiguous matches:

class A

{ 
        public: 
               void foo(int x) 
               {
                  cout << "foo with one\n"; 
               } 
               void foo(int x, int y=10) 
               { 
                  cout << "foo with two\n";
               } 

}; 
int main() 
{ 

      A a; 
      a.foo(1); //error? 
}

Because function/operator overloading is resolved by compiler at compile time. So overloading a function just by providing a default argument will cause ambiguity and compiler error.

Stack Overflow Situation

func_call() {
           funct_call();
}

Every time the above function is called the return address is stored onto the stack. Calling in this infinite loop will cause a stack overflow.

Standard prototypes for main() function

a. int main (void)
b. int main (int argc, char **argv)
c. int main (int argc, char *argv[])

C++ Features Not in C

Listed below are some features that are found in C++, not found in C, but still have nothing to do with Object Oriented Programming.

Casts:
In C, if you want to cast an int to a long int, for example, you'd use 
int i=0; 
long l = (long) i; 

In C++, you can use a function-like call to make the cast. 
long l = long(i);

It's easier to read. Since it's possible to create functions to perform casts involving user-defined types, this makes all the casts look consistent. For example, you may have a user-defined type -- complex numbers. 

You have a function that accepts an integer and casts it to a complex number: 1 --> 1 + 0i (real part is 1 and imaginary part is 0) 

Suppose your function call is named 'complex', then it may look like: 

Complex x;
int i=1; 
 x = complex(i);

Flexible Declarations:
In C, all var declarations within a scope occur at the beginning of that scope. Thus, all global declartions must appear before any functions, and any local declarations must be made before any executable statements.

C++, on the other hand, allows you to mix data declarations with functions and executable statements. 

E.g. In C,
void makeit(void) 
{
      float i; 
      char *cp;
      /* imagine 2000 lines of code here */ 
      /* allocate 100 bytes for cp */ 
      cp = malloc(100); /* 1st use of cp */ 
      for (i=0; i<100; ++i) /* 1st use of i */ 
      { 
              /* do something */ 
      } /* more code */ 
 } 

In C++, 
void makeit(void) 
{ 
      // 2000 lines of code 
      char *cp = new char[100]; 
      for (int i=1; i<10; i++) { } 
}

'struct' and 'union' Tags:

In C, we would have this segment: 
struct foo 
{
      int a; 
      float b;
} 
struct foo f; 

This declares a struct with the tag name 'foo' and then creates an instance of foo named f. Notice when you declare var of that struct, you have to say 'struct foo'. 
In C++, struct and union tags are considered to be type name, just as if they had been declared by the 'typedef' statement. 

struct foo {int a; float b;}
foo f; 

which is equivalent to the following in C: 
typedef struct 
{ 
      int a; 
      float b; 
} foo;

foo f;


'const':

In ANSI C, it also supports 'const', but C++'s 'const' is more flexible than C's. In both C and C++, a value declared as 'const' is inviolate; it may not be modified by any part of the program in any way. 
The most common use of 'const' values in C is to replace '#define' literal constants. 

#define MAX_CUSTOMERS 10 
 const int MAX_CUSTOMERS = 10; 

Thus, 
MAX_CUSTOMERS = 10; 
MAX_CUSTOMERS ++; 

are both not acceptable. Note: since you cannot make changes to a 'const', each constant must be initialized when declared. The following is wrong: 
const int invalid; 

In C++, you can do something like 
const int ArraySize = 100;
int Array[ArraySize];
while in ANSI C, this would be flagged as an error.

'new' and 'delete':

In C, all dynamic mem allocation is handled via library calls, such as 'malloc' and 'free'. Here's how a traditional C programs might allocate memory: 

void func(void) 
{
     int *i; 
     i = (int *)malloc(sizeof(int)); 
    *i = 10; 
     printf("%d", *i); 
     free(i); 
} 

In C++, there are new ways of dynamically allocating mem using operators called 'new' and 'delete', where 'new' replaces 'malloc' and 'delete' replaces 'free' in C. We could rewrite the above function as the following: 

void func() 
{ 
     int *i = new int; 
     *i = 10; 
     cout << *i; 
     delete i; 
}
You'd probably agree this is a much clearer syntax and it's much easier to use as well. 

A couple more examples: 
     int *i = new int[10]; // an array of 10 integers 
     int *i = new int(*)[10]; // an array of 10 pointers to integers 

You can also intialize all the variables allocated by 'new': 

float *f = new float[50] (0.0); 

Error Code: if 'new' fails to allocate any memory requested, it will return NULL;
Tip: Usually, right after a call to allocate memory, 'new' or 'malloc' check to see if any memory has been allocated. This can prevent your program from accessing a NULL pointer which is a disaster and which will cause a bus error.

Note: Don't mix the use of 'new' and 'delete' with that of 'malloc' and 'free'. i.e, always use either all the C lib calls 'malloc' and 'free' in your program to manage dynamic mem. OR use all 'new' and 'delete'. All the mem allocated by 'malloc' should be returned to the available mem pool by 'free' and the same holds for 'new' and 'delete'. I'd just use 'new' and 'delete'.

References:

C can by clumsy sometimes. When you write a function to swap two integers, you have to pass the two integers into the function by reference: 

void swapint(int *a, int *b) 
{ 
      int temp;
      temp = *a; 
      *a = *b; 
      *b = temp; 
}
Here's the function call: 
    swapint(&i1, &i2); 

C++ supports a special type of identifier known as 'reference' &. It makes changing the parameter values in a function reletively painless. The above function can be rewritten in C++ as follows: 

void swapint(int &a, int &b) 
{ 
     int temp = a; 
     a = b; 
     b = temp; 
} 
Function call: 
     swapint(i1, i2); 

When i1 and i2 are passed into the function, a POINTS to i1 and b POINTS to i2 instead of making local copies of i1 and i2. Now, whenever you refer to a or b in the function, you actually refer to i1 and i2. So, whatever changes you make to a or b, they will be reflected on i1 and i2.


Function Overloading:

In C, as in most other programming languages, every function must have a unique name. At times, it can be annoying. Imagine you want to have a function that returns the abs value of an integer. 
int abs(int i); 

If you need to figure out the abs value of every possible available data type, you then have to write a function for each of the possible types: 

long labs(long l);
double dabs(double d); 

All those functions do the same thing -- return the abs value of the argument. Thus it seems silly to have a different name for each of those functions. 

C++ solves this by allowing you to create those functions with the same name. This is called overloading. 

For example, you can do the above in C++: 
int abs(int i); 
long abs(long l); 
double abs(double d); 

And depending on the type of parameter you pass into the 'abs' func. C++ will select the right one. 

Note: What if the type of the parameter passed in is not identical to any of the available parameter types in the existing functions? 

abs('a'); 
abs(3.1415F); 

C++ will try to make the easiest conversion to match those parameter types in the funcion prototypes. 

abs('a'); // call int abs(int i) 
abs(3.1415F); // call double abs(double d);
If no such conversion exists, then an error will occur.

Can I mix C-style and C++ style allocation and deallocation?

Yes, in the sense that you can use malloc() and new in the same program.

No, in the sense that you cannot allocate an object with malloc() and free it using delete. Nor can you allocate with new and delete with free() or use realloc() on an array allocated by new.

The C++ operators new and delete guarantee proper construction and destruction; where constructors or destructors need to be invoked, they are. The C-style functions malloc(), calloc(), free(), and realloc() doesn't ensure that. Furthermore, there is no guarantee that the mechanism used by new and delete to acquire and release raw memory is compatible with malloc() and free(). If mixing styles works on your system, you were simply "lucky" - for now.

If you feel the need for realloc() - and many do - then consider using a standard library vector. 

For example // read words from input into a vector of strings:

vector<string> words;
string s;
while (cin>>s && s!=".") words.push_back(s);


The vector expands as needed.

Copy Constructor in C++

Copy constructor is a constructor function with the same name as the class used to make copy of objects.

There are 3 important places where a copy constructor is called -

1)When an object is created from another object of the same type
2)When an object is passed by value as a parameter to a function
2)When an object is returned from a function

If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure a shallow copy. If the class does not have pointer variables with dynamically allocated memory, then one need not worry about defining a copy constructor. It can be left to the compiler's discretion.
But if the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. 

For ex:

                    class A //Without copy constructor
                    {
                         private:
                                   int x;
                         public:
                                   A() 
                                   {
                                          A = 10;
                                   }
                                   ~A() 
                                   {
                                   }
                    }
                   class B //With copy constructor
                    {
                        private:
                                  char *name;
                        public:
                                   B()
                                   {
                                         name = new char[20];
                                   }
                                   ~B()
                                   {
                                         delete name[];
                                   }
                                 //Copy constructor
                                  B(const B &b)
                                  {
                                         name = new char[20];
                                         strcpy(name, b.name);
                                   }
                     };

Let us Imagine if we don't have a copy constructor for the class B. At the first place, if an object is created from some existing object, we cannot be sure that the memory is allocated. Also, if the memory is deleted in destructor, the delete operator might be called twice for the same memory location. 

This is a major risk. One thing is, if the class is not so complex this will come to the fore during development itself. But if the class is very complicated, then these kind of errors will be difficult to track.
We all know that compiler will generate default constructor, destructor, copy constructor and copy assignment = operator by default if we dont define in our class definitions. 
Assume that, there is a scenario where we should not allow copy constructor and copy assignment operator in the program. 
Lets take some example, 
class A {/*...*/}; 
int main() 
{ 
        A a; /* default constructor */ 
        A b(a); /* copy constructor.. We should not allow this */ 
        b = a; /* copy assignment operator.. we should not allow this */ 
} 
How do you achieve this? 

You can acheive this by making your copy constructor and assignment operator private.
here is your modified code 

class A 
{/*... 
      private : 
                 A(const A& ) 
                 { 
                 } 
                 A& operator=(const A ) 
                 { 
                 }
*/};
int main()
{
     A a; /* default constructor */
     A b(a); /* copy constructor.. We should not allow this */
     b = a; /* copy assignment operator.. we should not allow this */
}

now you will get compilation error saying copy constructor and assignment operator are private members.

You are right. You can have these in private and you don't have to implement that.
class A 
{ 
     private: 
               A(const A&);
               A& operator=(const A&);
     public: 
} 
The difference between shallow and deep copying is only relevant for compound objects. (i.e objects that contain other objects, like lists/class instances or if objects has pointers to dynamically allocated memory). 


A shallow copy is bitwise copy of any object.
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Thus if the object has no pointers to dynamically allocated memory, a shallow copy is probably sufficient. Therefore the default copy constructor, default assignment operator, and default destructor should be sufficient.
If there are compound objects, then one has to define their own copy constructors, assignment operator and destructors for deep copy.

For Example:

// Shallow copy

Class Test
{       public:
              Test( int a, float b )
              {
                     i = a;
                     j = b;
               }
      private:
               int i;
               float j;
}
Test t1( 10, 20.0 );
Test t2(t1); // In this case, shallow copy is sufficient.


// Deep Copy

Class Test
{       public:
               Test( int a, char* s )
               {
                      i = a;
                      int len = strlen(s);
                      str = new char[len+1];
               }
      private:
                int i;
                char* str;
}
Test t1( 10, "Test" );
Test t2(t1); // In this case, deep copy is needed.

Inheritance

Inheritance:The C++ classes can be reused in several ways. Once a class has been written and tested, it can be adapted by other programmers to suit their requirements. This is basically done by creating new classes, reusing the properties of the existing ones. The mechanism of deriving a new class from an old one is called inheritance ( or derivation ). The old class is referred to as the base class (superclass) and the new one is called the derived class (subclass). Inheritance is not only used for re-using the classes, but as major aid for structuring the complex problems, breaking them into meaningful modular objects representing the problem to be solved. 

Different forms of Inheritance:
The derived class inherits some or all of the traits from the base class. A class can also inherit properties from more than one or from more than one level. A derived class with only one base class is called single inheritance and one with several base classes is called multiple inheritance. 
The traits of one class may be inherited by more than one class. This process is known as hierarchical inheritance. The mechanism of deriving a class from another derived class is known as multilevel inheritance. 
The following figure shows the different forms of inheritance. The direction of arrow indicates the direction of inheritance. 



The most important benefit inheritance brings is the ability to classify a complex problem or knowledge base into hierarchical classification. For example Alto is part of the classification of Maruti Cars or Compact Cars or both (Multiple inheritance), which is under larger classifications of cars, which in turn is under the more general classification of Automobiles and so on. Without this concept each object would have to be defined explicitly. With the help of inheritance we can simple add those qualities that make it unique from the generic common form. 

Defining Derived Classes:
A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is: 

class derived-class-name : visibility-mode base-class-name
{
        ...............//
        ...............// members of derived class
        ...............//
}The colon indicates that the derived-class-name is derived from the base-class-name. The visibility-mode or access control is optional and if present, may be private ,public or protected. The default visibility mode is private.
Examples: 
class ABC: private XYZ                    //private derivation
{
           .............
           .............
};
class ABC: public XYZ                     //public derivation
{
           .............
           .............
};
class ABC: XYZ                                //private derivation by default
{
          ..............
          ..............
};

Typically the derived object has all the information that a base class has. In addition all the specialized information for the derived object is added at the end of the base class.

Notes:
Derived class can access the public and protected members of the base class.
Private members of the base class cannot be accessed directly.

For eg:  if Manager is derived from Employee then the representation can be as follows:


For the above example if we have emp and mgr as obejects of Employee and Manager class respectively and we have the respective pointers pemp* and pmgr*, it is always possible to use pemp* to represent both the base and derived class. 
                    pemp = &emp; //Valid;                     pemp = &mgr; //Still Valid 
pemp->Name, pemp->EMp_ID and pemp->Date_of_joining are also valid for the derived Manager object. Use of pemp* to represent Manager object has no side effects. Other way round, representing an Employee (base class object) with Manager* (derived object pointer) is not valid as pmgr->Date_of_Promotion_to_Mgr and pmgr->list_of_reportees are not valid for Employee object. 

Types of Inheritance:
C++ distinguishes three types of inheritance: public, private and protected. As a default, classes are privately derived from each other. Consequently, we must explicitly tell the compiler to use public inheritance. 

The type of inheritance influences the access rights to elements of the various superclasses. Using public inheritance, everything which is declared private in a superclass remains private in the subclass. Similarly, everything which is public remains public. The following table specifies the type of access of the base class members in the derived class.


The leftmost column lists possible access rights for elements of classes. The second to fourth column show the resulting access right of the elements of a superclass when the subclass is derived using the access control specified mentioned in the top row.
Relationship 
“Is-a relationship” 
Public Inheritance should be used when you want to have the subset of properties of the base class to the new class. This kind of relationship is called the “Is-a relationship”. (Generalization – Specialization). 
class Employee 
{ 
         private: 
                     std::string Name; 
                     int EmpID; 
                     std::string Date_of_Joining; 
}; 
class Manager : public Employee 
{ 
         private: 
                     std::string Date_of_Promotion_to_Mgr; 
                         ….. 
         public: 
                     // public members 
}; 
Here, Manager is an Employee. Every Manager is an Employee of the company. Every Manager object will have the properties of Employee objects too. Every operation that can be applied to Employee should also make sense when applied to Manager Objects. This is called “Is-a Relationship”. 

“Has-a relationship”
Public Inheritance should not be used when the base class is a component of the object described by the derived class. 

class Wheel 
{ 
         public: 
                    int size() const; 
}; 
class Car : public Wheel 
{ 
        private: 
                 // Data Member and functions. 
        public: 
                // Public Member data and functions 
}; 
A Car is not a specialization of Wheel class. But, a car has a Wheel. This inappropriate use of public inheritance allows users to apply Wheel operations on Car. 

Car mycar;
int cap = mycar.size(); // This is not what we want. This will return the size of wheel, not the size of car. 

There are two ways to represent this “Has-a relationship”

We can have a composition. 
class Car 
{ 
          private: 
                      Wheel W; 
          Public: 
                      // etc., 
}; 

Or we can also use private inheritance to achieve this. 
class Car : private Wheel 
{ 
          private: 
                 // Private Members 
         public: 
                // Public Members 
}; 
Private inheritance is not much used than public inheritance, because composition is simpler and usually works as well. There are some advantages / disadvantages using private / protected inheritance than composition / containment. 
Advantages: 
The derived class can override private base class’s virtual functions 
The derived class can access to the protected members of the base class
Disadvantages: 
The private / protected inheritance can introduce unnecessary multiple inheritance if you want your class to be publicly derived from other class.
Composition is simpler than private / protected inheritance in terms of access and code maintainability.


Constructors and Destructors in Derived Classes:
The important thing to note is, when both the derived and base classes contain constructors, the base constructor is executed first and then the constructor in the derived class is executed. 

Similarly when the object is destroyed, derived class destructor will be called first and then the base class destructor.

In case of multiple inheritance, the base classes are constructed in the order in which they appear in the declaration of the derived class. Similarly, in a multilevel inheritance, the constructors will be executed in the order of inheritance.
Passing parameters to the base class constructor:
Initialization list is the method of initializing the class objects in the constructor. The following is the syntax of initialization list. 
constructor (arglist) : initialization-section 
{ 
            assignment-section 
} 
The assignment-section is nothing but the body of the constructor function and is used to assign initial values to its data member. 

The initialization section basically contains a list of initializations separated by commas. This section is used to provide initial values to the base constructors and also to initialize its own class members. Thus we can use either of the sections to initialize the data members of the constructor class.

The following program illustrates the use of initialization lists in the base and derived constructors. Also this demonstrates the execution order of inheritance.
// Initialization List in the constructors 
// Constructors and destructors called. 
#include <iostream> 
using namespace std; 
class Alpha 
{ 
        int x; 
        public: 
                // constructors 
                Alpha(int i) 
                { 
                        x = i; 
                        cout << "\n Alpha constructed"; 
                } 
               ~Alpha() 
                { 
                       cout << "\n Alpha destroyed"; 
                } 
               void show_alpha() 
               { 
                      cout << " X = " << x << "\n"; 
               } 
}; 
class Beta : public Alpha 
{ 
       float p, q; 
       public: 
                  // Constructors 
                Beta(int i, float a, float b):Alpha(i), p(a), q(b+p) 
                { 
                       cout << "\n Beta Constructed"; 
                } 
                ~Beta() 
                 { 
                       cout << "\n Beta destroyed"; 
                 } 
                void show_beta() 
                { 
                       cout << " P = " << p << "\n"; 
                       cout << " Q = " << q << "\n"; 
                } 
}; 
class delta 
{ 
       int d; 
       public: 
                 delta(int a) { d = a; cout << "\n Delta Constructed";} 
                 ~delta() { cout << "\n Delta destroyed"; } 
                 void show_delta() 
                 { 
                         cout << " d = " << d << "\n"; 
                 } 
}; 
class Gamma : public Beta, public delta 
{ 
        int u, v; 
        public: 
                  // Constructors 
                  Gamma(int a, int b, float c): Beta(a,c,c), delta(a), u(a) 
                   { 
                            v = b; 
                           cout << "\n Gamma constructed"; 
                   } 
                   ~Gamma() 
                   { 
                            cout << "\n Gamma destroyed"; 
                   } 
                  void show_gamma() 
                  { 
                           cout << " U = " << u << "\n"; 
                           cout << " V = " << v << "\n"; 
                  } 
}; 
int main() 
{ 
        Gamma g(2, 4, 2.5); 
        cout << "\n\n Display member values " << "\n\n"; 
        g.show_alpha(); 
        g.show_beta(); 
        g.show_delta(); 
        g.show_gamma(); 
   return 0; 
} 
Above program produces following output: 
Alpha constructed 
Beta Constructed 
Delta Constructed 
Gamma constructed 

Display member values
X = 2 
P = 2.5 
Q = 5 
d = 2 
U = 2 
V = 4 
Gamma destroyed 
Delta destroyed 
Beta destroyed 
Alpha destroyed 


Replicated Classes and Virtual Base Class:

A modified version of the sample code that we had seen in the last week to understand the arguments passing to the base class constructor and order of execution of the constructor and destructor of the base & derived class is listed below:
#include <iostream> 
using namespace std; 
class Alpha 
{ 
           int x; 
           public:
                    // constructors 
                    Alpha(int i) 
                    { 
                           x = i; 
                           cout << "\n Alpha constructed"; 
                    } 
                   ~Alpha() 
                    { 
                           cout << "\n Alpha destroyed"; 
                    } 
                   void show_alpha() 
                   { 
                          cout << " X = " << x << "\n"; 
                   } 
}; 
class Beta : public Alpha 
{                                  
          float p, q;           public: 
                   // Constructors 
                   Beta(int i, float a, float b):Alpha(i), p(a), q(b+p) 
                   { 
                                 cout << "\n Beta Constructed"; 
                   } 
                   ~Beta() 
                   { 
                                 cout << "\n Beta destroyed"; 
                   } 
                  void show_beta() 
                  { 
                                  cout << " P = " << p << "\n"; 
                                  cout << " Q = " << q << "\n"; 
                  } 
}; 
class delta : public Alpha 
{ 
          int d; 
          public: 
                     delta(int i, int a): Alpha (i) { d = a; cout << "\n Delta Constructed";} 
                      ~delta() { cout << "\n Delta destroyed"; } 
                      void show_delta() 
                      { 
                                  cout << " d = " << d << "\n"; 
                      } 
}; 
//Gama is derived using Beta and delta. Both in turn are derived from Alpha. 
//As a result there are two Alpha objects are created for each Gama object. 
class Gamma : public Beta, public delta 
{ 
          int u, v; 
          public: 
                    // Constructors
                   Gamma(int a, int b, float c): 
                   Beta(a,c,c), delta(a,b), u(a) 
                   { 
                            v = b; 
                            cout << "\n Gamma constructed"; 
                   } 
                  ~Gamma() 
                   { 
                            cout << "\n Gamma destroyed"; 
                   } 
                  void show_gamma() 
                  { 
                           cout << " U = " << u << "\n"; 
                           cout << " V = " << v << "\n"; 
                  } 
}; 
int main() 
{ 

         Gamma g(2, 4, 2.5);
         cout << "\n\n Display member values " << "\n\n"; 
         g.show_alpha(); //Ambiguous For which Alpha object? 
         g.show_beta(); 
         g.show_delta(); 
         g.show_gamma(); 
       return 0; 
} 

The above example shows that ambiguity may be introduced when multiple base classes are inherited that in turn inherit from a common base class.

One way to remove this ambiguity is to manually resolve it by using the scope resolution operator. You may change the ambiguous statement as:

g.Beta::show_alpha() 

// Now it is clear that it has use the copy of Alpha that is
// created as part of Beta. 

This is not the perfect solution as in most of the cases intention is not to create multiple copies of the base class any way. C++ provides the concept of virtual base class to address this issue. If you declare a base class as virtual while inheriting only one copy of the base class object is created even if it is derived through multiple classes. The above example is modified using the virtual base class to have only single copy of Alpha in Gama:
#include <iostream> 
using namespace std; 
class Alpha 
{ 
        int x; 
        public: 
                 // constructors 
                Alpha(int i=0) 
                { 
                          x = i; 
                          cout << "\n Alpha constructed"; 
                } 
                ~Alpha()
                { 
                          cout << "\n Alpha destroyed"; 
                } 
                void show_alpha() 
                { 
                          cout << " X = " << x << "\n"; 
                } 
}; 
class Beta : virtual public Alpha 
{ 
           float p, q; 
           public: 
                      // Constructors 
                      Beta(int i, float a, float b): p(a), q(b+p) 
                      { 
                               cout << "\n Beta Constructed"; 
                      } 
                      ~Beta() 
                      { 
                               cout << "\n Beta destroyed"; 
                      } 
                      void show_beta() 
                       { 
                               cout << " P = " << p << "\n"; 
                               cout << " Q = " << q << "\n"; 
                        } 
}; 
class delta : virtual public Alpha 
{ 
          int d; 
          public: 
                     delta(int i, int a) { d = a; cout << "\n Delta Constructed";} 
                     ~delta() { cout << "\n Delta destroyed"; } 
                      void show_delta() 
                      { 
                               cout << " d = " << d << "\n"; 
                      } 
}; 
// Gama is derived using Beta and delta. Both in turn are derived from Alpha. 
// Since both have derived Alpha as virtual base, there will be only one 
// copy of Alpha in Gama. 

class Gamma : virtual public Beta, virtual public delta
{ 
         int u, v; 
         public: 
                   // Constructors, Explicitly calling the constructed of an 
                   // indirect virtual base class. 
                  Gamma(int a, int b, float c): Alpha(a), delta(a,b), Beta(a,c,c), u(a) 
                  { 
                           v = b; 
                          cout << "\n Gamma constructed"; 
                  } 
                  ~Gamma() 
                  { 
                          cout << "\n Gamma destroyed"; 
                  } 
                 void show_gamma() 
                 { 
                          cout << " U = " << u << "\n"; 
                          cout << " V = " << v << "\n"; 
                 } 
}; 
int main() 
{ 
         Gamma g(2, 4, 2.5); 
         cout << "\n\n Display member values " << "\n\n"; 
         g.show_alpha(); 
         g.show_beta(); 
         g.show_delta(); 
         g.show_gamma(); 
    return 0; 
} 
Following is the output produced by the above program: 
Alpha constructed 
Beta Constructed 
Delta Constructed 
Gamma constructed 
Display member values 
X = 2 
P = 2.5 
Q = 5 
d = 4 
U = 2 
V = 4 
Gamma destroyed 
Delta destroyed 
Beta destroyed 

Please note that even though both Beta and delta have declared Alpha as virtual, a copy of Alpha is still present in objects their type.
Please also note that Alpha’s constructor is explicitly called from Gama to initialize the value of x. If it not called explicitly then the default constructor will be called and the value of the x would be 0. 

Important points:
  • Arguments for the base class’ constructor have to be defined in the definition of a derived class’ constructor. 
  • A derived class constructor can only specify initializer for it’s own members and immediate base class only. It can’t initialize members of a base. 
  • For example in the above case Gama constructor can’t pass the argument for Alpha constructor directly. It has to do it through Beta. Secondly it can’t initialize members of base directly like 
                       Gama (int a, int b, float c) : Beta (a,c,c), d(a), u(a) 

                       //Invalid, d is member of delta base class.
  • Private inheritance (has-a relationship) can be converted into containment. Whenever possible use containment and if required use private inheritance. 
  • Use Multiple Inheritance judiciously. 
  • Multiple inheritances produce duplicate objects. This can be resolved using virtual public inheritance.