Você está na página 1de 84

Advance C++

=================================================
Session-1:
Intro to oo programming
MinGW compiler and basic commands
Configuration codeblock IDE/Eclipse IDE
Procedural stuff
Additional feature of C++ not in C
Session-2:
class and object
c++ advance stuff
1. dont return address of local variable from an method.
Session-3:
Function and Operator Overloading

Session-4:
inheritance,compostion and Polymorphism
c++ advance stuff
1. understanding c++ automatically generated functions:default c
tor,
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

Session-5:
Templates, Exception Handling
c++ advance stuff
Smart pointer: need and implementation
C Macros vs C++ template
Session-6:
STL

Session-7:
File IO, RTTI
Session-8:
Memory mgt in C++
Session-9:
Database programming
Session-9 and 10:
Project Work
MCQ test.

=======================================================================
Session-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 inte
ger
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

================================================================================
=====================
Session-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 met
hod
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 to
pic
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 in
itialization 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 show
2()
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 o
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 c
lass.(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 m

3.

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

4.

if multiple match found then


compile time error !!!

atch

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<<" )"<<en
dl;
}
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;
int inches;

// 0 to infinite
// 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++ arr
ays.
#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
----------------int codeNo
int noOfItem
float unitPrice

Inventory2
------------int code
float value

Now logically noOfItem * unitPrice=value


So considerting Inventory1 as source class and Inventory2 as destination
class

Source class

Destination class

Inventory1
----------------int codeNo
int noOfItem
float unitPrice

Inventory2
------------int code
float value

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

USE-A
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.
2.
3.
4.

single
multiple
multilevel
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:

protected:
-------private data:

become private

Never inherited

protected data: remain protected


public data:

become protected

public:
-------private data:

Never inherited

protected data: remain protected


public data:

ex:
-------#include <iostream>
#include<string>

remain public

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):Emp
loyee(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
Op overloading
function over..

Run time
Overriding........

#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 abstr
act...........
};
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 sy
stem
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 includ
ing
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 co
nstructor
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 o
f 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 bo
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 / prim
itive 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 o
f 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
overflow etc

keyboard error

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
Queue
list

initilization
sorting
searching

pointer
cycle through
content of container

transforming
Input
Bidirectional

OP

Random

Forward

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

Container classes
------------bitset :

set of bits <bitset>

deque

a double ended queue

list

linear list

map

key value only by value <map>

<deque>

multimap:
multiset:
priority_queue
queue
set
stack
vector

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

File IO
RTTI

Você também pode gostar