Advance C++notes

  • 942 views
Uploaded on

Concise to the point notes C++

Concise to the point notes C++

More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
942
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
1
Comments
0
Likes
3

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 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 CDay-2: class and object c++ advance stuff 1. dont return address of local variable from an method.Day-3: Function and Operator OverloadingDay-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 pointerDay-5: Templates, Exception Handling c++ advance stuff Smart pointer: need and implementation C Macros vs C++ templateDay-6: STLDay-7: File IO, RTTIDay-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 compilerHello World----------------#include <iostream>using namespace std;int main(){ cout<<"Hello world"<<endl; return 0;} Command to compile; ------------------ g++ -o Hello Hello.cppOOPs 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 arrayAdditional 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 unionuse 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;//compileNote: 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 asinteger 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 alieasif we change total num will be changed....Why to use reference?-----------------------------1. easy to use then pointer2. can used to produce effect of call by reference (swap the values)3. C dont support call by reference it support call by pointerEx: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 iscall 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 cant 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 isgreater............. } 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 fromheap 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 seperatorStruts of C++------------- no technical difference data is private by default.Union of C++-----------------
  • 8. annonymous union=====================================================================================================Day-2class and object=====================================================================================================Defining a classCreating an objectObject ScopeData AbstractionEnforcing Data Encapsulation‘this‘ PointerDefining member functionsDynamic creation of objectsConstructors and Destructors The Default Constructor The Destructor Parameterized Constructors Copy constructor Constructor initializersSome misc topics: random no generation sizeof operator const keywordMultifile program in C++Static static data static methodsReturning objectsArrays of ObjectsMethods and access modifiersAccessing class data and methods
  • 9. Friend class and friendly functionsDefining 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 notsuitable 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 cant refer to there addresss..... 6. Constructor can be overloaded but cant be overriden* 7. Cant inherit.... reference in c++ ------------------- Now after undestanding basic of reference in C++ come back on pendingtopic ie copy constructor
  • 17. copy constructor------------------------ http://www.codeproject.com/Tips/78946/C-Copy-Constructor-in-depthdefault 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 indetail) 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 refferedagain....... 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 theclass 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 deleteRemember;========= 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 10using 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 10using 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 copyEx:#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 constructorinitialization list also.
  • 26. This is just another way to initializeExample: 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 keywordrandom 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 Javacant be change once assigned......1. const on variable2. const on object2. const on method3. const on method arguments1. 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 objectwith 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 chagewe 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_HStatic
  • 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 variablesEx:#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 10using namespace std;class Meter;//forward declerationclass 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 10using 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 thisclass.(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 overloadingDay-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 typeFunction 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 operator4. conditional operatorSy:return type className::operator op(arg list){ fuction body}Rules:---1. Only existing operator can be overloaded2. overloaded operator must have at least one user define operand3. 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 classclass 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 destinationclass 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 declerationclass 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, InheritanceInheritance type of inheritance Access Modifiers Access and Inheritance Constructors and Inheritance Scope Resolution operator Multiple & Multilevel Inheritance Calling base class constructor Overriding base class membersVirtual 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 destructorReusing 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 inheritanceImplementing composition-------------------------- composition; ---------------- Strong relation bw two object if Employee is destroyed then Address also destroyed Employee <>-------Address Room<>-----------wallex:--------- 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 truetype of inheritance---------------------
  • 50. 1. single 2. multiple 3. multilevel 4. hierarchical inheritance1. 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 classInheritance 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 publicex:--------#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 classEx;Multiple inheritance----------------------- Person | Employee | PartTimeEmployeeNote: 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 createreference 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 itabstract...........};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 Ds constructor is not freeed why? ------- the problem is that Bs Constructor is not virtual , which means thatsystem bind p at compile time rather then run time.... because p is of type B , p is bound to Bs data member and methodincluding constructor and destructor rather then Ds 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. Destructoreven 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 owndefault or parameterized ctor.Ex:All following call default constA obj1;A obj1=new A;A obj1=new A();A *p=new A[100];// create array of 100 As 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 As 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 As 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 As object but do not callconstructor 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 oftype 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 implementationprivate.......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 constructoranda3=a2;// assignment operatorSinglton design pattern:--------------------------------what if i want to allow programmer to create objectof an class.........make an privte constructorclass 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 ofother 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 pointerMemory 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 "danglingpointer"
  • 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 forgetMemory 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 wepass? 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 chancefor execution of delete ptr; statementmemory 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 notdelete ptr; always execute......but now everytime we are allocating dynamicallywe 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 isalways for scope p->doFooWork(); how it should work ( Dont forget dry run !!!) ---------------------------------------------- auto_ptr <MyClass>p (new MyClass());//automatic variable that is alwaysfor scope when object goes out of scope ..destructor of auto_ptr class invoked Issue of ensureing deleting dynamically allocated memory issolved.......... 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 macroDay-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 vectorDay-6================================================================================================ File IO RTTI