SlideShare une entreprise Scribd logo
1  sur  78
Advance C++
=================================================

Day-1:
      Intro to oo programming

     MinGW compiler and basic commands

     Configuration codeblock IDE/Eclipse IDE

     Procedural stuff

     Additional feature of C++ not in C

Day-2:
      class and object

      c++ advance stuff
            1. dont return address of local variable from an method.
Day-3:
      Function and Operator Overloading
Day-4:

     inheritance,compostion and Polymorphism

     c++ advance stuff

            1. understanding c++ automatically generated functions:default ctor,

            copy ctor, overloded assignment op, destructor

            2. new vs malloc : which to use for object creation

            3.Virtual destructor in base class and its need

            4. How to create a class non copyable

            5. singlton design pattern

            6. copy constructor : deep copy vs shallow copy

            7. Memory leak and dangling pointer



Day-5:

     Templates, Exception Handling

     c++ advance stuff
           Smart pointer: need and implementation
           C Macros vs C++ template


Day-6:
      STL
Day-7:

     File IO, RTTI

Day-8:
      Memory mgt in C++
Day-9:
      Database programming
Day-9 and 10:
      Project Work


      MCQ test.
==========================================================================




Day-1
----------

     minGW compiler installation
     set path for compiler



Hello World
----------------

#include <iostream>
using namespace std;

int main()
{
      cout<<"Hello world"<<endl;

     return 0;
}




     Command to compile;
     ------------------

     g++ -o Hello Hello.cpp




OOPs piller
------------
      Abstraction and encapsulation
      Hirerchy
      Modularity


     Concepts:
     ----------

     class
     object
     abstraction , encapsulation, data hiding

     inheritance, polymorphism......
Procedural stuff
---------------
      if...else
      for, while , do.....while

     questions:
     ---------

     *
     **
     ***
     ****
     *****

     Dry run !!!


     Array
     ----------

     one D
     two D

     Examples.

             Sorting ex.
             inserting /deletion element in sorted array




Additional feature of C++ not in C
-------------------------------
      use of void pointer
      Difference in use of enum
            annonymous enum
      Reference variable
            call by ref vs call by pointer
      new and delete operator

     inline fun
     C++ operators

     Struct of C++
     Union of C++
           annonymous union


use of void pointer
------------------
      C++ is strongly typed language then C

#include <iostream>
using namespace std;

int main()
{
      void *p;
      char temp='a';
char *q=&temp;
        q=p;//compile error

        return 0;
}



Will not copile need explicit type casting
--------------------------------------
      q=(char*)p;//compile


Note:

        int i;
        double j=89.5;
        i=j;//OK in C++ error in Java.




Difference in use of enum
----------------------
      enum is named constant

      in C++ tag name become new data type while in C they are treated as
integer

        Ex:
        enum shape{circle, square,tringle};

        shape eclipse;// ok in c++


        enum color{red, green, yellow};

        color background=blue;//ok

        color background=7;//error

        color background=(color)7;//ok ?


annonymous enum
--------------------
      enum{OFF, ON};

        int status=OFF;
        ....
        ......


Reference variable
---------------------

        alias to previouly define variable
              --------------

        Ex:

        float total=100;
float &num=total;
now num and total point to same memory location, ie both are alieas

if we change total num will be changed....




Why to use reference?
-----------------------------

1. easy to use then pointer
2. can used to produce effect of call by reference (swap the values)

3. C dont support call by reference it support call by pointer


Ex:


call by pointer that you know
--------------------------------------
void swap(int *p,int *q){

      int temp=*p;
      *p=*q;
      *q=temp;
      }

int main(){
      ...........
      int i=11;
      int j=22;
      .......print before swap

      swap(&i, &j);

      ......print after the swap.

      }




what you should also know is

call by reference
-----------------------------
      simple and clean !!!



void swap(int &p,int &q){

      int temp=p;
p=q;
           q=temp;
           }

     int main(){
           ...........
           int i=11;
           int j=22;
           .......print before swap

           swap(i, j);//simple code

           ......print after the swap.




     Normally using pointer an method can't come at LHS

     ie
           fun()=x;//Not seen !!!


     this is possible using reference
     ------------------------------------



           int& max(int &x, int &y){
                 if(x>y)
                       return x;
                 else
                       return y;
                 }


                 main(){

                 ...........
                 ..............

                  max(a,b)=-1//     will assign -1 to whoever is
greater.............

                 }



     new and delete operator
     -------------------------

     Memory management operator in C++

     Dont use malloc/alloc in C++( can use)



     Ex:
     -----
     int *p=new int;
     int temp=99;
     p=&temp;
     cout<<p<<endl;
delete p;



       Ex:

       allocating memory for an array
       -----------------------------


                    int *p=new float[5];

                    delete p;//wrong only delete pointer.......

                    delete []p;//correct



       ---------------------------------------------------------------
       Remember: its programmer job to delete dynamically allocated memory from
heap

              if you dont do it.....it can leds to memory leak

       -------------------------------------------------




C++ operators
---------------------
      list of operator not in C

       ::     scope resolution operator

       ::*    pointer to member operator

       ->*    Pointer to member operator

       .*     Pointer to member operator

       <<     insertion operator

       >>     extractor

       delete       memory mgt operator

       endl   line feed operator

       new    memory mgt operator

       setw   field width seperator



Struts of C++
-------------
      no technical difference

       data is private by default.


Union of C++
-----------------
annonymous union



================================================================================
=====================
Day-2

class and object

================================================================================
=====================

Defining a class

Creating an object

Object Scope

Data Abstraction

Enforcing Data Encapsulation

‘this‘ Pointer

Defining member functions

Dynamic creation of objects


Constructors and Destructors

     The Default Constructor

     The Destructor

     Parameterized Constructors

     Copy constructor

     Constructor initializers


Some misc topics:

     random no generation
     sizeof operator
     const keyword

Multifile program in C++


Static
      static data
      static methods

Returning objects

Arrays of Objects

Methods and access modifiers

Accessing class data and methods
Friend class and friendly functions




Defining a class and creating an object
======================


     class NameOfTheClass{


     //data member

     //member methods

     };



     Ex:


     class Employee{

             public:

             int id;
             double salary;

             };


             void main()
             {

                   Employee e;
                   e.id=22;
                   e.salary=3344.6;
             }



Creating an object
------------------

     Employee e;

     create an object e


     Note:
Employee *e;//NOT CAREAT OBJECT BUT OBJECT HANDLER




     Note object has 3 things

     ----------------------

           1. state

                   decided by instance variable

           2. behaviour
                 decided by instance methods

           3. identity
                 Equivalent concept as PK in database
                 Ex: id of employee should unique..........




Object Scope
-------------


     consider
     ................


     void main()
           {
                   {

                   Employee e;
                   e.id=22;
                   e.salary=3344.6;

                   }

                   cout<<e.id<<endl;

                   //ERROR OBJECT SCOPE PROBLEM
           }




Data Abstraction
-----------------------
      foucus on essential thing........


Data Encapsulation
------------------------
      HIDING UNNESSARY DETAILS...........
sound same?


above ex kills Encapsulation
------------------------

     data should be accessable/ changes using public methods


     class X{

     private data

     public method

     }




class Employee{

     private:
     int id;
     double salary;

     public:

     void setId(int a){
           id=a;
           }

     void setSalary(double a){
           salary=a;
           }

     void show(){

              cout<<"id is :"<<id<<endl;
              cout<<"salary is :"<<salary<<endl;
              }

     }



void main(){

     Employee e;// creating an emp object

     //e.id=22;//will not compile

     e.setId(22);
     e.setSalary(333.7);

     e.show();
     }
Note:
------
      an class can have 3 type of data in the class

     1. instance variable
           Ex: id and salary is instance variables

     2. static

     3. local
           Ex: a is an local variable in........

                 void setId(int a){
                 id=a;
                 }




‘this‘ Pointer
================
      this is implecit pointer passed to every method

     used to resolve confusion bw local and instance variables



     what if we want to have something like.........


                 void setId(int id){
                 id=id;
                 }

     confusion is which id is assigned to which id
     ???????



     use this:
     -------------




     class Employee{

           private:
           int id;
           double salary;
public:

           void setId(int id){
                 this->id=id;
                 }

           void setSalary(double salary){
                 this->salary=salary;
                 }

           void show(){

                    cout<<"id is :"<<this->id<<endl;

                    cout<<"salary is :"<<salary<<endl;
                    }

           }



     void main(){

           Employee e;// creating an emp object

           //e.id=22;//will not compile

           e.setId(22);
           e.setSalary(333.7);

           e.show();
           }



     another use of this
     ------------------------

           returning *this return the address of object that has called method


     let us C some POC program:




#include <iostream>
#include<cstring>
using namespace std;

class Person
{
      char *name;
      int age;

     public:
           Person(){}
           Person(char *t, int a){
                       int len=strlen(t);
                       name=new char[len+1];
                       strcpy(name, t);
           }
Person& greater( Person &p);
            void show(){
                  cout<<"name is:"<<name<<endl;
                  cout<<"age is:"<<age<<endl;
            }
};

Person&   Person::greater( Person &p){
             if(p.age>age)
                   return p;
             else
                   return *this;
}




int main()
{
      Person p1("foo",45);
      Person p2("bar",25);

     Person p3=p1.greater(p2);

     p3.show();

     return 0;
}




     Now what if we want to initilize the
     state of the object at the time of creation?
     ---------------------------------------------

            when we say.....

            Employee e;

            e will have default value of id and salary that is garbage

            is there is any way to provide some meaningful values?


            Moreover we are using setter method
            --------------------------------

            Disadvantage of setter ?
----------------------
                 can be called many a time ..... may create problem.....


                 what problem:

                  if somebody called setId() twice he can change it...may not
suitable as per business
                  logic.....




     Constructor
     ===============

     class X{

           private:

                 int i,j;

           public:

                 X(){                //default constructor

                 cout<<"default const"<<endl;
                 }


                 X(int i, int j){        //parameterized constructor
                       cout<<"default const"<<endl;

                        this->i=i;

                        this->j=j;
                 }

           //copy constructor latter on*

           };//end of the class




     Ex:
     ---

           class Employee{

           private:
           int id;
           double salary;

           public:

           void Employee(){
                 id=0;
                 salary=0.0;
           }
void Employee(int id=0, double salary=0){
                   this->id=id;
                   this->salary=salary;
             }

             void show(){

                   cout<<"id is :"<<this->id<<endl;

                   cout<<"salary is :"<<salary<<endl;
                   }

             }



        void main(){

             Employee e;// creating an emp object

             //e.id=22;//will not compile

             e.setId(22);
             e.setSalary(333.7);

             e.show();
             }


important feature of constructors:
-----------------------------------

        1. constructor can be public/private

        2. should have same name as that of class

        3. should not return anything not even void

        4. invoked automatically....at the time of creation of the object
              after object creation cant be used

             ie. work only once the object life cycle


        5. we can't refer to there addresss.....


        6. Constructor can be overloaded but cant be overriden*

        7. Can't inherit....




        reference in c++
        -------------------


        Now after undestanding basic of reference in C++ come back on pending
topic
        ie copy constructor
copy constructor
------------------------
      http://www.codeproject.com/Tips/78946/C-Copy-Constructor-in-depth




default argument to an method
------------------------------
      small useful concept of C++
      -----------------------------

           we can define an fuction as;

           foo(int i=0,int j=0){
                 .....
                 ...
                 }

           void main(){


                 foo();
                 foo(11,66);
                 }


     foo();
           in this case i and j assigned to default values ie 0

     foo(11,66);
           in this case i and j assigned to assigned values ie 11 and 66
Dynamic creation of objects
================================
Object pointer /ref
------------------

     When we say ......

           Employee e;

     this create an object in stack area( more on memory latter......)

           We can also say......


           Employee *e;


      in this case e is an pointer that can point to an object in heap(latter in
detail)

           Employee *e=new Employee;

                 will call default const

           Employee *e=new Employee();

                 will call default const

           Employee *e=new Employee(22,44);




     an object can be reffered by more then one pointer at a time

           but

     one pointer cant refer two object at a time..........


     So ......

           identity of an object is unique...........




inline function
==================

      How function calling happens?
      ----------------------------
            function that is called ,address pushed to stack...and control
            transfer to called fuction and after finishing stack is reffered
again.......

           may be slow if an small fuction is called 100 time in an program
macro of C
        -------------
              forget about it!!!


        what is C++ approach?
        -----------------------

        use inline function.........


        Ex:

        void inline sum(int a,int b){

                return a+b;
        }


        call as usual from main........



        Note;

        good coding practics says that we should have prototype of method in the
class
        and defination should be seperate

        (Multifile program in C++ latter...........)




                class Employee{

                private:
                int id;
                double salary;

                public:

                void Employee();


                void Employee(int id, double salary);

                void show();            //method decleration !


                };



                void Employee::Employee(){
                      id=0;
                      salary=0.0;
                }


                void Employee::Employee(int id=0, double salary=0){
this->id=id;
                this->salary=salary;
          }


          //method defination


          void Employee::show(){

                cout<<"id is :"<<this->id<<endl;

                cout<<"salary is :"<<salary<<endl;
                }




important thing is :: ie scope resolution operator
     ---------------------------------

          resolve the confusion ?

          1. which method defination belong to which class

          2. resolve confusion bw local variable and local variable

          ex:

                int i=89;// global in C/C++

                int main(){

                      int i=90;//local

                      cout<<i<<endl;

                      cout<<::i<<endl; //global one.......
                      }



    destructor in c++
    ====================

          clean up job

          we have to do overself

          :)
                power to programmer
                can be faster if memory management is done by programmer


          :(
                more memoery mgt related issues

                      dangling pointer
                      Memroy leak *

                No GC (not lucky as Java guys.........)

                      you are powerful enough to create your own GC !!!
Ex:

     class Demo{

              public:

              Demo(){
                    cout<<"constructor of Demo class......"<<endl;
              }

              ~Demo(){
                    cout<<"destructor of Demo class......"<<endl;
              }

           };




int main(){

                Demo d;

     }



OP
=======

     constructor of Demo class......
     destructor of Demo class......



imp
==========


int main(){

     Demo *d=new Demo;
     delete d;

     }


in this case destructor is not going to call till you do not call

     delete

Remember;
=========
      if programmer burden to clean dynamically allocated memory........
dont forget delete ever you use new in C++




      Ex:

            stack
---------------------

#include <iostream>
#include<string.h>
#define SIZE 10
using namespace std;

class Stack{

    private:
        int s[SIZE];
        int top;

    public:
        void init(){
            top=0;// no valid element in the stack
        }
        void push(int data){
            if(top==SIZE){
                cout<<"stack is full"<<endl;
                return;
            }
            s[top++]=data;
        }
        int pop(){
            if(top==0){
                cout<<"stack is full"<<endl;
                return -1;
            }
            s[--top];
        }
};
int main(){

    Stack st;
    st.init();
    st.push(3);
    st.push(4);
    cout<<st.pop();

}




Copy constructor:
=======================

Compiler provide default copy constructor if you are not providing.......
copy constructor
---------------
#include <iostream>
#include<string.h>
#define SIZE 10
using namespace std;
class Employee{
    private:
        int id;
        double salary;
    public:
    Employee();
    Employee(int id, double salary);
    Employee(Employee &);
    void show();
};
Employee::Employee(){
    id=salary=0;
}

Employee::Employee(int id, double salary){
    this->id=id;
    this->salary=salary;
}


Employee::Employee(Employee &e){
    this->id=e.id;
    this->salary=e.salary;
}

void Employee::show(){
    cout<<"id:"<<id<<endl;
    cout<<"salary:"<<salary<<endl;
}
int main(){

    Employee e(11,34);
    Employee e1=e;
    e1.show();
}




Compiler synthesized default copy constructor
-----------------------------------------------

     A default copy constructor simply copies all the members.

     Most of the time, this default behaviour is acceptable.

     When it really does not work is when we have
     pointer variables as members of our class.

     This is because the default copy constructor does a shallow copy ‘ that is

     only values of the fields are copied.


     In other words, the pointer field in both the original object
and the copy will then point to the same dynamically allocated memory.


      This may not be what we desire for pointer datatypes.




problem with default compiler provided default copy const
-------------------------------------------

      it do shallow copy


Ex:

#include <iostream>
using namespace std;

class A
{
      int *j;
      public:
      A(int j1){
            j=new int;
            *j=j1;
            }
      void setJ(int j1){ *j=j1;}
      int getJ(){return *j;}
};

int main()
{
      int k=12;
      A a1(k);
      A a2=a1;
      k=10;
      a2.setJ(k);
      cout<<a1.getJ()<<endl;
      cout<<a2.getJ()<<endl;
return 0;
}




Now we need to provide copy constructor as:
-------------------------------------------

      To override the default behaviour,
      we create copy constructors in our code.

      What we need is a deep copy( copies all fields, and makes
      copies of dynamically allocated memory pointed to by the fields).
corrected program
------------------------


#include <iostream>
using namespace std;

class A
{
      int *j;
      public:
      A(int j1){
            j=new int;
            *j=j1;
            }
    A(A &a){
      j=new int;
      *j=a.getJ();
      }

     void setJ(int j1){ *j=j1;}
     int getJ(){return *j;}
};

int main()
{
      int k=12;
      A a1(k);
      A a2=a1;
      k=10;
      a2.setJ(k);
      cout<<a1.getJ()<<endl;
      cout<<a2.getJ()<<endl;
return 0;
}




Good Programming practics
--------------------------


To make a deep copy, we need to do two things
----------------------------------------------------
      1. write a copy constructor

     2. overload the assignment operator, otherwise the
     copy will point to the original, with disastrous consequences.

     (will cover latter)




Constructor initializers
-------------------------------


      If we just need to initialize the values
      without doing any checks then we could simply do it using constructor
initialization list also.
This is just another way to initialize


Example:

     class Complex{
           private:
           double real;
           double img;

             public:
             Complex(double r, double i):real(r), img(i){}
             };




Some misc topics:
-----------------------------

     random no generation
     sizeof operator
     const keyword




random no generation
-----------------------


#include <iostream>
#include<ctime>
#include<cstdlib>
using namespace std;


int main()
{

    srand(time(0));
    for(int temp=0;temp<100;temp++){
        cout<<1+rand()%6<<endl;
    }
return 0;
}



     sizeof operator
     -----------------------



    int temp=0;
    cout<<sizeof(temp);
const keyword
------------------

aka final of Java
cant be change once assigned......

1. const on variable

2. const on object

2. const on method

3. const on method arguments


1. const on variable
--------------------------

Ex:
 const int i=90;

      i=0;//will create compile error......

   return 0;




2. const on object
---------------------
when object is constant we can call only constant method on the object

with regular object we can call regular methods/const methods both.



Ex:


      #include <iostream>
      using namespace std;

      class Foo
      {
            int i;
            public:
                  Foo(int i){this->i=i;}
                  void show(int temp);
                  void show2(int temp)const;
      };

      void Foo::show(int temp){
            cout<<"showing show of Foo"<<endl;
            i=i+temp;
      }

      //Error not allowed to change value of instance variable in show2()

      void Foo::show2(int temp)const{
cout<<"showing constant show of Foo"<<endl;
           i=i+temp;
           }

     int main()
     {
           const Foo f(22);
           f.show2(44);
     return 0;
     }




How to declare an function constant?
------------------------------------

creating constant object
---------------------------

void Foo::show2()const{
            cout<<"showing show of Foo"<<endl;
            }




Constant variable
------------------
can only initilize once , then cant be chage

we need special syntac called Member initilization
                        ------------------------




Ex:
#include <iostream>
using namespace std;

class Foo
{
      const int i;
      public:
            Foo(int i){this->i=i;}
            void show();

};

void Foo::show(){
      cout<<"showing show of Foo"<<endl;

}



int main()
{
       Foo f(22);
      f.show();
      return 0;
}



     Foo(int i){this->i=i;} has to be replaced by Foo(int i):i(i){}




Multifile program in C++
---------------------------
      enhance Modularity of sw development

     what if 100 classes in an project?

     How to do it?

     Codeblock make it easy :)

           FILE======>NEW ======>CLASS

           give an good name to class

           ...
           ....

     now we have:
     -------------
           main.cpp

           Employee.cpp
           ------------
                 putting implementation

           Employee.h
           ----------
                 function prototype
                 and variable decleration



           both cpp must have
           --------------------
                 #include <iostream>
                 using namespace std;

           must mention
           -----------
           #include "Employee.h" in main.cpp




     finally we have 3 files
     -------------------------

     main.cpp
     ===========

     #include <iostream>
     #include "Employee.h"
     using namespace std;
