Professional Documents
Culture Documents
=================================================
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
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;
}
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....
swap(&i, &j);
......print after the swap.
}
return y;
}
main(){
...........
..............
max(a,b)=-1//
.........
}
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
C++ operators
--------------------list of operator not in C
::
::*
->*
.*
<<
insertion operator
>>
extractor
new
setw
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
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
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
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();
}
#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;
}
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
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
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;
}
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();
}
that is
{
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;
}
}
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;
}
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){}
};
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;
}
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;
}
#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();
}
};
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.
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.
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.
.,.*
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;
}
class Distance
{
private:
int feet;
int inches;
// 0 to infinite
// 0 to 12
......
.......
}
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.
2.
3.
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
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;
}
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
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:
-------private data:
become private
Never inherited
become protected
public:
-------private data:
Never inherited
ex:
-------#include <iostream>
#include<string>
remain public
-----------------------------#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
ClassD2
ClassD3
problem:
-----------which i?
solution in C++
----------------put virtual keywork before ....
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(){
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;
}
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.
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(){}
};
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;
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.
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.........
Eg:
class MyArray{
public:
int size;
int *data;
explicit MyArray(int s):size(s), data(new int[s])
{}
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......
}
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.....
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
......
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;
}
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
keywords
--------try
catch
throw
Note: No finally or throws as in Java
xFun(0);
xFun(10);
}
catch(int i){
cout<<"cant do that"<<endl;
}
catch(...){
cout<<" do that"<<endl;
}
return 0;
}
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
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......
};
fun((a)>(b)?(a):(b))
STL
container
algorithm
iterator
act on container
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 :
deque
list
linear list
map
<deque>
multimap:
multiset:
priority_queue
queue
set
stack
vector
Day-6
================================================================================
================
File IO
RTTI