of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm...

61
C++ C++ Dr. Binu P Chacko Associate Professor Department of Computer Science Department of Computer Science Prajyoti Niketan College, Pudukkad, THRISSUR

Transcript of of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm...

Page 1: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

C++C++

Dr. Binu P ChackoAssociate Professor

Department of Computer ScienceDepartment of Computer SciencePrajyoti Niketan College, Pudukkad, THRISSUR

Page 2: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

FundamentalsFundamentals • OOP language developed by Bjarne Stroustrup at AT & T Bell 

L b t i i l 1980’Laboratories in early 1980’s• Features: classes, inheritance, function overloading, operator 

overloading• Bottom up object oriented design• Bottom‐up object‐oriented design• Comments: // or /*….*/• #include<iostream> ‐ for I/O statements

t<<“i ti ( t t ) t ”• cout<<“insertion (put to) operator”;int main(){ float n1, n2, avg;

“E b “cout<<“Enter two numbers : “;cin>>n1>>n2;avg = (n1 + n2 ) / 2;

\cout<<“\nAverage : “<<avg;return 0; }

Page 3: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…#include<iostream.h>class student{ private:

Include filesClass declaration

{ private:char name[10];int age;

public:public:void read(){  cout<<“Enter name, age”;

cin>>name>>age; }

Member function definition

cin>>name>>age; }void disp(){ cout<<“Name : “<<name;

cout<<“Age : “<<age; }};cout<< Age     :  <<age; }};main(){  student s;

d()

Main function

s.read();s.disp(); }

Page 4: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

TokensTokens 

• Smallest individual units in a programSmallest individual units in a program• Keywords

asm defa lt float operator s itchasmautoboolbreak

defaultdeletedodouble

floatforfriendgoto

operatorprivateprotectedpublic

switchtemplatethisthrow

casecatchcharclass

dynamic_castelseenumexplicit

ifinlineintlong

registerreinterpret_castreturnshort

truetrytypedeftypeidclass

constconst_castcontinue

explicitexportexternfalse

longmutablenamespacenew

shortsignedsizeofstatic

typeidtypenameunionunsigned

voidvolatile

wchar_twhile

static_caststruct

usingvirtual

Page 5: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…

• Identifiers: names of variables, ,functions, arrays, classes, etc.

• No limit on the length of the << Insertion operator

>> Extraction operator

:: Scope resolution operatorname• Constants: wchar_t (wild character) type used for

:: Scope resolution operator

::* Pointer to member declarator

‐>* Pointer to member operatorcharacter) type used for character sets that cannot fit a character into a single byte. E g L’ab’

.* Pointer to member operator

delete Memory release operator

endl Line feed operatorE.g. L’ab’• Strings• Operators

p

new Memory allocation operator

setw Filed width operator

• Operators

Page 6: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Data TypesData Types• Basic data types: char, int, float, double• long, short, signed, unsigned• User defined data types: structures, classes, enumerated data type• Derived data type: arrays, functions, pointers• Symbolic constants: created using const and enum• Reference variable provides an alias (alternative name) for a 

previously defined variablefloat total = 100;float & sum = total; reference to floatchar & a = ‘\n’;int & n = 50; main()

{ i t 10 void f(int & x)int *p;int & m = *p;• A reference variable must be initialized at the time of declaration

{   int m = 10;f(m); }

void f(int & x){   x += 10;    }

• If value of one variable is updated, it will also reflect in its alias

Page 7: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

OperatorsOperators • Scope resolution operator (::)int m = 10;main()main(){ int m = 20;

cout<<m;cout<< m global variable }cout<<::m; global variable }

• Memory management operators (new, delete)int *p = new int;fl t *f fl t(12 3)float *f = new float(12.3);char *c = new char[10];delete p;d l []delete []c;• Manipulatorscout<<m<<endl<<n;cout<<setw(5)<<sum;• Type cast operator: avg = sum / float(n);

Page 8: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

• Operator overloading: *, <<, >>• Operators that cannot be overloaded: ?:, ::, ., sizeof, .*

Cont…Operator precedence and associativity

::‐> . () [] postfix ++ postfix ‐‐

f f !

L – RL – R

Prefix ++ prefix ‐‐ ~ ! Unary + unary –unary * unary & (type) sizeof new delete‐> * *•/ %

R – LL – RL – R/

+ ‐<< >><< = >> =

!

L – RL – RL – RL R== !=

&^|

L – RL – RL – RL – R

&&||?:= *= /= %= += =

L – RL – RL – RR L=  = /= %= += ‐=

<<== >>== &= ^= |=,

R – LL ‐ R

Page 9: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Expressions• Constant expression consists of only constant values12 + 5 / 2 512 + 5 / 2.5• Integral expression produces integer resultsm + n * 5• Float expressions produce floating point results• Float expressions produce floating point resultsx + y * 3.2• Pointer expressions produce address valuest 3ptr + 3