int main()
     {
             Employee e(22,44);
       e.show();
     }




     Employee.cpp
     ==============

     #include "Employee.h"
     #include <iostream>
     using namespace std;

     Employee::Employee()
     {
     }

     Employee::Employee(int id,float salary)
     {
             this->id=id;
             this->salary=salary;
     }

     void Employee::show()
     {
            cout<<"id:"<<id<<endl;
            cout<<"salary:"<<id<<endl;
     }




     Employee.h
     ===========
     #ifndef EMPLOYEE_H
     #define EMPLOYEE_H


     class Employee
     {

         private:
                     int id;
                    float salary;
     public:
                    Employee();
                    Employee(int id, float salary);
              void show();

     };

     #endif // EMPLOYEE_H



Static
================
      static data
      static methods


     instance data;
     -----------------
           per object
           seperate copy for every object

           Ex: name an id of employee are seperate


     static data:
     -----------
           only one copy of data for whole class

           visible only within the class, lifetime is whole program.

     static method
     ------------
           can be called without creating any object

           can not refer instance variables




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

using namespace std;

class Employee{
    private:
        int id;
        double salary;
            static int counter;
    public:
    Employee();
    Employee(int id, double salary);
    Employee(Employee &);
      static void showEmployeeCounter(){
            cout<<"total employee created :"<<counter<<endl;
      }
    void show();
};
Employee::Employee(){
    id=salary=0;
      counter++;
}

Employee::Employee(int id, double salary){
    this->id=id;
    this->salary=salary;
      counter++;
}

int Employee::counter=0;
Employee::Employee(Employee &e){
    this->id=e.id;
    this->salary=e.salary;
}

void Employee::show(){
    cout<<"id:"<<id<<endl;
    cout<<"salary:"<<salary<<endl;
}
int main(){

    Employee e(11,34);

      Employee::showEmployeeCounter();
    Employee e1=e;
      Employee e2(11,34);
       Employee e3(11,34);
      Employee e4(11,34);
      Employee::showEmployeeCounter();
    e1.show();
}




Returning objects and object as method arguments

--------------------------------------------------
Array of objects

      #include <iostream>
using namespace std;

class Employee{
    private:
        int id;
        double salary;
    public:
    Employee(){}
    Employee(int id, double salary){
        this->id=id;
        this->salary=salary;
    }
    void show(){
        cout<<"id:"<<id<<endl;
        cout<<"salary:"<<salary<<endl;
    }

};
int main()
{
   Employee *ep[5];
   Employee *p1;
   int tempId;
   double tempSalary;

    for(int i=0;i<5;i++){
        cout<<"enter id and salary of "<<endl;
        cin>>tempId>>tempSalary;
         p1=new Employee(tempId,tempSalary);
         ep[i]=p1;
    }
for(int i=0;i<5;i++){
        ep[i]->show();
    }

    //most imp cleanup the memory.......

     for(int i=0;i<5;i++){
       ep[i]=NULL;
    }
}




Friend
===============
      A class can have two kinds of friends
            1. Friend function
            2. Friend class

        If a function or a class is declared as a friend to a class,
        it can access all the members including the
        private members of that class.


        breaking encapsulation?


        for 2 unrelated classes a friend function can be used to bridge bw
        two classes


        Ex:

        we want to compare size in Centimeter and Meter

        put friend function in both the classes ............



EX:
---------


#include <iostream>
#include<string.h>
#define SIZE 10
using namespace std;

class Meter;//forward decleration

class CentiMeter{
    private:
        int cm;
    public:
    CentiMeter(int size){cm=size;}
    friend void greater(CentiMeter c, Meter m);
};

class Meter{
private:
         int m;
     public:
     Meter(int size){m=size;}
     friend void greater(CentiMeter c, Meter m);
};

     void greater(CentiMeter c, Meter me){
         int inCm=me.m*100;
         if(c.cm>inCm)
              cout<<"cm is greater"<<endl;
         else
              cout<<"cm is greater"<<endl;
     }


int main(){

     CentiMeter cm(223);
     Meter m(2);
     greater(cm,m);

}



Ex:
----------

#include <iostream>
#include<string.h>
#define SIZE 10

using namespace std;

class FriendClass;

class OnlyFriends{
      char secrets[5][30];
      friend class FriendClass;
      friend void display(const OnlyFriends&);

};

class FriendClass{
      public:
      void init(OnlyFriends &o){
                  for(int i=0;i<5;i++){
                  cout<<"Tell me secret :"<<i<<":";
                  cin>>o.secrets[i];
            }
       }
};


void display(const OnlyFriends &o)
{
      for(int i=0;i<5;i++)
                  cout<<o.secrets[i]<<endl;
}



int main(){
OnlyFriends o;
     FriendClass f;

     f.init(o);
     display(o);
     return 0;
}




     friend or no friends?
     -----------------------

     Some people believe having friend classes violates
     the principle of encapsulation.

     The way we need to look at friends is like a set
     of related classes and/or functions that work
     together to provide the same abstraction.



     Some applications?
     ------------------

      A Matrix class that encapsulating matrix data
      and MatrixOperations class that provides operations for objets of this
class.(operator overloading )

     A Tester class may need a good reason to look at
     internal details of a class that it is testing that are
      normally hidden from other classes.


     A Factory class that is responsible for creating
      instances of another class (Factory Design Pattern).




 Syntax:
friend function-prototype;
friend class class-name;
Very useful in operator overloading




Day-2
==========================================================================
Function and Operator Overloading
     ----------------------------------
     Function Overloading
     Using overloaded functions
     Rules for overloading
     Operator overloading and its uses
           ‘ Overloading unary and binary operators
           ‘ Overloading the assignment operator
           ‘ Overloading the << Operator
           ‘ Overloading the increment and decrement

     Dealing with strings using operators


     Converting data types
     ----------------------------------------
     ‘ Basic to class type
     ‘ Class to basic type
     ‘ Class to another class type




Function Overloading
------------------------
      compile time phenomena


     fun(int );
     fun(int ,int);

     How it Works      ?
     --------------
     1.    compilter first look for exact match

     2.    if fails
           compiler use promotion ie char to int, float to double to find match

     3.    If both fails
           compiler tries to apply build in convrsion to actual arguments

     4.    if multiple match found then
                 compile time error !!!




     Ambigous Ex
     ---------------


     #include <iostream>
     using namespace std;

     void fun(long );
     void fun(double );
     int main()
{

      fun(0);
      return 0;

}


void fun(long t){
      cout<<"char version"<<endl;
}

void fun(double t ){
      cout<<"int version"<<endl;
}



Note:
=========

      Declaring too few (or many) overloaded version of an function
      can leads to ambiguties.......