• Relational expression: x <= y• Logical expression: a < b && c >= d

d l d b l l (• Bitwise expressions are used to manipulate data at bit level (testing and shifting of bits)

x << 2  left shift 2 bit positionY >> 3 i ht hift 3 bit itiY >> 3 right shift 3 bit positionShift operations are used for multiplication and division by powers of 2• Assignment expressionsCh i d i 10 b d i i i li iChained assignment: x = y = 10;  cannot be used in intializationEmbedded assignment: x = (y = 50) + 10;Compound assignment: x += 10;

Page 10: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Implicit ConversionImplicit ConversionRHO Char Short Int Long Float Double Long 

LHO double

CharShortI t

IntIntI t

IntIntI t

IntIntI t

LongLongL

FloatFloatFl t

“““

“““Int

LongFloatDouble

IntLongFloatDouble

IntLongFloatdouble

IntLongFloatdouble

LongLongFloatdouble

FloatFloatFloatdouble

““““

““““

Long double

Long double

Long double

Long double

Long double

Long double

Long double

Long double

CONTROL STRUCTURESSequence structureSelection structure: if, switchLoop structure: do while while forLoop structure: do‐while, while, for

Page 11: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

FunctionsFunctions • Return by referenceint & max(int &x, int &y){ if (x > y)

return x;else

return y; }• Function returns reference to x or yFunction call:  max(a, b) = ‐1;• Inline function is expanded in line when it is invokedinline double cube(double a)( ){ return(a * a * a); }Function call:  c =  cube(3.5);• All inline functions must be defined before they are calledy

Page 12: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…• Default parametersfloat amount(float principal, int period, float rate = 0.15);( p p , p , );value = amount(5000, 7);value = amount(5000, 5, 0.12);• Constant argumentsConstant argumentsint length(const char *p);• Function should not modify the argument

Math library functions

ceil(x) ceil(8.1) = 9.0, ceil(‐8.8) = ‐8.0

cos(x) tan(x)( ) ( )

exp(x) log10(x)

fabs(x) pow(x, y)

fl ( ) fl (8 2) 8 0 fl ( 8 8) 9 0floor(x) floor(8.2) = 8.0, floor(‐8.8) = ‐9.0

sin(x) sqrt(x)

log(x) Natural logarithm of x

Page 13: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Function overloadingFunction overloading#include<iostream.h>

()void main(){ int volume(int);

double volume(double, int);long volume(int int int);long volume(int, int, int);cout<<volume(10)<<endl;cout<<volume(2.5, 8)<<endl;cout<<volume(100 75 15)<<endl; }cout<<volume(100, 75, 15)<<endl; }

int volume(int s) cube{ return(s * s * s); }double volume(double r, int h) cylinder( , ) y{ return(3.14 * r * r * h); }long volume(int l, int b, int h) rectangular box{ return(l * b * h); }

Page 14: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Classes and Objects class itemClasses and Objectsclass item{ private:

{ private:int code;float price;

public:int code;float price;

public:()

public:coid read();void display();  };

void item::read()void read(){ cin>>code>>price; }void display(){ cout<<code<<price; }} x y;

{   cin>>code>>price;   }void item::display(){   cout<<code<<price;  }};item a;{ cout<<code<<price; }} x, y;

item z;x.read(); x.display();• A way to bind data and its associated functions together (encapsulation)

item a;a.read();a.display();

A way to bind data and its associated functions together (encapsulation)• Class declaration describes the type and scope of its members• It allows data (and functions) hiding• define a class – create a new abstract data typeyp• Add inline in the header line of function definition to make it as inline 

funciton

Page 15: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…• A member function calls another member function• Private member function• Arrays within a class• Memory allocation for objects• Static member variable (class variable): initializes to 0 when the first 

object of its class is created• Shared by all objects of that class• Visible only within the class, but its lifetime is the entire program• Local classes: classes defined and used inside a function• They can access global variables (using ::) and static variables 

d l d i id h f ideclared inside the function• They cannot have static data members• Member functions must be defined inside the class

Page 16: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…class item{ static int count;

int number;public:

void getdata (int a)void getdata (int a){  number = a;count++; }

void getcount ()void getcount (){  cout<<count<<endl; } };

int item::count; int item::count = 35;void main()(){    item a, b;

a.getcount(); b.getcount();a.getdata(50);      b.getdata(60);a.getcount(); b.getcount(); } 

Page 17: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Static Member FunctionStatic Member Function• Access only the static member variables in the same class• Called using class nameclass test{  static int count;public:public:

void setcode(){  ++count; }static void showcount()static void showcount(){  cout<<count<<endl; } };

int test::count;void main()(){    test t1, t2;

t1.setcode(); t2.setcode();test::showcount(); }

Page 18: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Array of ObjectsArray of Objectsclass employee{   char name[10];

int age;public:

void read()void read(){  cin>>name>>age; }void disp(){ cout<<name<<age; } };{  cout<<name<<age; } };

void main(){   employee manager[5];

int i;;for (i = 0; i < 5; ++i)

manager[i].read();for (i = 0; i < 5; ++i)

manager[i].disp(); }

Page 19: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Add TimeAdd Timeclass time{ int hours;

int minutes;blipublic:void settime(int h, int m){  hours = h; minutes = m; }void disptime() const const member functionp (){  cout<<hours<<minutes;}void addtime(time t1, time t2){   minutes = t1.minutes + t2.minutes;

ho rs min tes / 60hours = minutes / 60;minutes %= 60;hours += t1.hours + t2.hours; } };

void main(){ time tm1, tm2, tm3;

tm1.settime(3, 30); tm2.settime(4, 45);tm3.addtime(tm1, tm2);tm1 disptime(); tm2 disptime(); tm3 disptime(); }tm1.disptime(); tm2.disptime(); tm3.disptime(); }

Page 20: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

friend functionfriend functionclass sample{ int a;

int b;public:

void setvalue() { a = 10;  b = 22;  }friend float mean(sample s); }; or declared in private part.

float mean(sample s) Access private member of the{ return((s.a + s.b) / 2.0); } class; Can’t access member void main() directly; Use objects as arguments{ sample X;{ p ;

X.setvalue();cout<<mean(X); } Can’t be called using object

• A function can be declared as a friend in any number of classesy

Page 21: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…• Member function of one class can be friend function of another classclass X{  ……….

int fun1();};………. };

class Y{ ……….

friend int X::fun1();friend int X::fun1();………. };

• All member functions of one class (X) can be friend functions of another class (Z)

class Z{ ………

friend class X;}……… };

Page 22: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…

class ABC; forward declaration;class XYZ{ int x;public:

void max(XYZ m, ABC n){ if (m.x >= n.a)

cout<<m.x;public:void setvalue(int i) { x = i; }friend void max(XYZ, ABC); };

elsecout<<n.a; }

void main(){ ABC abc;

class ABC{ int a;public:

{ ABC abc;abc.setvalue(100);XYZ xyz;xyz.setvalue(200);public:

void setvalue(int i) { a = i; }friend void max(XYZ, ABC); };

max(xyz, abc); }

Page 23: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…class class_2; Call by referenceclass class_1{ int value1;public:

void exchange(class_1 & x,class_2 & y)

{   int temp = x.value1;x value1 = y value2;void indata(int a) { value1 = a; }

void display() { cout<<value1; }friend void exchange(class_1 &, class_2 &);};

x.value1 = y.value2;y.value2 = temp; }

void main(){   class_1 c1;

class class_2{ int value2;public:

class_2 c2;c1.indata(10); c2.indata(20);c1.display(); c2.display();exchange(c1 c2);

void indata(int a) { value2 = a;  }void display() { cout<<value2; }friend void exchange(class_1 &, class_2 &);};

exchange(c1, c2);c1.display(); c2.display();   }

g ( _ , _ );};

Page 24: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

return objectclass complex{ float x; return object{ ;

float y;public:

void input(float real, float img){ x = real;  y = img; }void show(complex c){ cout<<c.x<<“ + i”<<c.y; }f i d l ( l l ) }friend complex sum(complex, complex); };

complex sum(complex c1, complex c2){    complex c3;

c3 x = c1 x + c2 x;c3.x = c1.x + c2.x;c3.y = c1.y + c2.y;return(c3); }

void main()void main(){ complex A, B, C;

A.input(4.5, 6.2); B.input(3.3, 9.1);C = sum(A, B);( , )A.show(A); B.show(B); C.show(C); }

Page 25: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Pointer to memberPointer to memberclass M

void main(){ int x;int y;

public:

void main(){  M n;

Pointer to member functionvoid (M :: *pf)(int, int) = &M :: set_xy;

void set_xy(int a, int b){ x = a; y = b; }friend int sum(M); };

(n.*pf)(5, 35);cout<<sum(n);M *op = &n;(op‐>*pf)(23 74);

int sum(M m){ int M ::* px = &M :: x;

int M ::* py = &M :: y; Pointer to member variable

(op‐> pf)(23, 74);cout<<sum(n); }

py y;M *pm = &m; Pointer to objectint s = m.*px + pm‐>*py;return(s); }( ); }

Page 26: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

ConstructorConstructor • A member function with same name of the class. • Invoked when an object is created; initializes the objectclass integer{ int m, n;public:

()integer(){ m = 0; n = 0; } };

integer int1;• Should be declared under public• Should be declared under public• No return type• Cannot be inherited, virtual, refer its address• Make implicit calls to the operators new and delete when memoryMake implicit calls to the operators new and delete when memory 

allocation is required• An object with a constructor or destructor cannot be used as a member of 

a unionf l I h b f h• Default constructor: no parameters. In the absence of such a constructor, 