Ex:
-

      void f1(char);

      void f1(long);


      void f2(char*);

      void f2(int*);

      main(){
            int i=9;

             f1(i);// problem which f1(char) or f1(long)?

             f2(0);// problem which f2(char*) or f2(int*) ?




Operator overloading
======================

explicit
--------

implicit
----------


C++ support both.
Mechenism to give special meaning to an existing operator.

It enhance power of extensibility of C++

operator that cant be overloaded
------------------------------
1.     class member access operator .,.*
2.     Scope resolution operator ::
3.     Sizeof operator
4.     conditional operator




Sy:

return type className::operator op(arg list)
{
      fuction body
}


Rules:
---

1. Only existing operator can be overloaded

2. overloaded operator must have at least one user define operand

3. we cant use friend fun to overload some operators
      =     ()     []    ->

4. Binary op must return some result eg. x=a+b;




Ex:
--------

overloding unary op -
--------------------------


#include <iostream>
using namespace std;
class Space
{
      int x,y,z;
      public:
            Space(){}
            Space(int x,int y,int z){
                  this->x=x;
                  this->y=y;
                  this->z=z;
            }
            void show(){
                        cout<<"("<<x<<", "<<y<<" ,"<<z<<" )"<<endl;
            }
            void operator -(){
                  x=-x;y=-y;z=-z;
}
     };
     int main(int argc, char *argv[])
     {
           Space s(2,4,-6);
           -s;
           s.show();
     }




Ex:
--------
operator overloading + , - etc
-----------------------------------


#include <iostream>
using namespace std;

class Complex{
      int real,img;
      public:
            Complex(){}
            Complex(int real,int img){
                  this->real=real;
                  this->img=img;
            }
            void show(){
                  cout<<real<<"+"<<img<<"i"<<endl;
            }
            Complex operator+(Complex c){
                  Complex temp;
                  temp.real=real+c.real;
                  temp.img=img+c.img;
                  return temp;
            }


           Complex operator-(Complex c){
                 Complex temp;
                 temp.real=real-c.real;
                 temp.img=img-c.img;
                 return temp;
           }
};


int main()
{
      Complex c1(2,4);
      Complex c2(4,5);
      Complex c3;
      c3=c1+c2;
      c3.show();
      return 0;
}
unary operator overloading ex
------------------------------
Ex: overload -ve operator for Distance class
      overload > and < operator for Distance class



class Distance
{
   private:
      int feet;              // 0 to infinite
      int inches;            // 0 to 12

      ......
      .......
}




 example extraction operator >> and insertion operator <<
-------------------------------------------------------------


#include <iostream>
using namespace std;

class Distance
{
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
   public:
      // required constructors
      Distance(){
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      friend ostream &operator<<( ostream &output,
                                       const Distance &D )
      {
         output << "F : " << D.feet << " I : " << D.inches;
         return output;
      }

      friend istream &operator>>( istream   &input, Distance &D )
      {
         input >> D.feet >> D.inches;
         return input;
      }
};
int main()
{
   Distance D1(11, 10), D2(5, 11), D3;

    cout << "Enter the value of object : " << endl;
    cin >> D3;
cout << "First Distance : " << D1 << endl;
    cout << "Second Distance :" << D2 << endl;
    cout << "Third Distance :" << D3 << endl;


    return 0;
}




overloading assignment operator =
------------------------------------------------
#include <iostream>
using namespace std;

class Distance
{
   private:
      int feet;              // 0 to infinite
      int inches;            // 0 to 12
   public:
      // required constructors
      Distance(){
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      void operator=(const Distance &D )
      {
         feet = D.feet;
         inches = D.inches;
      }
      // method to display distance
      void displayDistance()
      {
         cout << "F: " << feet << " I:" << inches << endl;
      }

};
int main()
{
   Distance D1(11, 10), D2(5, 11);

    cout << "First Distance : ";
    D1.displayDistance();
    cout << "Second Distance :";
    D2.displayDistance();

    // use assignment operator
    D1 = D2;
    cout << "First Distance :";
    D1.displayDistance();

    return 0;
}
overloading array subscripting [] op
--------------------------------------------

The subscript operator [] is normally used to access array elements.

This operator can be overloaded to enhance the existing functionality of C++
arrays.


#include <iostream>
using namespace std;
const int SIZE = 10;

class safearay
{
   private:
      int arr[SIZE];
   public:
      safearay()
      {
         register int i;
         for(i = 0; i < SIZE; i++)
         {
             arr[i] = i;
         }
      }
      int &operator[](int i)
      {
           if( i > SIZE )
           {
                cout << "Index out of bounds" <<endl;
                // return first element.
                return arr[0];
           }
           return arr[i];
      }
};
int main()
{
   safearay A;

    cout << "Value of A[2] : " << A[2] <<endl;
    cout << "Value of A[5] : " << A[5]<<endl;
    cout << "Value of A[12] : " << A[12]<<endl;

    return 0;
}
conversion functions
------------------------

     converting from build in type to class type and vica versa


     1.    build in type to class type

     2.    class type to build in type

     3.    one class type to other class type



     1.    build in type to class type
     ------------------------------------------

           it happens automatically.....using constructors.....


           ex:

           converting char* to String type
           ------------------------------------

           String::String(char *p){
                 len=strlen(p);
                 a=new char[len+1];
                 strcpy(a,p);
                 }



2.    class type to build in type
-----------------------------------------------


     for class to basic type we need conversion function

     Sy:

           operator typename(){

           }

     imp conditions:
     --------------

     1. casting function must be member of class,friend is not allowed

     2. it should not mention return type although it return type

     3. it should not have any arguments


     ex:

     String ::operator char*(){
           return p;
     }
3.    one class type to other class type
---------------------------------------------

        two techniques
        ----------------

        1. using const
        2. usign conversion fun....

        depends on wheter to keep conversion
        logic in source class or destination class




        Ex:

        consider two classes
        ------------------

        Inventory1              Inventory2
        -----------------       -------------
              int codeNo        int code
              int noOfItem            float value
              float unitPrice

        Now logically noOfItem * unitPrice=value


        So considerting Inventory1 as source class and Inventory2 as destination
class




        Source class                  Destination class


        Inventory1              Inventory2
-----------------        -------------
           int codeNo         int code
           int noOfItem             float value
           float unitPrice


           casting operator   convrsion constructor




#include <iostream>
using namespace std;

class Inventory2;//forward decleration

class Inventory1
{
      private:
      int codeNo;
      int noOfItem;
      float unitPrice;
      public:
      Inventory1(){}
      Inventory1(int c,int n,float up){
            codeNo=c;
            noOfItem=n;
            unitPrice=up;
      }
      void show(){
            cout<<"code no:"<<codeNo<<endl;
            cout<<"no of items:"<<noOfItem<<endl;
            cout<<"unit price:"<<unitPrice<<endl;
      }
      int getCodeNo(){return codeNo;}
      int getNoOfItem(){return noOfItem;}
      float getUnitPrice(){return unitPrice;}

     //conversion funtion in inventroy
     /*operator Inventory2(){
           Inventory2 temp;
           temp.code=codeNo;
           temp.value=noOfItem*unitPrice;
           return temp;
     }
     */
     //conversion funtion to get total value of stock

     operator float(){
           return unitPrice*noOfItem;
     }

};



class Inventory2
{
      private:
int code;
      float value;
      public:
      Inventory2(){}
      Inventory2(int c,float v){
            code=c;
            value=v;
      }
      void show(){
            cout<<"code:"<<code<<endl;
            cout<<"Total Stock value:"<<value<<endl;
      }

      //conversion constructor in inventroy2

      Inventory2(Inventory1 i){
            code=i.getCodeNo();
            value=i.getNoOfItem()*i.getUnitPrice();
      }

};

int main()
{
      Inventory1 iv1(22,3,560);
      Inventory2 iv2;
      iv2=iv1;

      float val=iv1;
      iv2.show();
      return 0;

}




Ex:
      String class with conversion fun to

      1. convert string to char*
      2. fun to give length of string

#include <iostream>
#include<cstring>
using namespace std;

class String
{
      char *p;
      int len;
      public:

           String(){}
           String(char *temp){
                 len=strlen(temp);
                 p=new char[len+1];
           }
void show(){
                 cout<<"string is:"<<p<<endl;
           }

           operator int(){
                 return strlen(p);
           }

           operator char*(){
                 return p;
           }

};

int main()
{
      String s("india");
      int len=s;
      char *t=s;



     return 0;
}



------------------------------
Problem with copy constructor : will discuss latter
-------------------------------------------------------------




Day-3
==========================================================================


type of relationship bw objects
      Compostion, aggrigation, Inheritance

Inheritance
      type of inheritance
      Access Modifiers
      Access and Inheritance
      Constructors and Inheritance
      Scope Resolution operator
      Multiple & Multilevel Inheritance
      Calling base class constructor
      Overriding base class members


Virtual functions and Polymorphism
      Virtual & non-virtual Overriding
      Virtual functions
      Rules for virtual functions
      Pure virtual functions
      Static and Dynamic Binding
Virtual base classes
      virtual destructor




Reusing classes, compostion
----------------------------

3 type of relationship in OO worlds:

      1.    USE-A
      2.    HAS-A
                    implemented using composition and aggrigation


      3.    IS-A
                    implemented using inheritance




Implementing composition
--------------------------

      composition;
      ----------------
            Strong relation bw two object

            if Employee is destroyed then Address also destroyed

            Employee <>-------Address

            Room<>-----------wall




ex:

---------
            Person has a date of birth
                   ------


#include <iostream>
#include<string>
using namespace std;

class Date
{
      int day,month, year;
public:
     Date(){}
     Date(int day, int month, int year){
           this->day=day;
           this->month=month;
           this->year=year;
     }

     void showDate(){
           cout<<day<<" : "<<month<<" :" <<year<<endl;
     }
};


class Person
{
      string name;
      Date date;
      public:
            Person(string x, Date d);
            void showPersonDetails();
};

//must use member initilizer list..........
Person::Person(string x, Date d):name(x),date(d)
{

}

void Person::showPersonDetails(){
      cout<<"name :"<<name;
      date.showDate();
}


int main()
{
      Date d(22,11,2011);

     Person p1("foo",d);
     p1.showPersonDetails();
     return 0;
}




Inheritance
===========

     Concept of base class and derived class.....

     resuability of code using IS-A relationship

     ex:
              Cat is-a Animal

              Employee IS-A Person

              reverse is not true


type of inheritance
---------------------
1.   single
     2.   multiple
     3.   multilevel
     4.   hierarchical inheritance




1. single
-------------
      keywork used :

     class B{

            private;
            int id;

            public:

            int j;
            void showB(){.......}
     };

     class D :public B{

            //now class D inherit j and showB() from class B


     }


     visibility modifier
     ----------------------
     private<protected<public

     private:
     -------
           never inherited
           can be accessed using public methods

     protected:
     --------
           can be assess in derived class
           cant access outside the class

            (Almost equal of default of java !!! )

     public:
     --------
           inherited
           can be access outside the class



Inheritance mode
-------------------

     private:
     -------
           private data:      Never inherited

            protected data:   become private
public data:      become private




     protected:
     --------
           private data:     Never inherited

           protected data:   remain protected

           public data:      become protected


     public:
     --------
           private data:     Never inherited

           protected data:   remain protected

           public data:      remain public




ex:
--------

#include <iostream>
#include<string>
using namespace std;

class Person
{
      string name;
      public:
            Person(){}
            Person(string name){this->name=name;}
            void showPerson(){
                  cout<<"Name of person:"<<name<<endl;
            }
};

class Employee: public Person
{
      string jobNature;
      public:
            Employee(){}
            Employee(string n, string jobNature):Person(n)
            {
                  this->jobNature=jobNature;
            }
            void showEmployee(){
                  showPerson();
                  cout<<"Job nature:"<<jobNature<<endl;
            }
};
int main()
{
      Employee e("foo","SW developer");
      e.showEmployee();
      return 0;
}
Notic:
----------

      how values for instance variable passes from derived ctor to base ctor


      Order of execution of constructor
      --------------------------------
            base class
            then
            derived class

Ex;

Multiple inheritance
-----------------------

      Person
       |
      Employee
       |
      PartTimeEmployee


Note: opportunity for debugg......
------------------------------

#include <iostream>
#include<string>
using namespace std;

class Person
{
      string name;
      public:
            Person(){}
            Person(string name){this->name=name;}
            void showPerson(){
                  cout<<"Name of person:"<<name<<endl;
            }
};

class Employee: public Person
{
      string jobNature;
      public:
            Employee(){}
            Employee(string n, string jobNature):Person(n)
            {
                  this->jobNature=jobNature;
            }
            void showEmployee(){
                  showPerson();
                  cout<<"Job nature:"<<jobNature<<endl;
            }
};

class PartTimeEmployee: public Employee
{
      double perHour;
      public:
            PartTimeEmployee(){}
            PartTimeEmployee(double perHour, string n, string
jobNature):Employee(n, jobNature)
            {
                  this->perHour=perHour;
            }
            void PartTimeEmployee(){
                  showEmployee();
                  cout<<"Per hr earning:"<<perHour<<endl;
            }
};
int main()
{
      PartTimeEmployee e(223333,"foo","SW developer");
      e.PartTimeEmployee();
      return 0;
}




Multiple Inheritance

----------------------
      Not there in Java !!!

     Can leads to poor sw design; diamond problem?


               ClassB

     ClassD1                    ClassD2

               ClassD3


     classC inherit both from ClassA and ClassB


      #include <iostream>
#include<string>
using namespace std;


class ClassB
{
      public:
            int i;

};
class ClassD1:public ClassB
{
      public:
            int j;

};

class ClassD2:public ClassB
{
      public:
            int k;
};

class ClassD3:public     ClassD1, ClassD2
{
public:
           int product(){

                 return i*j*k;
     }

};

int main()
{
      ClassD3 ob;
      ob.i=2;
      ob.j=3;
      ob.k=4;
      cout<<ob.product();
      return 0;
}


problem:
------------

     which i?

solution in C++
-----------------
      put virtual keywork before ....



class ClassD1:virtual public ClassB
{
      public:
            int j;

};

class ClassD2:virtual public ClassB
{
      public:
            int k;
};




abstract class
-------------
      aka ADT in C++

     when to declare an class abstract ?

           when we dont have symantically valid body of an method

     Ex;
     if i ask you what is the area of a Figure whose length =2 and width=3 ?

     Ans 6 ?

     But what is the shape of figure........
So we dont have answer till somebody dont specify kind of figure

     wheter it is Rectangle or Tringle?

     How to declare abostract class in C++
     -----------------------------------

     class Figure{

           public:
           virtual void showArea()=0;
           }




     Note:
     -------

            it is error to create object of abstract class , you can create
reference of
            that

     Ex:
     class Figure
     {
           public:
                 virtual void showArea()=0;
     };
     int main()
     {
           //Figure f;       compile time error

           Figure *f;//         ok
     }




Polymorphism
-------------
      many form of an funtion



           Polymorphism
     compile time               Run time

 Op overloading                 Overriding........
 function over..




#include <iostream>
#include<string>
using namespace std;

class A
{
public:
           void fun(){
           cout<<"fun of class A"<<endl;
     }
};

class B :public A
{
      public:
            void fun(){
            cout<<"fun of class B"<<endl;
      }
};


int main()
{
      A *a=new B();
      a->fun();
}




Run time polymorphism
----------------------

     requirment:
     -------------
           Base class pointer must assigned drived class object

           A *a=new B();

     still no run time polymorphism?
     -----------------------------

     Dont forget to apply virtual to base function

           virtual void fun(){
           cout<<"fun of class A"<<endl;
     }




     More example:
     ----------

           Media

#include <iostream>
#include<string>
#include<cstring>
using namespace std;

class Media
{
      protected:
      char title[20];
float price;
     public:
                 Media(){}
                 Media(char t[],float price){
                       strcpy(title,t);
                       this->price=price;
                 }

            virtual void display()=0;//dont know more stuff so make it
abstract...........

};

class Book :public Media
{
      int pages;
      public:
            Book(){}
            Book(int pages, char t[],float price):Media(t, price){
                  this->pages=pages;
            }

      void display(){
           cout<<"Title:"<<title<<endl;
           cout<<"Price:"<<price<<endl;
           cout<<"No of pages:"<<pages<<endl;
     }


};


class Tap :public Media
{
      int play_time;
      public:
            Tap(){}
            Tap(int play_time, char t[],float price):Media(t, price){
                  this->play_time=play_time;
            }

      void display(){
           cout<<"Title:"<<title<<endl;
           cout<<"Price:"<<price<<endl;
           cout<<"Play time:"<<play_time<<endl;
     }


};
int main()
{

     Book b(111, "C++ in action",2223.5);
     Media *m=&b;
     m.display();
     return 0;
}
Need of virtual destructor
-----------------------------

     Constructor cant be virtual

     but we need to have virtual destructor in some of cases....


consider :
-----------------------------

#include <iostream>
#include<string>
using namespace std;


class B{
      char *bp;

     public:
           B(){
           bp=new char[5];
           cout<<"B allocate 5 bytes"<<endl;
     }

     ~B(){
             delete []bp;
             cout<<"B De-allocate 5 bytes"<<endl;
     }
};

class D:public B{
      char *dp;

     public:
           D(){
           dp=new char[500];
           cout<<"D allocate 500 bytes"<<endl;
     }

     ~D(){
             delete []dp;
             cout<<"D De-allocate 500 bytes"<<endl;
      }
};
int main()
{

     B *p=new D();
     delete p;
     return 0;
}




OP
-------
      indicate that memory allocated by D's constructor is not freeed

     why?
     -------

      the problem is that B's Constructor is not virtual , which means that
system
      bind p at compile time rather then run time....

      because p is of type B , p is bound to B's data member and method
including
      constructor and destructor rather then D's data member and methods


     solution:
     ------------
     declare base constructor as virtual.......


     virtual ~B(){
           delete []bp;
           cout<<"B De-allocate 5 bytes"<<endl;
     }




==================================================================
some imp discussion
==========================================================

c++ automatically generated functions
----------------------------------------
      1.    Default constructor

     2.      copy constructor

     3.      Assignment operator overloaded

     4.      Destructor



even if we dont write these function thery are generated by default by c++

     Ex:


     class A{

     }

     A a1;//default const

     A a2=a1// copy const...

     A a3;

     a3=a2;// assignment op
Actually we write
------------------

class A{

};



C++ convert it to
----------------

class A{

     public:
     A(){}
     A(const A& t){}

     A& operator=(const A& temp){}

     ~A(){}

     };




     Now consider:
     ---------------

class A{
      private:

     int x,y;

};


What c++ does?
-----------------
      c++ does code gereration.....

class A{


     private:

     int x,y;

     public:
     A(){}
     A(const A& t){x=t.x;y=t.y}

     A& operator=(const A& temp){

           if(this!=temp){
                 x=temp.x;
                 y=temp.y;
}
           return *this;

      }

      ~A(){}

      };




C++ do not provoide default constructor if we provide our own
default or parameterized ctor.


Ex:

All following call default const

A obj1;

A obj1=new A;

A obj1=new A();

A *p=new A[100];// create array of 100 A's object
                  ctor called 100 times.......


Ex:

class A{

      A(int t){}
      }



All following will give compilation error ...........

A obj1;

A obj1=new A;

A obj1=new A();

A *p=new A[100];// create array of 100 A's object
                  ctor called 100 times.......



perfer new and delete in C++ rather then malloc and free
--------------------------------------------------

Never use malloc/free in case of class in c++



Ex:

A *p=new A[5];
Will create array of 5 A's object

     Note new ensure that constructor being called for each 5 object

     object are initilized....


     But:
     -----

     A *p=(A*)malloc(5*sizeof(A));

      Just allocated memory chunk required for 5 A's object but do not call
constructor

     hence must not be treated as object...........


     What to do while deleting memory of array of object
     --------------------------------------------------

     A *p=new A[5];

     delete p;
     //Wrong.......

     only delete memory occupied by A[0] object

     correct way:
     --------------
           delete []p;




     Virtual destructor in base class and its need?
     ------------------------------------------

     in case of polymorphism , if we are using pointer of base class to
     point to derived object then dont forget to make destructor of base
     class as virtual otherwise memory leak can occour..........




             Ex:

     class Shape
     {
           public:

             virtual void showShape(){}=0;
             shape(){
                   cout<<"calling base constructor"<<endl;
             }
             ~shape(){
                   cout<<"calling base de-structor"<<endl;
             }

     };


     class Circle:public Shape
{
           int *radius;
           public:

           virtual void showShape(){
                 cout<<"are of circle is"<<*radius*radius*3.14<<endl;
                 }
           shape(){
                 cout<<"calling base constructor"<<endl;
           }
           ~shape(){
                 cout<<"calling base de-structor"<<endl;

                 delete radius;
           }

     };



     ........
     .......

     {
     Shape *p=new Circle();

     p->showShape();
     }

     when scope of code finished

     only destructor of base class is called.....

     static binding.......

     leads to memroy leak....


      Make base class destructor virtual so that it its decided on the basis of
type of object
      rather then type of pointer.




How to create a class non copyable
-----------------------------------

     ie what if we do not want to support ;


     A a1=a2;// copy constructor

     and

     a3=a2;// assignment operator

     What to do?
     ===============
Dont write copy constructor and assignement operator ?

but C++ automatically generate code........


Simple solution?
------------------

make both copy ctor and assignment op overloading implementation
private.......

so that cant be called form main.


class A{


      private:

      A(const A& t){x=t.x;y=t.y}

      A& operator=(const A& temp){

           if(this!=temp){
                 x=temp.x;
                 y=temp.y;
           }
           return *this;

      }


      public:
      A(){}
      ~A(){}

      };

A a1=a2;// copy constructor

and

a3=a2;// assignment operator



Singlton design pattern:
--------------------------------

what if i want to allow programmer to create object
of an class.........


make an privte constructor

class A{

private:
A(){}

}


What if i want to have a class whose object cant be created but want to
allow
        subclassing.........?


        class A{


              private:

              A(const A& t){x=t.x;y=t.y}

              A& operator=(const A& temp){

                   if(this!=temp){
                         x=temp.x;
                         y=temp.y;
                   }
                   return *this;

              }

              protected:
              A(){}
              ~A(){}

              };

        class B:private A{}




        copy constructor : deep copy vs shallow copy
        ---------------------------------------------------


        what should happen during copying process the data of the class must
        be copied on seperate memory localtion for another object

        ie.

        let say i have define an class as:----

        class Myclass{

              int a;
              double b;
              string s;


        };
what c++ does using code generation:
     -----------------------------------

           class Myclass{

           int a;
           double b;
           string s;

           public:

           MyClass(const MyClass &m):a(m.a), b(m.b), s(m.s)
           {}

           //overloaded assignment operaotr

           //default ctor

           //default destructor

           };


     default copy const is ok in this case.




     Now consider:
     ---------

           class Myclass{

           int *p;
           double b;
           string s;

           public:

           MyClass(const MyClass &m):a(m.a), b(m.b), s(m.s)
           {}

           //overloaded assignment operaotr

           //default ctor

           //default destructor

           };

      Problem is that if MyClass container pointer to some other object /
primitive data

     then rather then creating different memory ...it just assign pointer

     so an serious problem can occour.........
WE SHOULD NOT COPY POINTERS RATHER

     COPY WHAT IS POINTED TO BY POINTER........

      If one destructor for one object is called it will corrupt shared data of
other object.......


     Dangling pointer issue
     -----------------------------

     default copy const is ok in this case.
     So never relies on default copy const


     we need deep copy?
     ---------------------




     Eg:

     class MyArray{
           public:

           int size;
           int *data;
           explicit MyArray(int s):size(s), data(new int[s])
           {}

           ~MyArray(){ delete []data;}

     }

     C++ provide its own copy constructor as follows:

     MyArray::MyArray(MyArray& temp):size(temp.size), data(temp.data)
     {}




     int main(){

           MyArray a(20);
           a.data[0]=5;
                 //define an scope
                 {
                       MyArray b=a;
                       cout<<a.data[0]<<b.data[0];
                 }

                   // b local variable is removed...


           a.data[0]=12;//segmentation fault......

     }
size would be different for two object but *data is shared.........


     Solution:
     =========

     rather then this
     ======================
     MyArray::MyArray(MyArray& temp):size(temp.size), data(temp.data)
     {}

     Use this
     ===========
     MyArray::MyArray(MyArray& temp):size(temp.size), data(new int[temp.size])
     {}




Memory leak and dangling pointer
-----------------------------------

     if you are a C++ developer you are not so lucky as Java developers

     We dont have garbage collector

     We should care about memeory related issue more then java developers

     Now will discuss some basic idea of memory leak and dangaling pointer




Memory leak
---------------

     consider

     int *p,*q;

     p=new int;//dynamically allocated memory
     q=p;

     .....
     ......
     delete(p);
     //forget to delete q


     q is still pointing to invalid memory.....



     =>POINTER q CONTAIN ADDRESS OF MEMORY LOCATION THAT DO NOT EXIST


      =>A reference to a memory object that do not exists is called "dangling
pointer"
now we say

     int *r=new int;

            let r is assigned same memory that is earlier pointed by p

     now conceptually both r and q pointing to that newly allocated memory




     =>Possibility that r data can be mismanupulated by using pointer q


     good programming practice
     --------------------
     p=new int;//dynamically allocated memory
     q=p;

     .....
     ......
     delete(p);
     q=NULL;//dont forget




Memory leak
=========
      memory block exist taht do not have valid reference to it

     Ex:
     int *p,*q;
     p=new int;

     q=new int;

     now if we do:

     p=q;

     then the memory location pointed by pointer p cant be referenced

     =>memory leak.


Day-4
==========================================================================

Templates
      need of templates, hello world
      function Template
      class Template


 Exception Handling
      Templates
      Function templates
      Class templates
      Exception handling
Templates
==============

        Need?
        ------

        let we need to have an adder that can add 2 int, float ,double whatever we
pass?


        int adder(int i, int j){
              return i+j;
        }

        double adder(double i, double j){
              return i+j;
        }


        Same algo only data type changes?

        go for

        function Template ........
        ==========================



             template <class T>

             T adder(T i, T j){
                         return i+j;
                   }




        function template with multiple parameters
        ---------------------------------------

        template <class T1,class T2>


        void printMe(T1 t1, T2 t2)
        {
                    cout<<t1<<endl;
                    cout<<t2<<endl;
        }

        int main()
        {

        printMe("foo",121);
        }
class Template
     ------------------




#include <iostream>
#include<string>
using namespace std;

template <class T>
class Adder
{
      T first, second;
      public:
            Adder(T a, T b){
            first=a;
            second=b;
      }
      T sum();
};

//now most strang syntex c++

template <class T>
T Adder<T>::sum(){
      return first+ second;
}


int main()
{
      Adder<int>add(22,22);
      int temp=add.sum();
      cout<<temp;

     //same for double etc......
     return 0;
}




template specilization
----------------------------
      way to make class different implementation with specific one !!!

     lets we want to handle a particular data type differntly then other one

     problem......

     for ex i want to have differnt behaviour when char data is used........
solution
     --------------
           template specilization




#include <iostream>
using namespace std;

template<class T>
class Foo{
    public:
    Foo(T t){
        cout<<"for all data except char"<<endl;
    }
};
template<>
class Foo<char>{
    public:
    Foo(char t){
        cout<<"for char"<<endl;
    }
};
int main()
{
    Foo<int> ob1(2);
    Foo<float>ob2(4.6);
    Foo<char>ob3('c');
    return 0;
}




Exception Handling
----------------------


     exception handling is unusual condition (such as errors) that can
     cause proram to misbehaves /terminate


           Exceptions

     Synchronous         Asynch

     out of range             keyboard error
     overflow etc
to handling error during program running.....

      All exception happens at run time

      keywords
      ---------

      try
      catch
      throw

      Note: No finally or throws as in Java



      put risky code inside try
      --------------------------

      Ex:


  #include <iostream>
using namespace std;

int main()
{
      int income=78;
    int expence=90;
    try{
         if(expence>income){
             throw 99;   //error no
         }
    }
    catch(int i){
         cout<<"cant do that"<<endl;
    }

    catch(...){
         cout<<" do that"<<endl;
     }

      return 0;
}



      throwing an exception from an functions
      -------------------------------------------

      #include <iostream>
using namespace std;


void xFun(int t){
      cout<<"inside xFun "<<t<<endl;
      if( t){
            throw 55;
      }
}

int main()
{
try{
       xFun(0);
           xFun(10);
    }
    catch(int i){
         cout<<"cant do that"<<endl;
    }

    catch(...){
         cout<<" do that"<<endl;
     }

      return 0;
}




Handling exception thrown by new
-----------------------------
      in c++ when an allocation fails then new throws an bad_alloc exception

      we can handle it.......



      use <new.h>


#include <iostream>
#include<new>
using namespace std;


int main()
{
      double *p;
      do{

            try{
                  p=new double[100000];
            }
            catch(bad_alloc x){
                  cout<<"allocation error"<<endl;
                  return 1;
            }
            cout<<"Allocation is ok"<<endl;
      }while(p);
      return 0;
}




smart pointer
===============
      smart pointer helps solving problem associated with pointer


      Consider exception safe code:
-------------------------------

MyClass *ptr;

ptr=new MyClass();
ptr->doFooWork();

delete ptr;

Now what some bug is there in doFooWork() and we dont get chance
for execution of delete ptr; statement

memory leak.....


Now we can improve the code as:

MyClass *p;

try{

       ptr=new MyClass();
       ptr->doFooWork();
}

catch(...){
      delete ptr;
}

Now its guranteed that wheter doFooWork(); work sucessfully or not

delete ptr; always execute......


but now everytime we are allocating dynamically

we need to use try catch........ :(




template<class T>

class auto_ptr
{
      T *ptr;

       public:
       explicit auto_ptr(T *t=NULL):ptr(p){}
       ~auto_ptr(){delete ptr;}

       T& operator* (){return *ptr;}//help in dereferencing ptr
       T& operator-> (){return ptr;}//help in referencing ptr

       //Some more code......

};



Now rather then;
----------------
ptr=new MyClass();

           ptr->doFooWork();

           delete ptr;


     we use someting like:
     ------------------------

            auto_ptr <MyClass>p (new MyClass());//automatic variable that is
always for scope

           p->doFooWork();




     how it should work ( Dont forget dry run !!!)
     ----------------------------------------------

      auto_ptr <MyClass>p (new MyClass());//automatic variable that is always
for scope

     when object goes out of scope ..destructor of auto_ptr class invoked

      Issue of ensureing deleting dynamically allocated memory is
solved..........


     Dont need unnessary try....catch.




     C Macros vs C++ template
     --------------------------

     Dont use c macro for implementation of gernalized logic in c++

     C++ template prove to be more superiour in most of the cases.....


     Ex:

     #define MAX(a,b)    fun((a)>(b)?(a):(b))


     Now we have unpredictable behabiour in following case:
-----------------------------------------------

     int i=10;
     int j=5;

     method call MAX(++i, j)// i incremented twice

     method call MAX(++i,j+10)// i incremented once


     What is better approach:
     -------------------------


     use template:

           1. provide predictable code
           2. type sale......



     template <T t>
     inline void MAX(const T&a, const T&b){
           fun(a>b?a:b);
     }

     1. no need of ()
     2. inline is same efficient as macro


Day-5
==========================================================================

     STL
     Std template Libarary.....

     Readymade DS in C++



                 STL


     container         algorithm          iterator

     how to hold object      act on container   how to move back/forth

     vector                  initilization           pointer
     Queue             sorting                 cycle through
     list              searching         content of container
                       transforming

                                          Input OP     Random    Bidirectional
     Forward




     Associative container
     --------------------
     Efficient retrival on basis of key
     Ex:
     Map
Container classes
     -------------

     bitset      :       set of bits <bitset>

     deque :     a double ended queue     <deque>

     list    :   linear list

     map     :   key value only by value <map>

     multimap:


     multiset:

     priority_queue

     queue

     set

     stack

     vector




Day-6
================================================================================
================



     File IO
     RTTI

Contenu connexe

Tendances

Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
Function in Python
Function in PythonFunction in Python
Function in PythonYashdev Hada
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++guestf0562b
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in javaanshu_atri
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.Haard Shah
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-pythonAakashdata
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programmingClaus Wu
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 
C programming presentation for university
C programming presentation for universityC programming presentation for university
C programming presentation for universitySheikh Monirul Hasan
 

Tendances (20)

Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
LLVM
LLVMLLVM
LLVM
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
Deep C
Deep CDeep C
Deep C
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Data types in C
Data types in CData types in C
Data types in C
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
C programming presentation for university
C programming presentation for universityC programming presentation for university
C programming presentation for university
 
C# in depth
C# in depthC# in depth
C# in depth
 

En vedette

Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)Tola LENG
 
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseConfigure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseTola LENG
 
Install linux suse(sless11)
Install linux suse(sless11)Install linux suse(sless11)
Install linux suse(sless11)Tola LENG
 
Configure active directory &amp; trust domain
Configure active directory &amp; trust domainConfigure active directory &amp; trust domain
Configure active directory &amp; trust domainTola LENG
 
Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11Tola LENG
 
DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)Tola LENG
 
How to be a good presentor by tola
How to be a good presentor by tolaHow to be a good presentor by tola
How to be a good presentor by tolaTola LENG
 
Tola.leng sa nagios
Tola.leng sa nagiosTola.leng sa nagios
Tola.leng sa nagiosTola LENG
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jRajiv Gupta
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modulesmohamedmoharam
 
Basic security &amp; info
Basic security &amp; infoBasic security &amp; info
Basic security &amp; infoTola LENG
 
File Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and WindowsFile Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and WindowsTola LENG
 
How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7Tola LENG
 
Configure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-RelayConfigure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-RelayTola LENG
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jspRajiv Gupta
 

En vedette (20)

Network Diagram
Network DiagramNetwork Diagram
Network Diagram
 
Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)
 
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseConfigure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
 
Map.ppt
Map.pptMap.ppt
Map.ppt
 
Install linux suse(sless11)
Install linux suse(sless11)Install linux suse(sless11)
Install linux suse(sless11)
 
Configure active directory &amp; trust domain
Configure active directory &amp; trust domainConfigure active directory &amp; trust domain
Configure active directory &amp; trust domain
 
Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11
 
DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
How to be a good presentor by tola
How to be a good presentor by tolaHow to be a good presentor by tola
How to be a good presentor by tola
 
Tola.leng sa nagios
Tola.leng sa nagiosTola.leng sa nagios
Tola.leng sa nagios
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modules
 
Basic security &amp; info
Basic security &amp; infoBasic security &amp; info
Basic security &amp; info
 
Jsp Notes
Jsp NotesJsp Notes
Jsp Notes
 
File Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and WindowsFile Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and Windows
 
How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7
 
Configure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-RelayConfigure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-Relay
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jsp
 

Similaire à Advance C++notes

M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversionNabeelaNousheen
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started CppLong Cao
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific StatisticsThe Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific StatisticsMichael Rosenblum
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxssuser3cbb4c
 
c++ practical Digvajiya collage Rajnandgaon
c++ practical  Digvajiya collage Rajnandgaonc++ practical  Digvajiya collage Rajnandgaon
c++ practical Digvajiya collage Rajnandgaonyash production
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxssuser454af01
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
 

Similaire à Advance C++notes (20)

C++ Programs
C++ ProgramsC++ Programs
C++ Programs
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Lecture5
Lecture5Lecture5
Lecture5
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversion
 
Getting Started Cpp
Getting Started CppGetting Started Cpp
Getting Started Cpp
 
Writing MySQL UDFs
Writing MySQL UDFsWriting MySQL UDFs
Writing MySQL UDFs
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific StatisticsThe Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
 
Quiz 9
Quiz 9Quiz 9
Quiz 9
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
c++ practical Digvajiya collage Rajnandgaon
c++ practical  Digvajiya collage Rajnandgaonc++ practical  Digvajiya collage Rajnandgaon
c++ practical Digvajiya collage Rajnandgaon
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 

Plus de Rajiv Gupta

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepRajiv Gupta
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentalsRajiv Gupta
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2Rajiv Gupta
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastRajiv Gupta
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect jRajiv Gupta
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injectionRajiv Gupta
 
Java spring framework
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuffRajiv Gupta
 

Plus de Rajiv Gupta (13)

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by step
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencast
 
Struts2
Struts2Struts2
Struts2
 
Java 7
Java 7Java 7
Java 7
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect j
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injection
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuff
 

Dernier

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Dernier (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Advance C++notes

  • 1. Advance C++ ================================================= Day-1: Intro to oo programming MinGW compiler and basic commands Configuration codeblock IDE/Eclipse IDE Procedural stuff Additional feature of C++ not in C Day-2: class and object c++ advance stuff 1. dont return address of local variable from an method. Day-3: Function and Operator Overloading Day-4: inheritance,compostion and Polymorphism c++ advance stuff 1. understanding c++ automatically generated functions:default ctor, copy ctor, overloded assignment op, destructor 2. new vs malloc : which to use for object creation 3.Virtual destructor in base class and its need 4. How to create a class non copyable 5. singlton design pattern 6. copy constructor : deep copy vs shallow copy 7. Memory leak and dangling pointer Day-5: Templates, Exception Handling c++ advance stuff Smart pointer: need and implementation C Macros vs C++ template Day-6: STL Day-7: File IO, RTTI Day-8: Memory mgt in C++ Day-9: Database programming
  • 2. Day-9 and 10: Project Work MCQ test. ========================================================================== Day-1 ---------- minGW compiler installation set path for compiler Hello World ---------------- #include <iostream> using namespace std; int main() { cout<<"Hello world"<<endl; return 0; } Command to compile; ------------------ g++ -o Hello Hello.cpp OOPs piller ------------ Abstraction and encapsulation Hirerchy Modularity Concepts: ---------- class object abstraction , encapsulation, data hiding inheritance, polymorphism......
  • 3. Procedural stuff --------------- if...else for, while , do.....while questions: --------- * ** *** **** ***** Dry run !!! Array ---------- one D two D Examples. Sorting ex. inserting /deletion element in sorted array Additional feature of C++ not in C ------------------------------- use of void pointer Difference in use of enum annonymous enum Reference variable call by ref vs call by pointer new and delete operator inline fun C++ operators Struct of C++ Union of C++ annonymous union use of void pointer ------------------ C++ is strongly typed language then C #include <iostream> using namespace std; int main() { void *p; char temp='a';
  • 4. char *q=&temp; q=p;//compile error return 0; } Will not copile need explicit type casting -------------------------------------- q=(char*)p;//compile Note: int i; double j=89.5; i=j;//OK in C++ error in Java. Difference in use of enum ---------------------- enum is named constant in C++ tag name become new data type while in C they are treated as integer Ex: enum shape{circle, square,tringle}; shape eclipse;// ok in c++ enum color{red, green, yellow}; color background=blue;//ok color background=7;//error color background=(color)7;//ok ? annonymous enum -------------------- enum{OFF, ON}; int status=OFF; .... ...... Reference variable --------------------- alias to previouly define variable -------------- Ex: float total=100;
  • 5. float &num=total; now num and total point to same memory location, ie both are alieas if we change total num will be changed.... Why to use reference? ----------------------------- 1. easy to use then pointer 2. can used to produce effect of call by reference (swap the values) 3. C dont support call by reference it support call by pointer Ex: call by pointer that you know -------------------------------------- void swap(int *p,int *q){ int temp=*p; *p=*q; *q=temp; } int main(){ ........... int i=11; int j=22; .......print before swap swap(&i, &j); ......print after the swap. } what you should also know is call by reference ----------------------------- simple and clean !!! void swap(int &p,int &q){ int temp=p;
  • 6. p=q; q=temp; } int main(){ ........... int i=11; int j=22; .......print before swap swap(i, j);//simple code ......print after the swap. Normally using pointer an method can't come at LHS ie fun()=x;//Not seen !!! this is possible using reference ------------------------------------ int& max(int &x, int &y){ if(x>y) return x; else return y; } main(){ ........... .............. max(a,b)=-1// will assign -1 to whoever is greater............. } new and delete operator ------------------------- Memory management operator in C++ Dont use malloc/alloc in C++( can use) Ex: ----- int *p=new int; int temp=99; p=&temp; cout<<p<<endl;
  • 7. delete p; Ex: allocating memory for an array ----------------------------- int *p=new float[5]; delete p;//wrong only delete pointer....... delete []p;//correct --------------------------------------------------------------- Remember: its programmer job to delete dynamically allocated memory from heap if you dont do it.....it can leds to memory leak ------------------------------------------------- C++ operators --------------------- list of operator not in C :: scope resolution operator ::* pointer to member operator ->* Pointer to member operator .* Pointer to member operator << insertion operator >> extractor delete memory mgt operator endl line feed operator new memory mgt operator setw field width seperator Struts of C++ ------------- no technical difference data is private by default. Union of C++ -----------------
  • 8. annonymous union ================================================================================ ===================== Day-2 class and object ================================================================================ ===================== Defining a class Creating an object Object Scope Data Abstraction Enforcing Data Encapsulation ‘this‘ Pointer Defining member functions Dynamic creation of objects Constructors and Destructors The Default Constructor The Destructor Parameterized Constructors Copy constructor Constructor initializers Some misc topics: random no generation sizeof operator const keyword Multifile program in C++ Static static data static methods Returning objects Arrays of Objects Methods and access modifiers Accessing class data and methods
  • 9. Friend class and friendly functions Defining a class and creating an object ====================== class NameOfTheClass{ //data member //member methods }; Ex: class Employee{ public: int id; double salary; }; void main() { Employee e; e.id=22; e.salary=3344.6; } Creating an object ------------------ Employee e; create an object e Note:
  • 10. Employee *e;//NOT CAREAT OBJECT BUT OBJECT HANDLER Note object has 3 things ---------------------- 1. state decided by instance variable 2. behaviour decided by instance methods 3. identity Equivalent concept as PK in database Ex: id of employee should unique.......... Object Scope ------------- consider ................ void main() { { Employee e; e.id=22; e.salary=3344.6; } cout<<e.id<<endl; //ERROR OBJECT SCOPE PROBLEM } Data Abstraction ----------------------- foucus on essential thing........ Data Encapsulation ------------------------ HIDING UNNESSARY DETAILS...........
  • 11. sound same? above ex kills Encapsulation ------------------------ data should be accessable/ changes using public methods class X{ private data public method } class Employee{ private: int id; double salary; public: void setId(int a){ id=a; } void setSalary(double a){ salary=a; } void show(){ cout<<"id is :"<<id<<endl; cout<<"salary is :"<<salary<<endl; } } void main(){ Employee e;// creating an emp object //e.id=22;//will not compile e.setId(22); e.setSalary(333.7); e.show(); }
  • 12. Note: ------ an class can have 3 type of data in the class 1. instance variable Ex: id and salary is instance variables 2. static 3. local Ex: a is an local variable in........ void setId(int a){ id=a; } ‘this‘ Pointer ================ this is implecit pointer passed to every method used to resolve confusion bw local and instance variables what if we want to have something like......... void setId(int id){ id=id; } confusion is which id is assigned to which id ??????? use this: ------------- class Employee{ private: int id; double salary;
  • 13. public: void setId(int id){ this->id=id; } void setSalary(double salary){ this->salary=salary; } void show(){ cout<<"id is :"<<this->id<<endl; cout<<"salary is :"<<salary<<endl; } } void main(){ Employee e;// creating an emp object //e.id=22;//will not compile e.setId(22); e.setSalary(333.7); e.show(); } another use of this ------------------------ returning *this return the address of object that has called method let us C some POC program: #include <iostream> #include<cstring> using namespace std; class Person { char *name; int age; public: Person(){} Person(char *t, int a){ int len=strlen(t); name=new char[len+1]; strcpy(name, t); }
  • 14. Person& greater( Person &p); void show(){ cout<<"name is:"<<name<<endl; cout<<"age is:"<<age<<endl; } }; Person& Person::greater( Person &p){ if(p.age>age) return p; else return *this; } int main() { Person p1("foo",45); Person p2("bar",25); Person p3=p1.greater(p2); p3.show(); return 0; } Now what if we want to initilize the state of the object at the time of creation? --------------------------------------------- when we say..... Employee e; e will have default value of id and salary that is garbage is there is any way to provide some meaningful values? Moreover we are using setter method -------------------------------- Disadvantage of setter ?
  • 15. ---------------------- can be called many a time ..... may create problem..... what problem: if somebody called setId() twice he can change it...may not suitable as per business logic..... Constructor =============== class X{ private: int i,j; public: X(){ //default constructor cout<<"default const"<<endl; } X(int i, int j){ //parameterized constructor cout<<"default const"<<endl; this->i=i; this->j=j; } //copy constructor latter on* };//end of the class Ex: --- class Employee{ private: int id; double salary; public: void Employee(){ id=0; salary=0.0; }
  • 16. void Employee(int id=0, double salary=0){ this->id=id; this->salary=salary; } void show(){ cout<<"id is :"<<this->id<<endl; cout<<"salary is :"<<salary<<endl; } } void main(){ Employee e;// creating an emp object //e.id=22;//will not compile e.setId(22); e.setSalary(333.7); e.show(); } important feature of constructors: ----------------------------------- 1. constructor can be public/private 2. should have same name as that of class 3. should not return anything not even void 4. invoked automatically....at the time of creation of the object after object creation cant be used ie. work only once the object life cycle 5. we can't refer to there addresss..... 6. Constructor can be overloaded but cant be overriden* 7. Can't inherit.... reference in c++ ------------------- Now after undestanding basic of reference in C++ come back on pending topic ie copy constructor
  • 17. copy constructor ------------------------ http://www.codeproject.com/Tips/78946/C-Copy-Constructor-in-depth default argument to an method ------------------------------ small useful concept of C++ ----------------------------- we can define an fuction as; foo(int i=0,int j=0){ ..... ... } void main(){ foo(); foo(11,66); } foo(); in this case i and j assigned to default values ie 0 foo(11,66); in this case i and j assigned to assigned values ie 11 and 66
  • 18. Dynamic creation of objects ================================ Object pointer /ref ------------------ When we say ...... Employee e; this create an object in stack area( more on memory latter......) We can also say...... Employee *e; in this case e is an pointer that can point to an object in heap(latter in detail) Employee *e=new Employee; will call default const Employee *e=new Employee(); will call default const Employee *e=new Employee(22,44); an object can be reffered by more then one pointer at a time but one pointer cant refer two object at a time.......... So ...... identity of an object is unique........... inline function ================== How function calling happens? ---------------------------- function that is called ,address pushed to stack...and control transfer to called fuction and after finishing stack is reffered again....... may be slow if an small fuction is called 100 time in an program
  • 19. macro of C ------------- forget about it!!! what is C++ approach? ----------------------- use inline function......... Ex: void inline sum(int a,int b){ return a+b; } call as usual from main........ Note; good coding practics says that we should have prototype of method in the class and defination should be seperate (Multifile program in C++ latter...........) class Employee{ private: int id; double salary; public: void Employee(); void Employee(int id, double salary); void show(); //method decleration ! }; void Employee::Employee(){ id=0; salary=0.0; } void Employee::Employee(int id=0, double salary=0){
  • 20. this->id=id; this->salary=salary; } //method defination void Employee::show(){ cout<<"id is :"<<this->id<<endl; cout<<"salary is :"<<salary<<endl; } important thing is :: ie scope resolution operator --------------------------------- resolve the confusion ? 1. which method defination belong to which class 2. resolve confusion bw local variable and local variable ex: int i=89;// global in C/C++ int main(){ int i=90;//local cout<<i<<endl; cout<<::i<<endl; //global one....... } destructor in c++ ==================== clean up job we have to do overself :) power to programmer can be faster if memory management is done by programmer :( more memoery mgt related issues dangling pointer Memroy leak * No GC (not lucky as Java guys.........) you are powerful enough to create your own GC !!!
  • 21. Ex: class Demo{ public: Demo(){ cout<<"constructor of Demo class......"<<endl; } ~Demo(){ cout<<"destructor of Demo class......"<<endl; } }; int main(){ Demo d; } OP ======= constructor of Demo class...... destructor of Demo class...... imp ========== int main(){ Demo *d=new Demo; delete d; } in this case destructor is not going to call till you do not call delete Remember; ========= if programmer burden to clean dynamically allocated memory........
  • 22. dont forget delete ever you use new in C++ Ex: stack --------------------- #include <iostream> #include<string.h> #define SIZE 10 using namespace std; class Stack{ private: int s[SIZE]; int top; public: void init(){ top=0;// no valid element in the stack } void push(int data){ if(top==SIZE){ cout<<"stack is full"<<endl; return; } s[top++]=data; } int pop(){ if(top==0){ cout<<"stack is full"<<endl; return -1; } s[--top]; } }; int main(){ Stack st; st.init(); st.push(3); st.push(4); cout<<st.pop(); } Copy constructor: ======================= Compiler provide default copy constructor if you are not providing.......
  • 23. copy constructor --------------- #include <iostream> #include<string.h> #define SIZE 10 using namespace std; class Employee{ private: int id; double salary; public: Employee(); Employee(int id, double salary); Employee(Employee &); void show(); }; Employee::Employee(){ id=salary=0; } Employee::Employee(int id, double salary){ this->id=id; this->salary=salary; } Employee::Employee(Employee &e){ this->id=e.id; this->salary=e.salary; } void Employee::show(){ cout<<"id:"<<id<<endl; cout<<"salary:"<<salary<<endl; } int main(){ Employee e(11,34); Employee e1=e; e1.show(); } Compiler synthesized default copy constructor ----------------------------------------------- A default copy constructor simply copies all the members. Most of the time, this default behaviour is acceptable. When it really does not work is when we have pointer variables as members of our class. This is because the default copy constructor does a shallow copy ‘ that is only values of the fields are copied. In other words, the pointer field in both the original object
  • 24. and the copy will then point to the same dynamically allocated memory. This may not be what we desire for pointer datatypes. problem with default compiler provided default copy const ------------------------------------------- it do shallow copy Ex: #include <iostream> using namespace std; class A { int *j; public: A(int j1){ j=new int; *j=j1; } void setJ(int j1){ *j=j1;} int getJ(){return *j;} }; int main() { int k=12; A a1(k); A a2=a1; k=10; a2.setJ(k); cout<<a1.getJ()<<endl; cout<<a2.getJ()<<endl; return 0; } Now we need to provide copy constructor as: ------------------------------------------- To override the default behaviour, we create copy constructors in our code. What we need is a deep copy( copies all fields, and makes copies of dynamically allocated memory pointed to by the fields).
  • 25. corrected program ------------------------ #include <iostream> using namespace std; class A { int *j; public: A(int j1){ j=new int; *j=j1; } A(A &a){ j=new int; *j=a.getJ(); } void setJ(int j1){ *j=j1;} int getJ(){return *j;} }; int main() { int k=12; A a1(k); A a2=a1; k=10; a2.setJ(k); cout<<a1.getJ()<<endl; cout<<a2.getJ()<<endl; return 0; } Good Programming practics -------------------------- To make a deep copy, we need to do two things ---------------------------------------------------- 1. write a copy constructor 2. overload the assignment operator, otherwise the copy will point to the original, with disastrous consequences. (will cover latter) Constructor initializers ------------------------------- If we just need to initialize the values without doing any checks then we could simply do it using constructor initialization list also.
  • 26. This is just another way to initialize Example: class Complex{ private: double real; double img; public: Complex(double r, double i):real(r), img(i){} }; Some misc topics: ----------------------------- random no generation sizeof operator const keyword random no generation ----------------------- #include <iostream> #include<ctime> #include<cstdlib> using namespace std; int main() { srand(time(0)); for(int temp=0;temp<100;temp++){ cout<<1+rand()%6<<endl; } return 0; } sizeof operator ----------------------- int temp=0; cout<<sizeof(temp);
  • 27. const keyword ------------------ aka final of Java cant be change once assigned...... 1. const on variable 2. const on object 2. const on method 3. const on method arguments 1. const on variable -------------------------- Ex: const int i=90; i=0;//will create compile error...... return 0; 2. const on object --------------------- when object is constant we can call only constant method on the object with regular object we can call regular methods/const methods both. Ex: #include <iostream> using namespace std; class Foo { int i; public: Foo(int i){this->i=i;} void show(int temp); void show2(int temp)const; }; void Foo::show(int temp){ cout<<"showing show of Foo"<<endl; i=i+temp; } //Error not allowed to change value of instance variable in show2() void Foo::show2(int temp)const{
  • 28. cout<<"showing constant show of Foo"<<endl; i=i+temp; } int main() { const Foo f(22); f.show2(44); return 0; } How to declare an function constant? ------------------------------------ creating constant object --------------------------- void Foo::show2()const{ cout<<"showing show of Foo"<<endl; } Constant variable ------------------ can only initilize once , then cant be chage we need special syntac called Member initilization ------------------------ Ex: #include <iostream> using namespace std; class Foo { const int i; public: Foo(int i){this->i=i;} void show(); }; void Foo::show(){ cout<<"showing show of Foo"<<endl; } int main() { Foo f(22); f.show(); return 0;
  • 29. } Foo(int i){this->i=i;} has to be replaced by Foo(int i):i(i){} Multifile program in C++ --------------------------- enhance Modularity of sw development what if 100 classes in an project? How to do it? Codeblock make it easy :) FILE======>NEW ======>CLASS give an good name to class ... .... now we have: ------------- main.cpp Employee.cpp ------------ putting implementation Employee.h ---------- function prototype and variable decleration both cpp must have -------------------- #include <iostream> using namespace std; must mention ----------- #include "Employee.h" in main.cpp finally we have 3 files ------------------------- main.cpp =========== #include <iostream> #include "Employee.h" using namespace std;
  • 30. int main() { Employee e(22,44); e.show(); } Employee.cpp ============== #include "Employee.h" #include <iostream> using namespace std; Employee::Employee() { } Employee::Employee(int id,float salary) { this->id=id; this->salary=salary; } void Employee::show() { cout<<"id:"<<id<<endl; cout<<"salary:"<<id<<endl; } Employee.h =========== #ifndef EMPLOYEE_H #define EMPLOYEE_H class Employee { private: int id; float salary; public: Employee(); Employee(int id, float salary); void show(); }; #endif // EMPLOYEE_H Static
  • 31. ================ static data static methods instance data; ----------------- per object seperate copy for every object Ex: name an id of employee are seperate static data: ----------- only one copy of data for whole class visible only within the class, lifetime is whole program. static method ------------ can be called without creating any object can not refer instance variables Ex: #include <iostream> #include<string.h> using namespace std; class Employee{ private: int id; double salary; static int counter; public: Employee(); Employee(int id, double salary); Employee(Employee &); static void showEmployeeCounter(){ cout<<"total employee created :"<<counter<<endl; } void show(); }; Employee::Employee(){ id=salary=0; counter++; } Employee::Employee(int id, double salary){ this->id=id; this->salary=salary; counter++; } int Employee::counter=0;
  • 32. Employee::Employee(Employee &e){ this->id=e.id; this->salary=e.salary; } void Employee::show(){ cout<<"id:"<<id<<endl; cout<<"salary:"<<salary<<endl; } int main(){ Employee e(11,34); Employee::showEmployeeCounter(); Employee e1=e; Employee e2(11,34); Employee e3(11,34); Employee e4(11,34); Employee::showEmployeeCounter(); e1.show(); } Returning objects and object as method arguments -------------------------------------------------- Array of objects #include <iostream> using namespace std; class Employee{ private: int id; double salary; public: Employee(){} Employee(int id, double salary){ this->id=id; this->salary=salary; } void show(){ cout<<"id:"<<id<<endl; cout<<"salary:"<<salary<<endl; } }; int main() { Employee *ep[5]; Employee *p1; int tempId; double tempSalary; for(int i=0;i<5;i++){ cout<<"enter id and salary of "<<endl; cin>>tempId>>tempSalary; p1=new Employee(tempId,tempSalary); ep[i]=p1; }
  • 33. for(int i=0;i<5;i++){ ep[i]->show(); } //most imp cleanup the memory....... for(int i=0;i<5;i++){ ep[i]=NULL; } } Friend =============== A class can have two kinds of friends 1. Friend function 2. Friend class If a function or a class is declared as a friend to a class, it can access all the members including the private members of that class. breaking encapsulation? for 2 unrelated classes a friend function can be used to bridge bw two classes Ex: we want to compare size in Centimeter and Meter put friend function in both the classes ............ EX: --------- #include <iostream> #include<string.h> #define SIZE 10 using namespace std; class Meter;//forward decleration class CentiMeter{ private: int cm; public: CentiMeter(int size){cm=size;} friend void greater(CentiMeter c, Meter m); }; class Meter{
  • 34. private: int m; public: Meter(int size){m=size;} friend void greater(CentiMeter c, Meter m); }; void greater(CentiMeter c, Meter me){ int inCm=me.m*100; if(c.cm>inCm) cout<<"cm is greater"<<endl; else cout<<"cm is greater"<<endl; } int main(){ CentiMeter cm(223); Meter m(2); greater(cm,m); } Ex: ---------- #include <iostream> #include<string.h> #define SIZE 10 using namespace std; class FriendClass; class OnlyFriends{ char secrets[5][30]; friend class FriendClass; friend void display(const OnlyFriends&); }; class FriendClass{ public: void init(OnlyFriends &o){ for(int i=0;i<5;i++){ cout<<"Tell me secret :"<<i<<":"; cin>>o.secrets[i]; } } }; void display(const OnlyFriends &o) { for(int i=0;i<5;i++) cout<<o.secrets[i]<<endl; } int main(){
  • 35. OnlyFriends o; FriendClass f; f.init(o); display(o); return 0; } friend or no friends? ----------------------- Some people believe having friend classes violates the principle of encapsulation. The way we need to look at friends is like a set of related classes and/or functions that work together to provide the same abstraction. Some applications? ------------------ A Matrix class that encapsulating matrix data and MatrixOperations class that provides operations for objets of this class.(operator overloading ) A Tester class may need a good reason to look at internal details of a class that it is testing that are normally hidden from other classes. A Factory class that is responsible for creating instances of another class (Factory Design Pattern). Syntax: friend function-prototype; friend class class-name; Very useful in operator overloading Day-2 ==========================================================================
  • 36. Function and Operator Overloading ---------------------------------- Function Overloading Using overloaded functions Rules for overloading Operator overloading and its uses ‘ Overloading unary and binary operators ‘ Overloading the assignment operator ‘ Overloading the << Operator ‘ Overloading the increment and decrement Dealing with strings using operators Converting data types ---------------------------------------- ‘ Basic to class type ‘ Class to basic type ‘ Class to another class type Function Overloading ------------------------ compile time phenomena fun(int ); fun(int ,int); How it Works ? -------------- 1. compilter first look for exact match 2. if fails compiler use promotion ie char to int, float to double to find match 3. If both fails compiler tries to apply build in convrsion to actual arguments 4. if multiple match found then compile time error !!! Ambigous Ex --------------- #include <iostream> using namespace std; void fun(long ); void fun(double ); int main()
  • 37. { fun(0); return 0; } void fun(long t){ cout<<"char version"<<endl; } void fun(double t ){ cout<<"int version"<<endl; } Note: ========= Declaring too few (or many) overloaded version of an function can leads to ambiguties....... Ex: - void f1(char); void f1(long); void f2(char*); void f2(int*); main(){ int i=9; f1(i);// problem which f1(char) or f1(long)? f2(0);// problem which f2(char*) or f2(int*) ? Operator overloading ====================== explicit -------- implicit ---------- C++ support both.
  • 38. Mechenism to give special meaning to an existing operator. It enhance power of extensibility of C++ operator that cant be overloaded ------------------------------ 1. class member access operator .,.* 2. Scope resolution operator :: 3. Sizeof operator 4. conditional operator Sy: return type className::operator op(arg list) { fuction body } Rules: --- 1. Only existing operator can be overloaded 2. overloaded operator must have at least one user define operand 3. we cant use friend fun to overload some operators = () [] -> 4. Binary op must return some result eg. x=a+b; Ex: -------- overloding unary op - -------------------------- #include <iostream> using namespace std; class Space { int x,y,z; public: Space(){} Space(int x,int y,int z){ this->x=x; this->y=y; this->z=z; } void show(){ cout<<"("<<x<<", "<<y<<" ,"<<z<<" )"<<endl; } void operator -(){ x=-x;y=-y;z=-z;
  • 39. } }; int main(int argc, char *argv[]) { Space s(2,4,-6); -s; s.show(); } Ex: -------- operator overloading + , - etc ----------------------------------- #include <iostream> using namespace std; class Complex{ int real,img; public: Complex(){} Complex(int real,int img){ this->real=real; this->img=img; } void show(){ cout<<real<<"+"<<img<<"i"<<endl; } Complex operator+(Complex c){ Complex temp; temp.real=real+c.real; temp.img=img+c.img; return temp; } Complex operator-(Complex c){ Complex temp; temp.real=real-c.real; temp.img=img-c.img; return temp; } }; int main() { Complex c1(2,4); Complex c2(4,5); Complex c3; c3=c1+c2; c3.show(); return 0; }
  • 40. unary operator overloading ex ------------------------------ Ex: overload -ve operator for Distance class overload > and < operator for Distance class class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 ...... ....... } example extraction operator >> and insertion operator << ------------------------------------------------------------- #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } friend ostream &operator<<( ostream &output, const Distance &D ) { output << "F : " << D.feet << " I : " << D.inches; return output; } friend istream &operator>>( istream &input, Distance &D ) { input >> D.feet >> D.inches; return input; } }; int main() { Distance D1(11, 10), D2(5, 11), D3; cout << "Enter the value of object : " << endl; cin >> D3;
  • 41. cout << "First Distance : " << D1 << endl; cout << "Second Distance :" << D2 << endl; cout << "Third Distance :" << D3 << endl; return 0; } overloading assignment operator = ------------------------------------------------ #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } void operator=(const Distance &D ) { feet = D.feet; inches = D.inches; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches << endl; } }; int main() { Distance D1(11, 10), D2(5, 11); cout << "First Distance : "; D1.displayDistance(); cout << "Second Distance :"; D2.displayDistance(); // use assignment operator D1 = D2; cout << "First Distance :"; D1.displayDistance(); return 0; }
  • 42. overloading array subscripting [] op -------------------------------------------- The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays. #include <iostream> using namespace std; const int SIZE = 10; class safearay { private: int arr[SIZE]; public: safearay() { register int i; for(i = 0; i < SIZE; i++) { arr[i] = i; } } int &operator[](int i) { if( i > SIZE ) { cout << "Index out of bounds" <<endl; // return first element. return arr[0]; } return arr[i]; } }; int main() { safearay A; cout << "Value of A[2] : " << A[2] <<endl; cout << "Value of A[5] : " << A[5]<<endl; cout << "Value of A[12] : " << A[12]<<endl; return 0; }
  • 43. conversion functions ------------------------ converting from build in type to class type and vica versa 1. build in type to class type 2. class type to build in type 3. one class type to other class type 1. build in type to class type ------------------------------------------ it happens automatically.....using constructors..... ex: converting char* to String type ------------------------------------ String::String(char *p){ len=strlen(p); a=new char[len+1]; strcpy(a,p); } 2. class type to build in type ----------------------------------------------- for class to basic type we need conversion function Sy: operator typename(){ } imp conditions: -------------- 1. casting function must be member of class,friend is not allowed 2. it should not mention return type although it return type 3. it should not have any arguments ex: String ::operator char*(){ return p; }
  • 44. 3. one class type to other class type --------------------------------------------- two techniques ---------------- 1. using const 2. usign conversion fun.... depends on wheter to keep conversion logic in source class or destination class Ex: consider two classes ------------------ Inventory1 Inventory2 ----------------- ------------- int codeNo int code int noOfItem float value float unitPrice Now logically noOfItem * unitPrice=value So considerting Inventory1 as source class and Inventory2 as destination class Source class Destination class Inventory1 Inventory2
  • 45. ----------------- ------------- int codeNo int code int noOfItem float value float unitPrice casting operator convrsion constructor #include <iostream> using namespace std; class Inventory2;//forward decleration class Inventory1 { private: int codeNo; int noOfItem; float unitPrice; public: Inventory1(){} Inventory1(int c,int n,float up){ codeNo=c; noOfItem=n; unitPrice=up; } void show(){ cout<<"code no:"<<codeNo<<endl; cout<<"no of items:"<<noOfItem<<endl; cout<<"unit price:"<<unitPrice<<endl; } int getCodeNo(){return codeNo;} int getNoOfItem(){return noOfItem;} float getUnitPrice(){return unitPrice;} //conversion funtion in inventroy /*operator Inventory2(){ Inventory2 temp; temp.code=codeNo; temp.value=noOfItem*unitPrice; return temp; } */ //conversion funtion to get total value of stock operator float(){ return unitPrice*noOfItem; } }; class Inventory2 { private:
  • 46. int code; float value; public: Inventory2(){} Inventory2(int c,float v){ code=c; value=v; } void show(){ cout<<"code:"<<code<<endl; cout<<"Total Stock value:"<<value<<endl; } //conversion constructor in inventroy2 Inventory2(Inventory1 i){ code=i.getCodeNo(); value=i.getNoOfItem()*i.getUnitPrice(); } }; int main() { Inventory1 iv1(22,3,560); Inventory2 iv2; iv2=iv1; float val=iv1; iv2.show(); return 0; } Ex: String class with conversion fun to 1. convert string to char* 2. fun to give length of string #include <iostream> #include<cstring> using namespace std; class String { char *p; int len; public: String(){} String(char *temp){ len=strlen(temp); p=new char[len+1]; }
  • 47. void show(){ cout<<"string is:"<<p<<endl; } operator int(){ return strlen(p); } operator char*(){ return p; } }; int main() { String s("india"); int len=s; char *t=s; return 0; } ------------------------------ Problem with copy constructor : will discuss latter ------------------------------------------------------------- Day-3 ========================================================================== type of relationship bw objects Compostion, aggrigation, Inheritance Inheritance type of inheritance Access Modifiers Access and Inheritance Constructors and Inheritance Scope Resolution operator Multiple & Multilevel Inheritance Calling base class constructor Overriding base class members Virtual functions and Polymorphism Virtual & non-virtual Overriding Virtual functions Rules for virtual functions Pure virtual functions Static and Dynamic Binding
  • 48. Virtual base classes virtual destructor Reusing classes, compostion ---------------------------- 3 type of relationship in OO worlds: 1. USE-A 2. HAS-A implemented using composition and aggrigation 3. IS-A implemented using inheritance Implementing composition -------------------------- composition; ---------------- Strong relation bw two object if Employee is destroyed then Address also destroyed Employee <>-------Address Room<>-----------wall ex: --------- Person has a date of birth ------ #include <iostream> #include<string> using namespace std; class Date { int day,month, year;
  • 49. public: Date(){} Date(int day, int month, int year){ this->day=day; this->month=month; this->year=year; } void showDate(){ cout<<day<<" : "<<month<<" :" <<year<<endl; } }; class Person { string name; Date date; public: Person(string x, Date d); void showPersonDetails(); }; //must use member initilizer list.......... Person::Person(string x, Date d):name(x),date(d) { } void Person::showPersonDetails(){ cout<<"name :"<<name; date.showDate(); } int main() { Date d(22,11,2011); Person p1("foo",d); p1.showPersonDetails(); return 0; } Inheritance =========== Concept of base class and derived class..... resuability of code using IS-A relationship ex: Cat is-a Animal Employee IS-A Person reverse is not true type of inheritance ---------------------
  • 50. 1. single 2. multiple 3. multilevel 4. hierarchical inheritance 1. single ------------- keywork used : class B{ private; int id; public: int j; void showB(){.......} }; class D :public B{ //now class D inherit j and showB() from class B } visibility modifier ---------------------- private<protected<public private: ------- never inherited can be accessed using public methods protected: -------- can be assess in derived class cant access outside the class (Almost equal of default of java !!! ) public: -------- inherited can be access outside the class Inheritance mode ------------------- private: ------- private data: Never inherited protected data: become private
  • 51. public data: become private protected: -------- private data: Never inherited protected data: remain protected public data: become protected public: -------- private data: Never inherited protected data: remain protected public data: remain public ex: -------- #include <iostream> #include<string> using namespace std; class Person { string name; public: Person(){} Person(string name){this->name=name;} void showPerson(){ cout<<"Name of person:"<<name<<endl; } }; class Employee: public Person { string jobNature; public: Employee(){} Employee(string n, string jobNature):Person(n) { this->jobNature=jobNature; } void showEmployee(){ showPerson(); cout<<"Job nature:"<<jobNature<<endl; } }; int main() { Employee e("foo","SW developer"); e.showEmployee(); return 0; }
  • 52. Notic: ---------- how values for instance variable passes from derived ctor to base ctor Order of execution of constructor -------------------------------- base class then derived class Ex; Multiple inheritance ----------------------- Person | Employee | PartTimeEmployee Note: opportunity for debugg...... ------------------------------ #include <iostream> #include<string> using namespace std; class Person { string name; public: Person(){} Person(string name){this->name=name;} void showPerson(){ cout<<"Name of person:"<<name<<endl; } }; class Employee: public Person { string jobNature; public: Employee(){} Employee(string n, string jobNature):Person(n) { this->jobNature=jobNature; } void showEmployee(){ showPerson(); cout<<"Job nature:"<<jobNature<<endl; } }; class PartTimeEmployee: public Employee { double perHour; public: PartTimeEmployee(){} PartTimeEmployee(double perHour, string n, string
  • 53. jobNature):Employee(n, jobNature) { this->perHour=perHour; } void PartTimeEmployee(){ showEmployee(); cout<<"Per hr earning:"<<perHour<<endl; } }; int main() { PartTimeEmployee e(223333,"foo","SW developer"); e.PartTimeEmployee(); return 0; } Multiple Inheritance ---------------------- Not there in Java !!! Can leads to poor sw design; diamond problem? ClassB ClassD1 ClassD2 ClassD3 classC inherit both from ClassA and ClassB #include <iostream> #include<string> using namespace std; class ClassB { public: int i; }; class ClassD1:public ClassB { public: int j; }; class ClassD2:public ClassB { public: int k; }; class ClassD3:public ClassD1, ClassD2 {
  • 54. public: int product(){ return i*j*k; } }; int main() { ClassD3 ob; ob.i=2; ob.j=3; ob.k=4; cout<<ob.product(); return 0; } problem: ------------ which i? solution in C++ ----------------- put virtual keywork before .... class ClassD1:virtual public ClassB { public: int j; }; class ClassD2:virtual public ClassB { public: int k; }; abstract class ------------- aka ADT in C++ when to declare an class abstract ? when we dont have symantically valid body of an method Ex; if i ask you what is the area of a Figure whose length =2 and width=3 ? Ans 6 ? But what is the shape of figure........
  • 55. So we dont have answer till somebody dont specify kind of figure wheter it is Rectangle or Tringle? How to declare abostract class in C++ ----------------------------------- class Figure{ public: virtual void showArea()=0; } Note: ------- it is error to create object of abstract class , you can create reference of that Ex: class Figure { public: virtual void showArea()=0; }; int main() { //Figure f; compile time error Figure *f;// ok } Polymorphism ------------- many form of an funtion Polymorphism compile time Run time Op overloading Overriding........ function over.. #include <iostream> #include<string> using namespace std; class A {
  • 56. public: void fun(){ cout<<"fun of class A"<<endl; } }; class B :public A { public: void fun(){ cout<<"fun of class B"<<endl; } }; int main() { A *a=new B(); a->fun(); } Run time polymorphism ---------------------- requirment: ------------- Base class pointer must assigned drived class object A *a=new B(); still no run time polymorphism? ----------------------------- Dont forget to apply virtual to base function virtual void fun(){ cout<<"fun of class A"<<endl; } More example: ---------- Media #include <iostream> #include<string> #include<cstring> using namespace std; class Media { protected: char title[20];
  • 57. float price; public: Media(){} Media(char t[],float price){ strcpy(title,t); this->price=price; } virtual void display()=0;//dont know more stuff so make it abstract........... }; class Book :public Media { int pages; public: Book(){} Book(int pages, char t[],float price):Media(t, price){ this->pages=pages; } void display(){ cout<<"Title:"<<title<<endl; cout<<"Price:"<<price<<endl; cout<<"No of pages:"<<pages<<endl; } }; class Tap :public Media { int play_time; public: Tap(){} Tap(int play_time, char t[],float price):Media(t, price){ this->play_time=play_time; } void display(){ cout<<"Title:"<<title<<endl; cout<<"Price:"<<price<<endl; cout<<"Play time:"<<play_time<<endl; } }; int main() { Book b(111, "C++ in action",2223.5); Media *m=&b; m.display(); return 0; }
  • 58. Need of virtual destructor ----------------------------- Constructor cant be virtual but we need to have virtual destructor in some of cases.... consider : ----------------------------- #include <iostream> #include<string> using namespace std; class B{ char *bp; public: B(){ bp=new char[5]; cout<<"B allocate 5 bytes"<<endl; } ~B(){ delete []bp; cout<<"B De-allocate 5 bytes"<<endl; } }; class D:public B{ char *dp; public: D(){ dp=new char[500]; cout<<"D allocate 500 bytes"<<endl; } ~D(){ delete []dp; cout<<"D De-allocate 500 bytes"<<endl; } }; int main() { B *p=new D(); delete p; return 0; } OP
  • 59. ------- indicate that memory allocated by D's constructor is not freeed why? ------- the problem is that B's Constructor is not virtual , which means that system bind p at compile time rather then run time.... because p is of type B , p is bound to B's data member and method including constructor and destructor rather then D's data member and methods solution: ------------ declare base constructor as virtual....... virtual ~B(){ delete []bp; cout<<"B De-allocate 5 bytes"<<endl; } ================================================================== some imp discussion ========================================================== c++ automatically generated functions ---------------------------------------- 1. Default constructor 2. copy constructor 3. Assignment operator overloaded 4. Destructor even if we dont write these function thery are generated by default by c++ Ex: class A{ } A a1;//default const A a2=a1// copy const... A a3; a3=a2;// assignment op
  • 60. Actually we write ------------------ class A{ }; C++ convert it to ---------------- class A{ public: A(){} A(const A& t){} A& operator=(const A& temp){} ~A(){} }; Now consider: --------------- class A{ private: int x,y; }; What c++ does? ----------------- c++ does code gereration..... class A{ private: int x,y; public: A(){} A(const A& t){x=t.x;y=t.y} A& operator=(const A& temp){ if(this!=temp){ x=temp.x; y=temp.y;
  • 61. } return *this; } ~A(){} }; C++ do not provoide default constructor if we provide our own default or parameterized ctor. Ex: All following call default const A obj1; A obj1=new A; A obj1=new A(); A *p=new A[100];// create array of 100 A's object ctor called 100 times....... Ex: class A{ A(int t){} } All following will give compilation error ........... A obj1; A obj1=new A; A obj1=new A(); A *p=new A[100];// create array of 100 A's object ctor called 100 times....... perfer new and delete in C++ rather then malloc and free -------------------------------------------------- Never use malloc/free in case of class in c++ Ex: A *p=new A[5];
  • 62. Will create array of 5 A's object Note new ensure that constructor being called for each 5 object object are initilized.... But: ----- A *p=(A*)malloc(5*sizeof(A)); Just allocated memory chunk required for 5 A's object but do not call constructor hence must not be treated as object........... What to do while deleting memory of array of object -------------------------------------------------- A *p=new A[5]; delete p; //Wrong....... only delete memory occupied by A[0] object correct way: -------------- delete []p; Virtual destructor in base class and its need? ------------------------------------------ in case of polymorphism , if we are using pointer of base class to point to derived object then dont forget to make destructor of base class as virtual otherwise memory leak can occour.......... Ex: class Shape { public: virtual void showShape(){}=0; shape(){ cout<<"calling base constructor"<<endl; } ~shape(){ cout<<"calling base de-structor"<<endl; } }; class Circle:public Shape
  • 63. { int *radius; public: virtual void showShape(){ cout<<"are of circle is"<<*radius*radius*3.14<<endl; } shape(){ cout<<"calling base constructor"<<endl; } ~shape(){ cout<<"calling base de-structor"<<endl; delete radius; } }; ........ ....... { Shape *p=new Circle(); p->showShape(); } when scope of code finished only destructor of base class is called..... static binding....... leads to memroy leak.... Make base class destructor virtual so that it its decided on the basis of type of object rather then type of pointer. How to create a class non copyable ----------------------------------- ie what if we do not want to support ; A a1=a2;// copy constructor and a3=a2;// assignment operator What to do? ===============
  • 64. Dont write copy constructor and assignement operator ? but C++ automatically generate code........ Simple solution? ------------------ make both copy ctor and assignment op overloading implementation private....... so that cant be called form main. class A{ private: A(const A& t){x=t.x;y=t.y} A& operator=(const A& temp){ if(this!=temp){ x=temp.x; y=temp.y; } return *this; } public: A(){} ~A(){} }; A a1=a2;// copy constructor and a3=a2;// assignment operator Singlton design pattern: -------------------------------- what if i want to allow programmer to create object of an class......... make an privte constructor class A{ private: A(){} } What if i want to have a class whose object cant be created but want to
  • 65. allow subclassing.........? class A{ private: A(const A& t){x=t.x;y=t.y} A& operator=(const A& temp){ if(this!=temp){ x=temp.x; y=temp.y; } return *this; } protected: A(){} ~A(){} }; class B:private A{} copy constructor : deep copy vs shallow copy --------------------------------------------------- what should happen during copying process the data of the class must be copied on seperate memory localtion for another object ie. let say i have define an class as:---- class Myclass{ int a; double b; string s; };
  • 66. what c++ does using code generation: ----------------------------------- class Myclass{ int a; double b; string s; public: MyClass(const MyClass &m):a(m.a), b(m.b), s(m.s) {} //overloaded assignment operaotr //default ctor //default destructor }; default copy const is ok in this case. Now consider: --------- class Myclass{ int *p; double b; string s; public: MyClass(const MyClass &m):a(m.a), b(m.b), s(m.s) {} //overloaded assignment operaotr //default ctor //default destructor }; Problem is that if MyClass container pointer to some other object / primitive data then rather then creating different memory ...it just assign pointer so an serious problem can occour.........
  • 67. WE SHOULD NOT COPY POINTERS RATHER COPY WHAT IS POINTED TO BY POINTER........ If one destructor for one object is called it will corrupt shared data of other object....... Dangling pointer issue ----------------------------- default copy const is ok in this case. So never relies on default copy const we need deep copy? --------------------- Eg: class MyArray{ public: int size; int *data; explicit MyArray(int s):size(s), data(new int[s]) {} ~MyArray(){ delete []data;} } C++ provide its own copy constructor as follows: MyArray::MyArray(MyArray& temp):size(temp.size), data(temp.data) {} int main(){ MyArray a(20); a.data[0]=5; //define an scope { MyArray b=a; cout<<a.data[0]<<b.data[0]; } // b local variable is removed... a.data[0]=12;//segmentation fault...... }
  • 68. size would be different for two object but *data is shared......... Solution: ========= rather then this ====================== MyArray::MyArray(MyArray& temp):size(temp.size), data(temp.data) {} Use this =========== MyArray::MyArray(MyArray& temp):size(temp.size), data(new int[temp.size]) {} Memory leak and dangling pointer ----------------------------------- if you are a C++ developer you are not so lucky as Java developers We dont have garbage collector We should care about memeory related issue more then java developers Now will discuss some basic idea of memory leak and dangaling pointer Memory leak --------------- consider int *p,*q; p=new int;//dynamically allocated memory q=p; ..... ...... delete(p); //forget to delete q q is still pointing to invalid memory..... =>POINTER q CONTAIN ADDRESS OF MEMORY LOCATION THAT DO NOT EXIST =>A reference to a memory object that do not exists is called "dangling pointer"
  • 69. now we say int *r=new int; let r is assigned same memory that is earlier pointed by p now conceptually both r and q pointing to that newly allocated memory =>Possibility that r data can be mismanupulated by using pointer q good programming practice -------------------- p=new int;//dynamically allocated memory q=p; ..... ...... delete(p); q=NULL;//dont forget Memory leak ========= memory block exist taht do not have valid reference to it Ex: int *p,*q; p=new int; q=new int; now if we do: p=q; then the memory location pointed by pointer p cant be referenced =>memory leak. Day-4 ========================================================================== Templates need of templates, hello world function Template class Template Exception Handling Templates Function templates Class templates Exception handling
  • 70. Templates ============== Need? ------ let we need to have an adder that can add 2 int, float ,double whatever we pass? int adder(int i, int j){ return i+j; } double adder(double i, double j){ return i+j; } Same algo only data type changes? go for function Template ........ ========================== template <class T> T adder(T i, T j){ return i+j; } function template with multiple parameters --------------------------------------- template <class T1,class T2> void printMe(T1 t1, T2 t2) { cout<<t1<<endl; cout<<t2<<endl; } int main() { printMe("foo",121); }
  • 71. class Template ------------------ #include <iostream> #include<string> using namespace std; template <class T> class Adder { T first, second; public: Adder(T a, T b){ first=a; second=b; } T sum(); }; //now most strang syntex c++ template <class T> T Adder<T>::sum(){ return first+ second; } int main() { Adder<int>add(22,22); int temp=add.sum(); cout<<temp; //same for double etc...... return 0; } template specilization ---------------------------- way to make class different implementation with specific one !!! lets we want to handle a particular data type differntly then other one problem...... for ex i want to have differnt behaviour when char data is used........
  • 72. solution -------------- template specilization #include <iostream> using namespace std; template<class T> class Foo{ public: Foo(T t){ cout<<"for all data except char"<<endl; } }; template<> class Foo<char>{ public: Foo(char t){ cout<<"for char"<<endl; } }; int main() { Foo<int> ob1(2); Foo<float>ob2(4.6); Foo<char>ob3('c'); return 0; } Exception Handling ---------------------- exception handling is unusual condition (such as errors) that can cause proram to misbehaves /terminate Exceptions Synchronous Asynch out of range keyboard error overflow etc
  • 73. to handling error during program running..... All exception happens at run time keywords --------- try catch throw Note: No finally or throws as in Java put risky code inside try -------------------------- Ex: #include <iostream> using namespace std; int main() { int income=78; int expence=90; try{ if(expence>income){ throw 99; //error no } } catch(int i){ cout<<"cant do that"<<endl; } catch(...){ cout<<" do that"<<endl; } return 0; } throwing an exception from an functions ------------------------------------------- #include <iostream> using namespace std; void xFun(int t){ cout<<"inside xFun "<<t<<endl; if( t){ throw 55; } } int main() {
  • 74. try{ xFun(0); xFun(10); } catch(int i){ cout<<"cant do that"<<endl; } catch(...){ cout<<" do that"<<endl; } return 0; } Handling exception thrown by new ----------------------------- in c++ when an allocation fails then new throws an bad_alloc exception we can handle it....... use <new.h> #include <iostream> #include<new> using namespace std; int main() { double *p; do{ try{ p=new double[100000]; } catch(bad_alloc x){ cout<<"allocation error"<<endl; return 1; } cout<<"Allocation is ok"<<endl; }while(p); return 0; } smart pointer =============== smart pointer helps solving problem associated with pointer Consider exception safe code:
  • 75. ------------------------------- MyClass *ptr; ptr=new MyClass(); ptr->doFooWork(); delete ptr; Now what some bug is there in doFooWork() and we dont get chance for execution of delete ptr; statement memory leak..... Now we can improve the code as: MyClass *p; try{ ptr=new MyClass(); ptr->doFooWork(); } catch(...){ delete ptr; } Now its guranteed that wheter doFooWork(); work sucessfully or not delete ptr; always execute...... but now everytime we are allocating dynamically we need to use try catch........ :( template<class T> class auto_ptr { T *ptr; public: explicit auto_ptr(T *t=NULL):ptr(p){} ~auto_ptr(){delete ptr;} T& operator* (){return *ptr;}//help in dereferencing ptr T& operator-> (){return ptr;}//help in referencing ptr //Some more code...... }; Now rather then; ----------------
  • 76. ptr=new MyClass(); ptr->doFooWork(); delete ptr; we use someting like: ------------------------ auto_ptr <MyClass>p (new MyClass());//automatic variable that is always for scope p->doFooWork(); how it should work ( Dont forget dry run !!!) ---------------------------------------------- auto_ptr <MyClass>p (new MyClass());//automatic variable that is always for scope when object goes out of scope ..destructor of auto_ptr class invoked Issue of ensureing deleting dynamically allocated memory is solved.......... Dont need unnessary try....catch. C Macros vs C++ template -------------------------- Dont use c macro for implementation of gernalized logic in c++ C++ template prove to be more superiour in most of the cases..... Ex: #define MAX(a,b) fun((a)>(b)?(a):(b)) Now we have unpredictable behabiour in following case:
  • 77. ----------------------------------------------- int i=10; int j=5; method call MAX(++i, j)// i incremented twice method call MAX(++i,j+10)// i incremented once What is better approach: ------------------------- use template: 1. provide predictable code 2. type sale...... template <T t> inline void MAX(const T&a, const T&b){ fun(a>b?a:b); } 1. no need of () 2. inline is same efficient as macro Day-5 ========================================================================== STL Std template Libarary..... Readymade DS in C++ STL container algorithm iterator how to hold object act on container how to move back/forth vector initilization pointer Queue sorting cycle through list searching content of container transforming Input OP Random Bidirectional Forward Associative container -------------------- Efficient retrival on basis of key Ex: Map
  • 78. Container classes ------------- bitset : set of bits <bitset> deque : a double ended queue <deque> list : linear list map : key value only by value <map> multimap: multiset: priority_queue queue set stack vector Day-6 ================================================================================ ================ File IO RTTI