compiler will supply a default constructor

Page 27: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Parameterized ConstructorParameterized Constructor• Constructors with argumentsl i tclass integer{  int m, n;public:

integer(int x, int y)g ( , y){ m = x;  n = y; }void display(){  cout<<m<<n; } };

void main()void main(){  integer int1 = integer(100, 0); explicit call

integer int2(10, 40); implicit callint1.display(); int2.display(); }

class A{  ……….public:

A (A); };

class A{  ……….public:

If no copy constructor, compiler suppliesits own copy constructorA (A); };

illegal A (A&); };Copy constructor

its own copy constructor

Page 28: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Overloaded ConstructorOverloaded Constructorclass integer{  int m, n;public:public:

integer(){ m = 0;  n = 0; }integer(int a, int b){ b }{ m = a;  n = b; }integer(integer & i){ m = i.m;  n = i.n; } };

integer i1;g ;integer i2(34, 94);integer i3(i2); or  i3 = i2;Integer i6;i6 i1; doesn’t invoke copy constructor; member by member copyi6 = i1; doesn t invoke copy constructor; member‐by‐member copyConstructor with default argumentsinteger(int a, int b = 0){  m = a;  n = b; }integer i4(45); integer i5(12, 19);

Page 29: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Dynamic initialization of constructorsDynamic initialization of constructors

class fixed_deposit void main(){ fixed deposit fd1 fd2 fd3;{   int p, y;

float rate;public:

fixed deposit() {}

{ fixed_deposit fd1, fd2, fd3;int x, y, z;float w;cin>>x>>y>>z;

fixed_deposit() {}fixed_deposit(int a, int b, float c = 0.11){  p = a; y = b; rate = c; }fixed deposit(int a int b int c)

fd1 = fixed_deposit(x, y, z);cin>>w>>x>>y;fd2 = fixed_deposit(x, y, w);cin>>x>>y;fixed_deposit(int a, int b, int c)

{  p = a, y = b; rate = c; }void display(){  cout<<p<<y<<rate; } };

cin>>x>>y;fd3 = fixed_deposit(x, y);fd1.display();fd2.display();f () }

{ p y ; } };fd3.display(); }

Page 30: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Dynamic ConstructorsDynamic Constructors#include<string.h>class String{ char *name;{  char  name;

int length;public:

String(){ l th 0{  length = 0;name = new char[length + 1]; }

String(char *s){  length = strlen(s);{ g ( );name = new char[length + 1];strcpy(name, s); }

void display(){ cout<<name; } };{  cout<<name; } };

void main(){   char *str = “Robin”;

String s1, s2(str), s3(“Remya”);s2.display(); s3.display(); }

Page 31: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

DestructorDestructor • A member function with the same name of the class• Used to destroy the objects created by a constructor• Invoked by the compiler upon exit from the program (or block or function)int count = 0;class alpha{ bl{ public:

alpha(){  cout<<“No of object created”<<++count;}~alpha() No arguments no return value~alpha() No arguments, no return value{ cout<<“No of object destroyed”<<count‐‐;}};

void main(){ alpha a1 a2 a3;{   alpha a1, a2, a3;

{   alpha a4; }{   alpha a5; } }

• Objects are destroyed in the reverse order of creationj y

Page 32: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Operator OverloadingOperator Overloading• Giving special meaning to an existing operator• Power of extensibility – original meaning is not lost• Semantics of an operator can be extended, bit not the syntax. i.e., number of 

operands precedence and associativity of operators remain the sameoperands, precedence and associativity of operators remain the sameOverloading unary operatorclass unary{ int x;

int y;public:

void read(){ cin>>x>>y; }{ cin>>x>>y; }void display(){ cout<<x<<y; }void operator‐() operator function

Using friend functionDeclarationfriend void operator‐(unary &m);D fi iti{   x = ‐x;   y = ‐y; }};

void main(){ unary um;

um.read(); um.display();

Definitionvoid operator‐(unary &m){   m.x = ‐m.x;    m.y = ‐m.y;    }

um.read();    um.display();‐um;um.display(); }

Page 33: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Binary OperatorBinary Operatorclass complex{ int x;

int y;public:

complex() {}complex() {}complex(int real, int img){ x = real; y = img; }complex operator+(complex c)complex operator+(complex c){ return(complex((x + c.x), (y + c.y)));

complex t;t.x = x + c.x; t.y = y + c.y;

void main(){   complex c1(12, 5), c2(3, 4), c3;

3 1 2; y y y;

return(t); }void display(){ cout<<x<<“ + i“<<y; }};

c3 = c1 + c2;c3 = c1.operator+(c2);c3.display(); }

Page 34: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Using friend FunctionsUsing friend Functionsclass vector{ int v[5];public:

vector(){ for(int i 0; i < 5; ++i){  for(int i = 0; i < 5; ++i)

v[i] = 0; }vector(int *x){ for(int i = 0; i < 5; ++i){  for(int i = 0; i < 5; ++i)

v[i] = x[i]; }Cannot overload =, (), [] and ‐> using friend function

friend vector operator *(int a, vector b);p ( , );friend vector operator *(vector b, int a);friend istream & operator >> (istream &, vector &);friend ostream & operator << (ostream &, vector &); };

Page 35: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Cont…Cont…vector operator * (int a, vector b){ vector c;

for(int i = 0; i < 5; ++i)[i] * b [i]

int x[5] = {23, 41, 5, 90, ‐3};void main(){ vector m;c.v[i] = a * b.v[i];

return(c); }vector operator * (vector b, int a){ vector c;

{   vector m;vector n = x;cin>>m;cout<<m;{ ;

for(int i = 0; i < 5; ++i)c.v[i] = b.v[i] * a;

return(c); }istream & operator >> (istream &din e tor &b)

vector p, q;p = 2 * m;q = n * 3;cout<<p;istream & operator >> (istream &din, vector &b)

{ for(int i = 0; i < 5; ++i)din>>b.v[i];

return(din); }

cout<<p;cout<<q; }

Overloaded operator must have at least one operand of user‐defined typeostream & operator << (ostream &dout, vector &b){ for(int i = 0; i < 5; ++i)

dout<<b v[i];dout<<b.v[i];return(dout); }

Page 36: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

String Manipulationstring operator + (string s){   string t;t.len = len + s.len;t p new char[t len + 1]String Manipulation

class string{ h *

t.p = new char[t.len + 1];strcpy(t.p, p);strcat(t.p, s.p);return(t); }

{ char *p;int len;

public:string()

int operator <= (string s){   int m = strlen(p);int n = strlen(s.p);if (m <= n)g()

{    len = 0;  p = 0; }string(const char *str){ len = strlen(str);

p = new char[len + 1];

if (m <= n)return(1);

elsereturn(0); }

p = new char[len + 1];strcpy(p, str); }

string(const string & s){ len = s.len;

void show(){    puts(p); }};void main(){ string s1 = “Computer “ s2 = “Science”;

p = new char[len + 1];strcpy(p, s.p); }

~string(){ delete p; }

{  string s1    Computer  , s2    Science ;string t1, t2, t3;t1 = s1; t2 = s2;t3 = t1 + t2;

h () 2 h () 3 h (){ delete p; } t1.show();  t2.show();  t3.show();if (t1 <= t2)  cout<<“Smaller”;else cout<<“Larger”; }

Page 37: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Type ConversionType Conversion• Basic to Class typeUsing constructor• Class to Basic typevector::operator int() No parameters and return type{ int sum = 0;

for(int i = 0; i < 5; ++i)sum += v[i];

return(sum); }• operator int() can be used asint s = int(v1); or int s = v1;( ); ;• One class to another class typeConversion using a casting operator in source class or a constructor in 

destination class

Page 38: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Exampleclass invent2class invent1{ int code; Example{ ;

int items;float price;

public:i t1(i t i t b fl t )

class invent2{  int code;float value;

invent1(int a, int b, float c){ code = a;  items = b;  price = c;}void display(){ cout<<code<<items<<price; }

public:invent2(){  code = 0; value = 0; }invent2(invent1 p)

int getcode(){  return(code); }int getitems(){ return(items);}

invent2(invent1 p){  code = p.getcode();value = p.getitems() * p.getprice();}void display()

{  return(items);}float getprice(){  return(price); }operator float()

{  cout<<code<<value; } };void main(){  invent1 s1(23, 5, 6.5);invent2 d1;

{  return(items * price); }operator invent2()   invent1 to invent2{  invent2 t;t code = code;

invent2 d1;float total_value;total_value = s1;d1 = s1;1 di l ()t.code = code;

t.value = price * items;return(t); } };

s1.display();cout<<total_value;d1.display(); }

Page 39: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

InheritanceInheritance • Deriving a new class (derived class or subclass) from an old one 

(b l ) bilit(base class) – reusability• Derived class inherits some or all of the traits from the base class• Single inheritance: A derived class with one base class

l l h d d l h b l• Multiple inheritance: A derived class with many base classes• Hierarchical inheritance: Traits of one class may be inherited by 

more than one classM ltil l i h it D i i l f th d i d l• Multilevel inheritance: Deriving a class from another derived class

• Hybrid inheritanceclass ABC: private XYZ{ b f ABC }

Public members of the base class are accessible withinderived class but not to the objects of derived class{  members of ABC };

class ABC : public XYZ{  members of ABC };

derived class, but not to the objects of derived class

Public members of the base class are accessible to objects of derived class

• Private members are not inherited

Page 40: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Single InheritanceSingle Inheritanceclass B{ i t{ int a;public:

int b;void get_ab() oid main()g _ (){  a = 23;  b = 90;  }int get_a(){  return(a); }void show a()

void main(){  D d;d.get_ab();d.mult();void show_a()

{  cout<<a; } };class D : public B{ int c;

d.show_a();d.display();d,b = 26;d mult();public:

void mult(){  c = b * get_a(); }void display()

d.mult();d.display(); }

void display(){  cout<<get_a()<<b<<c; }};

Page 41: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Privately Derived classPrivately Derived classclass D : private B{ int c;public:void mult(){ get ab();{     get_ab();

c = b * get_a(); }void display(){ cout<<get a()<<b<<c; }};{  cout<<get_a()<<b<<c; }};

void main(){   D d;

d.mult();();d.display(); }

• If both base class and derived class contain a function with same name, then the derived class function supersedes the base class definition

Page 42: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Multilevel InheritanceMultilevel Inheritanceclass student{ t t d

Access specifiers may appear in any order and any number of times in a class

Members declared under protected section are accessible{ protected:int roll_number;

public:void get_number(int a) class result : pubic test

Members declared under protected section are accessible within the class and in the derived class

g _ ( ){  roll_number = a; }void put_number(){  cout<<roll_number;  }};

class test : public student

p{  float total;public:void display(){ total = sub1 + sub2;class test : public student

{ protected:float sub1;float sub2;

{   total = sub1 + sub2;put_number();put_marks();cout<<total; }};

public:void get_marks(float x, float y){  sub1 = x;  sub2 = y; }void put marks()

void main(){  result student1;student1.get_number(101);student1 get marks(79 61);void put_marks()

{  cout<<sub1<<sub2; }};student1.get_marks(79, 61);student1.display(); }

Page 43: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Multiple InheritanceMultiple Inheritanceclass M{ t t d{ protected:

int m;public:

void get_m(int x) void main()g _ ( ){  m = x; }};

class N{ protected:

int n;

{  P p;p.get_m(34);p.get_n(40);p.display(); }int n;

public:void get_n(int y){  n = y; }};

p.display(); }

class P : public M, public N{ public:

void display(){ cout<<m<<n<<m * n; }};{  cout<<m<<n<<m   n; }};

Page 44: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

AmbiguityAmbiguity class M{ bli{ public:

void display(){  cout<<“Class M”; }};

class N

class A{ public:

void display(){ cout<<“A”; }};

{ public:void display(){  cout<<“Class N”; }};

class P : public M public N

{  cout A ; }};class B : public A{ public:

void display(){ t “B” }}class P : public M, public N

{ public:void display(){  M::display(); }}; Solution

{  cout<<“B”; }};void main(){  B b;b.display();

void main(){  P p;p.display(); }

p y()b.A::display();b.B::display(); }

Page 45: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Hybrid Inheritanceclass sports{ protected:

float score;Hybrid Inheritanceclass student{ t t d

float score;public:void get_score(float s){  score = s; }

{ protected:int roll_no;

public:void get_number(int a)

void put_score(){  cout<<score; }};

class result : public test, public sports{ float total;g _ ( )

{  roll_no = a; }void put_number(){  cout<<roll_no; }};

class test : public student

{    float total;public:void display(){ total = part1 + part2 + score;

t b ()class test : public student{ protected:

float part1, part2;public:

put_number();put_marks();put_score();cout<<total; }};

void get_marks(float x, float y){  part1 = x;  part2 = y; }void put_marks(){ cout<<part1<<part2; }};

}}void main(){  result student1;student1.get_number(1380);student1 get marks(83 91);{  cout<<part1<<part2; }}; student1.get_marks(83, 91);student1.get_score(4.6);student1.display(); }

Page 46: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Virtual Base Classclass sports : public virtual student{ protected:

float score;Virtual Base Class float score;public:void get_score(float s){  score = s; }

Duplication of inherited members due to multiple paths can be avoided by making the common base class as virtual base class

class student{ protected:

int roll_no;

void put_score(){  cout<<score; }};

class result : public test, public sports{ float total; One op of st dent ill

common base class as virtual base class

Abstract class

_public:

void get_number(int a){  roll_no = a; }void put number()

{    float total;public:void display(){ total = part1 + part2 + score;

t b ()

One copy of student willbe inherited

void put_number(){  cout<<roll_no; }};

class test : virtual public student{ protected:

put_number();put_marks();put_score();cout<<total; }};

float part1, part2;public:

void get_marks(float x, float y){ part1 = x; part2 = y; }

}}void main(){  result student1;student1.get_number(1380);student1 get marks(83 91);{  part1 = x;  part2 = y; }

void put_marks(){  cout<<part1<<part2; }};

student1.get_marks(83, 91);student1.get_score(4.6);student1.display(); }

Page 47: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Derived class ConstructorDerived class Constructorclass alpha First, constructor beta(b)

is executed{ int x;public:

alpha(int i){ x i; }

class gamma : public beta, public alpha{   int m, n;public:

is executed

{  x = i; }void show_x(){  cout<<x; }};

class beta

public:gamma(int a, float b, int c, int d) :

alpha(a), beta(b){  m = c;  n = d; }id h ()class beta

{ float y;public:

beta(float j)

void show_mn(){  cout<<m<<n; }};

void main(){   gamma g(31, 8.4, 38, 42);( j)

{  y = j; }void show_y(){  cout<<y; }};

{ g g( , , , );g.show_x();g.show_y();g.show_mn(); }

The constructors for virtual base classes are invoked before any non‐virtual base classes

Page 48: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Initialization ListInitialization Listclass alpha

class gamma : public beta, public alpha{ int x;public:

alpha(int i){ x i; }

class gamma : public beta, public alpha{  int u, v;public:gamma(int a, int b, float c) : 

l h ( * 2) b ( ) ( ){  x = i; }void show_alpha(){  cout<<x; }};

class beta

alpha(a * 2), beta(c, c), u(a){  v = b; }void show_gamma(){  cout<<u<<v; }};class beta

{ float p, q;public:

beta(float a, float b) : p(a), q(b + p)

{ ; }};void main(){  gamma g(36, 7, 2.5);g.show_alpha();g show beta();( , ) p( ), q( p)

{}void show_beta(){  cout<<p<<q; }};

g.show_beta();g.show_gamma();}

Data members are initialized in the order of their declaration

Page 49: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

ContainershipContainership • An object can be a collection of other objectsclass gamma{ ……

l halpha a;beta b;

public:public:gamma(arglist) : a(arglist1), b(arglist2){ …… }………};

• The constructors of member objects are called in the order in which they are declared in the nested classorder in which they are declared in the nested class

Page 50: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

PointersPointers class item{ int code;

float price;public:

void getdata(int a, float b){ b }{   code = a; price = b;}void show(){ cout<<code<<price; }};

item x;item x;item *ptr = &x;ptr‐>getdata(12, 3.5);ptr‐>show(); or (*ptr) show();ptr >show(); or ( ptr).show();item *ptr = new item;ptr‐>getdata(45, 6.9);item *ptr = new item[10]; array of objectsp [ ]; y jptr(i)‐>show();

Page 51: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Array of Pointers to ObjectsArray of Pointers to Objects#include<iostream.h>#i l d t i h#include<cstring.h>using namespace std;class city{ protected:

int main(){  city *cptr[10];{ p

char *name;int l;

public:city()

int n = 1;int option;do{ cptr[n] = new city;city()

{  l = 0;name = new char[l + 1]; }

void getname()

{ cptr[n]   new city;cptr[n]‐>getname();n++;cout<<“Continue (1/0)”;i ti{  char *s;

s = new char[10];cin>>s;l = strlen(s);

cin>>option;} while(option); }

l = strlen(s);name = new char[l + 1];strcpy(name, s);}};

Page 52: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

this pointerthis pointerclass person int main(){  char name[10];int age;public:person(char *s int a)

{  person P1(“Rony”, 35), P2(“Johny”, 25), P3(“Mani”, 45);

person P = P1.greater(P3);Pdisplay();person(char *s, int a)

{  strcpy(name, s);age = a; }

person & person :: greater(person & x)

P.display();P = P1.greater(P2);P.display(); }

person & person :: greater(person & x){  if (x.age >= age)

return x;else

return *this; } return the object it points tovoid display(){  cout<<name<<age; }};

• a pointer that points to the object for whichthis function was called

Page 53: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Pointer to Derived ClassPointer to Derived Classclass BC int main()

{ BC *bptr;{  public:

int b;id h ()

{  BC *bptr;BC base;bptr = &base;bptr‐>b = 100;

void show(){  cout<<b;}};

class DC : public BC

bptr‐>show();DC derived;bptr = &derived;bptr‐>b = 200;class DC : public BC

{ public:int d;

bptr >b = 200;bptr‐>d = 300; Errorbptr‐>show();DC *dptr;

void show(){  cout<<b<<d; }};

dptr = &derived;dptr‐>d = 300;dptr‐>show();((DC *)bptr)‐>d = 400;(( C )bptr) d 400;((DC *)bptr)‐>show(); }

Page 54: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Virtual FunctionVirtual Functionclass Base{ bli

void main(){ Base B *bptr;{ public: 

void display() { cout<<“Display Base”; }virtual void show()

{  Base B,  bptr;Derived D;bptr = &B;bptr‐>display();Base version()

{ cout<<“Show Base”; }};class Derived: public Base{ public:

void display()

p p y();bptr‐>show();  Base versionbptr = &D;bptr‐>display();Base version

void display(){  cout<<“Display Derived”; }void show(){  cout<<“Show Derived”; }};

bptr‐>show(); Derived version}

Pure Virtual Function is declared in a base class that has no definition relate to the base class. In such cases, each derived class should contain a  definition of the function or redeclare the function as a pure virtual function

virtual void display() = 0;A class containing pure virtual functions cannot be used to declare any objects its own. 

Such classes are called abstract base classes. These classes are used to create a base pointer required for achieving run time polymorphism

Page 55: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

FilesFiles 

• A file is a collection of related data stored in aA file is a collection of related data stored in a particular area on the disk

• I/O system of C++ uses file streams as an• I/O system of C++ uses file streams as an interface between the programs and the files. Input stream reads data from the file andInput stream reads data from the file and output stream writes data to the file

E d f filEnd‐of‐file• while(file1) or if(file1.eof() == 0)

Page 56: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

File I/OFile I/O#include<iostream.h>#include<fstream.h>void main(){  ofstream outf(“ITEM”); ofstream outf; outf.open(“ITEM”);

char name[10];char name[10];float cost;cin>>name>>cost;outf<<name<<“\n”<<cost;outf<<name<< \n <<cost;outf.close();ifstream inf(“ITEM”);inf>>name;;inf>>cost;cout<<name<<cost;inf.close(); }

Page 57: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Multiple FilesMultiple Files

void main() Stream_object.open(“file name”, mode);(){ char line[80];ifstream file1, file2;

_ j p ( , );File mode

Parameter Meaning

file1.open(“country”);file2.open(“capital”);

ios::app Append

ios::ate Go to end‐of‐file

ios::binary Binary filefile1.getline(line, 80);cout<<line;fil 2 li (li 80)

ios::binary Binary file

ios::in Read only

ios::nocreate Open fails if file doesn’t exist

file2.getline(line, 80);cout<<line; }

ios::noreplace Open fails if file already exists

ios::out Write only

ios::trunc Delete the contents of the file

Page 58: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Sequential I/OSequential I/O#include<fstream.h>void main(){ char c, s[20];

cin>>s;int l = strlen(s);fstream file;file.open(“Text”, ios::in | ios::out);for (int i = 0; i < l; ++i)file.put(s[i]);file.seekg(0);g( );while(file){  file.get(c);cout<<c; }; }

}

Page 59: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Binary I/OBinary I/O#include<iomanip.h>

()void main(){ float height[4] = {1.2, 3.45, 9.3, 23.6};

ofstream outfile;outfile open(“Binary”);outfile.open(“Binary”);outfile.write((char *) & height, sizeof(height));outfile.close();ifstream infile;ifstream infile;infile.open(“Binary”);infile.read((char *) & height, sizeof(height));for (int i = 0; i < 4; ++i)( ; ; ){  cout.setf(ios::showpoint);cout<<setw(10)<<setprecision(2)<<height[i]; }

infile.close(); }

Page 60: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Object I/Oclass inventory{ char name[10]; Object I/O

int code;public:

void readdata(){ cin>>name>>code; }{ cin>>name>>code; }void writedata(){ cout<<setiosflags(ios::left)<<setw(10)<<name<<setiosflags(ios::right)<<setw(10)<<code<<endl; }};code<<endl; }};

void main(){ inventory item[3];

fstream file;file.open(“stock.dat”, ios::in | ios::out);for (int i = 0; i < 3; ++i){ item[i].readdata();file.write((char *) & item[i], sizeof(item[i])); }file.write((char  ) & item[i], sizeof(item[i])); }file.seekg(0);for(i = 0; i < 3; ++i){ file.read((char *) & item[i], sizeof(item[i]));i [i] i d () }item[i].writedata(); }file.close(); }

Page 61: of Computer Science Pudukkad, THRISSURprajyotiniketan.edu.in/files/content/C++.pdf• Keywords asm defa lt float operator sitch auto bool break default delete do double for friend

Random AccessRandom Accessvoid main(){ inventory item; class inventory

fstream inoutfile; cout<<“Enter object No: “;inoutfile.open(“stock.dat”, ios::ate | ios::in | ios::out | ios::binary);inoutfile.seekg(0, ios::beg);while(inoutfile.read((char *) & item, sizeof(item)))

cout<< Enter object No:  ;int object;cin>>object;int location=(object – 1)*sizeof(item);i fil k (l i )while(inoutfile.read((char  ) & item, sizeof(item)))

item.writedata();inoutfile.clear(); turn off EOF flagitem.getdata();i tfil it (( h *) & it i f(it ))

inoutfile.seekp(location);item.getdata();inoutfile.write((char *) & item,

sizeof(item));inoutfile.write((char *) & item, sizeof(item));inoutfile.seekg(0);while(inoutfile.read((char *) & item, sizeof(item)))

item.writedata();

( ));Inoutfile.seekg(0);whie(inoutfile.read((char *) & item,

sizeof(item)))item writedata();();

int last = inoutfile.tellg();int n = last / sizeof(item);cout<<“No of bytes : “<<n;cout<<“Total bytes : “<<last;

item.writedata();inoutfile.close();}

cout<< Total bytes  :  <<last;