Escolar Documentos
Profissional Documentos
Cultura Documentos
- Socrates
Encapsulation
Data Abstraction
Single Inheritance
Comprises Supported By
Polymorphism
OOP C++
Paradig Persistence
m
Delegation
Genericity
Multiple Inheritance
Encapsulation
Data abstraction
Inheritance
Polymorphism
Message passing
Extensibility
Persistence
Delegation
Genericity
Multiple Inheritance
Inheritance
Class Foundation { F W R
}
Class Wall {
H
}
Class Room {
}
Class House {
}
Inheritance
F
Class Foundation {
}
W
Class Wall : public Foundation {
} R
Class Room: public Wall {
}
H
Class House: public Room {
}
Class Foundation {
}
Class Wall {
}
Class Room {
}
Class House {
Foundation F;
Wall W;
Room R;
}
1. char &ch1=ch;
2. int &a=b;
3. float &x=y;
4. double &height = length;
5. int &x=y[100]; // x is an alias of y[100]th element
6. int n;
int *p=&n;
int &m=*p; // these declaration cause m to refer n
void main()
{
int a =1,b=2,c=3;
int &z=a;
cout<<“a=“<<a<<“b=“<<b<<“c=“<<c<<“z=“<<z<<”\n”;
z=b;
cout<<“a=“<<a<<“b=“<<b<<“c=“<<c<<“z=“<<z<<”\n”;
z=c;
cout<<“a=“<<a<<“b=“<<b<<“c=“<<c<<“z=“<<z<<”\n”;
cout<<“&a=“<<&a<<“&b=“<<&b<<“&c=“<<&c<<“&z=“<<&z;
}
void main()
{
int n=100;
int *p=&n;
int &m=*p;
cout<<“n =“<<n<<“m=“<<m<<“*p=“<<*p<<endl;
int k=5;
p=&k;
k=200;
cout<<“n =“<<n<<“m=“<<m<<“*p=“<<*p<<endl;
}
Default Arguments
In a C++ function call , when one or more function arguments
are omitted, the function may be defined to take default values
for omitted arguments by providing the default values in the
function prototype.
#include<stdio.h>
void showdata(struct stud *t) {
#include<conio.h>
cout<<" mark1 mark2 mark3\n";
#include<iostream.h>
struct stud cout<<t->mark1<<t->mark2<<t->mark3;
{ }
int mark1, mark2,int mark3,total; void processdata(struct stud *t) {
};// end of structure t->total=t->mark1+t->mark2+t->mark3;
void getdata(struct stud *t) { }
cout<<"enter mark1";
void main() {
cin>>t->mark1;
struct stud st1;
cout<<"enter mark2";
cin>>t->mark2; getdata(&st1);
cout<<"enter mark3"; showdata(&st1);
cin>>t->mark3; processdata(&st1);
t->total=0; cout<<"total = "<<st1.total;
} }
void showdata() {
cout<<" mark1 mark2 mark3\n";
#include<stdio.h> cout<<mark1<<mark2<<mark3;}
#include<conio.h> void processdata()
{
#include<iostream.h>
total=mark1+mark2+mark3;
struct stud { }
int mark1,mark2,mark3,total; };// end of structure
void getdata() { void main() {
struct stud st1;
cout<<"enter mark1";
st1.getdata();
cin>>mark1; st1.showdata();
cout<<"enter mark2"; st1.processdata();
cin>>mark2; cout<<"total = "<<st1.total;
}
cout<<"enter mark3";
cin>>mark3;
total=0;
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
C++ Class 32
#include<stdio.h> void showdata() {
#include<conio.h> cout<<" mark1 mark2 mark3\n";
cout<<mark1<<mark2<<mark3;}
#include<iostream.h>
void processdata()
class stud {
{
public:
total=mark1+mark2+mark3;
int mark1,mark2,mark3,total; }
void getdata() { };// end of class
cout<<"enter mark1";cin>>mark1; void main() {
cout<<"enter mark2";cin>>mark2; struct stud st1; st1.getdata();
cout<<"enter mark3";cin>>mark3; st1.showdata(); st1.processdata();
total=0; cout<<"total = "<<st1.total;
} }
Include files
Class declaration
Program Elements
Comments
Keywords
Identifiers
Literals
Operators and Punctuators
Input/Output
int a,b;
cout<<“enter the input for a and b”;
cin>>a>>b;
cout<<“sum of a and b is “<<a+b;
void main() {
void swap(char &x, char &y){ char ch1,ch2; float f1,f2; int i1,i2;
char t; t=x; x=y; y=t; } ch1=‘a’; ch2=‘b’; f1=3.5; f2=4.6;
i1=56; i2=89;
void swap(int &x, int &y){ swap(ch1,ch2);
int t; t=x; x=y; y=t; } cout<<ch1<<ch2<<endl;
swap(i1,i2);
void swap(float &x, float &y){ cout<<i1<<i2<<endl;
float t; t=x; x=y; y=t; } swap(f1,f2);
cout<<f1<<f2<<endl;
}
Go back
The compiler will not consider return type in discriminating one with
the other in function overloading.
int i;
i=add(5,6);
cout<<add(5,6);
x := 5;
{x > 0} Assertion
x := x + 1
{x > 1} Assertion
Data
data1
data2
data3
Functions
func1 ( )
func2 ( )
func3 ( )
Class Specification
class className {
};
int wheel
showdata ( ) reverse ( )
class student {
private:
int roll_no; char name[20];
public:
void setdata (int roll_no_in, char *name_in)
{
roll_no=roll_no_in; strcpy(name,name_in);
}
void outdata()
{
cout<<“Rollno=“<<roll_no<<endl;
cout<<“Name=“<<name<<endl;
}
};
Class Objects
student s1,s2,s3,s4;
student s[4];
Example
class student {
int roll_no; char name[20];
public:
void main()
void setdata (int roll_no_in, char
*name_in) {
{ roll_no=roll_no_in; student s1,s2;
strcpy(name,name_in); } s1.setdata(10,”raja”);
void outdata(); s2.setdata(20,”ramu”);
}; s2.outdata();
void student::outdata() s2.outdata();
{ }
cout<<“Rollno=“<<roll_no<<endl;
cout<<“Name=“<<name<<endl;
}
Private Members
class person {
private:
……..
……..
int age; // private data
int getage(); // private function
};
person p1;
int a=p1.age; // cannot access private data
int age=p1.getage(); // cannot access private function
Protected Members
class person {
protected:
……..
……..
int age; // protected data
int getage(); // protected function
};
person p1;
int a=p1.age; // cannot access protected member
int age=p1.getage(); // same as private
Public Members
class person {
public:
……..
……..
int age; // public data
int getage; // public function
};
person p1;
int a=p1.age; // can access public data
int age=p1.getage(); // can access public function
Access Accessible to
Specifier
Own Class Object of a
members Class
Private: Yes No
Protected: Yes No
58
Empty Classes
Class xyz { };
Class empty
{
};
Significant usage of empty classes can be found in Exception
Handling.
void Vector::show_sum(){
class Vector {
int sum=0;
int *v,sz;
for(int i =0;i<sz;i++)
public:
sum+=v[i];
void VectorSize(int size) {
cout<<“vector sum is “<<sum;}
sz=size; v=new int[size]; }
void release() {
void main() {
delete v; }
Vector v1; int count;
void read();
cout<<“enter size of vector”;
void show_sum();
cin>>count;
};
V1.VectorSize(count); V1.read();
void Vector::read() {
V1.show_sum(); V1.release();
for(int i =0;i<sz;i++)
cin>>v[i]; }
}
feet
feet
24.0
inches
inches
1.5
d1 d2
feet feet
d1.feet d2.feet
12.0 11.0
inches inches
d1.inches d2.inches
7.25 6.25
The policy is that if you are not a member you cannot access
the member data and functions.
class X class Y
private:
data or function fy1 ( )
protected:
friend class y;
friend fun1( );
friend z::
fz1( );
class Z
fun1( )
fz1 ( )
friend of x
fz2 ( )
Since it is not in the scope of the class, it cannot be called using the
object of that class
It can be invoked like a normal function without the aid of any object
and friendship is not mutual by default
It can be declared either in the public or the private part of a class and
usually, it has objects as arguments
Friend Classes
Friend Classes
Friend Classes
class Twovalue {
void main() {
int a; int b;
public : Twovalue ob;
void setvalue( int i, int j) { ob.setvalue(10,20);
a=i; b=j; } Min m;
int showa( ) { return a; } cout<<"Minimum
int showb( ) { return b; } of"<<ob.showa()<<"and"
friend class Min; <<ob.showb()<<"is“
}; <<m.minimum(ob);
class Min {
}
public:
int minimum(Twovalue &x) {
return x.a < x.b ? x.a : x.b; }
};
class demo {
int i;
This program will not
public:
compile because set_i() is
int get_i ( ) const {
declared as const. This
return i; } means that it is not
void set_i( int x ) const { allowed to modify the
i=x; } invoking object.
};
void main() {
demo ob;
ob.set_i(1500);
cout<<ob.get_i();
}
fun 1()
fun k()
(PN) (MCA)(2010-11/ EVEN) (2010-13)
88
Static Data members
When one of them modifies the static data member, the effect is
visible to all the instance of the class
data1 data1 …
data1
static data 1
Each object of a class has its own set of public or private data
class Classname
{
storage qualifier
………
static data member
}; Initialization is optional
Static data member declaration in a class and its definition outside the class
void main ( ) {
class myclass {
myclass obj1; obj1.show();
static int count;
obj1.set(100); obj1.show();
int number;
myclass obj2,obj3;
public:
obj2.set(200);obj2.show();
void set (int num)
{ number=num; ++count; } obj2.set(250); obj3.set(300);
void show() { obj1.show(); }
cout<<“\count is =:”<<count;
count is = 0
}
count is = 1
};
count is = 2
int myclass :: count=0;
count is = 4
The static data members which are declared in public limit are
similar to normal global variables, they can be reached by
prefixing class name and scope resolution :: operator or
through the instance of that class
class test {
void main(){
static int privateint;
test::publicint=100;
static void privatefunction() {
cout<<"i am static private // Wrong test::privateint=200;
function\n"; } test::publicfunction(); //ok
public: // wrong test::privatefunction();
static int publicint; test obj1;
static void publicfunction() { obj1.publicint=100;//ok
cout<<"i am static public function\n";
// wrong obj1.privateint=200;
privatefunction(); }
obj1.publicfunction();//ok
};
//wrong obj1.privatefunction();
int test::privateint;
int test::publicint; }
void main( ) {
class directory{
cout<<“path:”<<directory::path;
public:
directory::setpath(“/usr”);
static char path[ ];
directory dir;
static void setpath (char const
cout<<“path:”<<directory::path;
*newpath);
dir.setpath(“/etc”);
};
cout<<“path:”<<dir.path; }
char directory::path[100]=“/usr/raj”;
Path: /usr/raj
void directory ::setpath(char const
*newpath){ Path: /usr
strcpy(path,newpath); } Path: /etc
Only one copy of static data member exists for all the
instance of a class
class classname {
…..
…..
public:
classname(){ definition inside}
…..
……
};
class Counter {
private: unsigned int count;
void main() {
public: Counter() : count(0){}
Counter c1, c2;
void inc_count() {
cout<<“\nc1=”<< c1.get_count();
count++; } cout<<“\nc2=”<<c2.get_count();
int get_count() { c1.inc_count(); //increment c1
return count; } c2.inc_count(); //increment c2
}; c2.inc_count(); //increment c2
cout <<“\nc1=”<<c1.get_count();
cout <<“\nc2=”<<c2.get_count();
}
c1=0
c2=0
c1=1
c2=2
back
Parameterized Constructors
Destructor
class classname {
…..
…..
public:
~classname(){ definition inside}
…..
……
};
void main() {
class test { test x;
public: cout<<“Terminating main()\n”;
test(); }
~test(); };
test::test() {
cout<<“constructor of test
class called\n”;
}
constructor of test class called
test::~test() {
Terminating main
cout<<“destructor of test
destructor of test class called
class called\n”;
}
Constructor Overloading
void main() {
class test { test t1,t2;
int a,b; t1.setdata(5,6); t2.setdata(7,8);
public: cout<<"\n object t1"<<endl;
void addressanddata(); t1.addressanddata();
cout<<"\n object t2"<<endl;
void setdata(int k1,int k2) {
t2.addressanddata(); }
a=k1;b=k2; }
}; object t1
void test::addressanddata() { a is 5 its address is 0x8fc4fff2
cout<<" \n a is "<<a <<" its b is 6 its address is 0x8fc4fff4
address is "<<&a<<endl; object t2
cout<<" \n b is "<<b <<" its a is 7 its address is 0x8fc4ffee
address is "<<&b<<endl; } b is 8 its address is 0x8fc4fff0
Assignment
class base {
int a[5]; int sz; void base::dataandaddress(){
public: for(int i=0;i<sz;i++)
cout<<"address of a["<<i<<"]is
void readdata(int);
"<<&a[i]<<" data of a["<<i<<"]
void showaddress();
is "<<a[i];
void dataandaddress(); }
};
void base::readdata(int size){ void base::showaddress() {
sz=size; cout<<"address alloted in
for(int i=0;i<sz;i++) cin>>a[i]; memory is"<<a; }
}
void main() {
base b1,b2; cout<<"b1 ";
b1.showaddress();
cout<<"b2 ";
b2.showaddress();
cout<<"\n enter b1 data;
b1.readdata(5);
cout<<"\n b1 address and its
data member";
b1.dataandaddress();
b2=b1;//assignment
cout<<"\n b2 address and its
data member";
b2.dataandaddress(); }
void main() {
base b1; cout<<"b1 ";
b1.showaddress();
cout<<"\n enter b1 data ";
b1.readdata(5);
cout<<"\n b1 address and its data member";
b1.dataandaddress();
base b2(b1); //copy constructor
cout<<"\n b2 ";
b2.showaddress();
cout<<"\n b2 address and its data member";
b2.dataandaddress();
}
enter b1 data: 1 2 3 4 5
This works well if the fields are values, but may not be what
you want for fields that point to dynamically allocated memory.
The pointer will be copied, but the memory it points to will not
be copied
The field in both the original object and the copy will then point
to the same dynamically allocated memory, which is not
usually what you want (deep copy required)
Deep Copy
void main() {
base b1(5),base b2(5);
cout<<"\n enter b1 data ";
b1.readdata();
cout<<"\n b1 address and its data member";
b1.showdataandaddress();
b2=b1; //calling compiler default copy constructor
//base b2=b1; calling user defined copy constructor version
//base b2(b1); calling user defined copy constructor version
cout<<"\n b2 address and its data member";
b2.showdataandaddress();
}
void main() {
cout<<"b1 "; base b1(5);
cout<<"\n enter b1 data ";
b1.readdata();
cout<<"\n b1 address and its data member";
b1.showdataandaddress();
cout<<"b2 ";
//base b2=b1;
base b2(b1);// calling overridden user defined copy constructor
cout<<"\n b2 address and its data member"<<endl<<endl;
b2.showdataandaddress(); }
enter b1 data: 1 2 3 4 5
Nameless Object
classname (arguments);
void main() {
class nameless {
nameless().show();
public:
nameless n1;
nameless() { nameless n2;
cout<<“constructor”; } n2.show();
~nameless() { cout<<“program terminates”;
cout<<“destructor”; } }
void show() constructor <- nameless()
{ I am show called
cout<<“I am show called”; destructor <- nameless()
} constructor <- nameless n1()
constructor <- nameless n2()
};
I am show called
program terminates
destructor <- nameless n2()
destructor <- nameless n1()
Nested Classes
this pointer
class test {
void main() {
int a,b;
test t1(10,20);
public:
t1.show();
test(int a,int b) {
}
a=a; b=b;
}
void show() {
cout<<" a is "<<a<<endl;
cout<<" b is "<<b<<endl;
}
};
class test {
void main() {
int a,b;
test t1(10,20);
public:
t1.show();
test(int a,int b) {
}
this->a=a; this->b=b;
}
friend function and static
void show() {
component( data + function)
cout<<" a is "<<a<<endl;
cannot be invoked using this pointer
cout<<" b is "<<b<<endl;
}
};
Dynamic Objects
The operators new and delete used with standard data type
variable’s management can also be used for creating or
destroying objects at run time respectively
Pointer to objects
pointer_to_object->member_name
or
(*pointer_to_object).member_name
void main() {
class test { test *ptr,t;
int a,b; ptr=&t;
public: t.setdata(1,2);
void setdata(int k1,int k2) { ptr->showdata();
a=k1;b=k2; } t.showdata();
void showdata() { (*ptr).showdata();
cout<<" a is "<<a<<endl; }
cout<<" b is "<<b<<endl;
} };
void main() {
class test { test *ptr=new test;
int a,b; ptr->setdata(1,2);
public: ptr->showdata();
test() { cout<<“constructor”;} (*ptr).showdata();
~test() { cout<<“destrcutor”;} delete ptr; }
void setdata(int k1,int k2) {
a=k1;b=k2; }
void showdata() {
cout<<" a is "<<a<<” b
is”<<b; }
};
When the dynamic object pointed to, by the variable ptr goes
out of scope, the memory allocated to that object is not
released automatically
for(i=0;i<10;i++,count++) {
class student { cout<<"object to be initialized
int rollno; char name[20]; (y/n): ";
public: cin>>flag;
void setdata(int roll, char *n) if(flag=='y' || flag=='Y') {
{strcpy(name,n); rollno=roll;} cout<<"enter rollno of student :";
void showdata() { cin>>rollno;
cout<<"Roll No: "<<rollno; cout<<"enter name of student :";
cout<<"Name: "<<name; cin>>name;
}}; s[i].setdata(rollno,name);
}
else break;
void main() {
}
int i,rollno,count=0;
cout<<“student details:”;
student s[10];
for(i=0;i<count;i++) {
char flag, name[20];
s[i].showdata();
}
for(i=0;i<10;i++,count++) {
class student {
cout<<"object to be initialized(y/n):";
int rollno; char name[20];
cin>>flag;
public:
if(flag=='y' || flag=='Y') {
void setdata(int roll, char *n)
cout<<"enter rollno of student :";
{
cin>>rollno;
strcpy(name,n); rollno=roll;
cout<<"enter name of student :";
}
cin>>name;
void showdata() {
S[i]=new student;// dynamic object
cout<<"Roll No: "<<rollno;
s[i]->setdata(rollno,name);
cout<<"Name: "<<name;
}
}};
else break; }
cout<<“student details:”;
void main() {
for(i=0;i<count;i++) s[i]->showdata();
int i,rollno,count=0;
for(i=0;i<count;i++) delete s[i];
student *s[10];
} // dynamic object deletion
char flag, name[20];
a is 0 a is 1
b is 0 a is 3 b is 1 z[1]
c is 0 b is 4 y[1] c is 1
x[1]
c is 0
a is 0 a is 3
b is 0 a is 5 b is 4 z[2]
y[2]
c is 0 x[2] b is 6 c is 0
c is 0
a is 5
b is 6 z[3]
c is 7
The syntax for defining the pointer to class member and binding
the class member to the pointer is shown below
datatype classname::*pointername;
class test
{
private:
int x;
public:
int a,b;
int init(int z);
int check(int c);
};
int test::*ip;
ip=&test::a;
int test::*ip=&test::a;
The pointer variable ip, acts like the class member so that it can
be invoked with a class object
The pointer and the variable have meaning only when they are
associated with the class to which they belong
int (test::*func_ptr)(int);
func_ptr=&test:: show;
or
int(test::*func_ptr)(int)=&test:: show;
index 1 0
index 2 0
index 1 1
index 2 2
class complex {
float x,y;
public: void main()
complex() { } complex c1(1.5,2.5),c2(1.7,2.6);
complex(float x1,float y1){ complex c3;
x=x1;y=y1;}
c3=c1+c2;
void show() {
cout<<"C1 = ";c1.show();
cout<< x<<" + j"<< y }
complex operator+(complex&); cout<<"C2 = ";c2.show();
}; cout<<"C3 = ";c3.show();
complex complex::operator + }
(complex &obj2) {
float x1,y1;
x1=x+obj2.x; y1=y+obj2.y; C1 = 1.5 + j2.5
return complex(x1,y1); C2 = 1.7 + j2.6
} C3 = 3.2 + j5.1
class index {
int value;
public:
index ( ) { value=0;
void main() {
}
int get_index(){return value; } index idx1,idx2;
friend void operator++(index i1); cout<<“ index1
}; "<<idx1.get_index();
void operator ++ (index i1) { cout<<" index2
i1.value =i1.value + 1; } "<<idx2.get_index();
++idx1;
index 1 0 idx2++;
index 2 0
idx2++;
index 1 0
index 2 0
cout<<" index1
"<<idx1.get_index();
cout<<"index2“
<<idx2.get_index();
}
void main() {
class complex{ complex c1(1.5,2.5),c2(1.7,2.6);
float x,y; complex c3;
public:
complex() { }
c3=c1+c2;
complex(float x1,float y1){ cout<<"C1 = ";c1.show();
x=x1;y=y1;} cout<<"C2 = ";c2.show();
void show() { cout<<"C3 = ";c3.show();
cout<< x<<" + j"<< y ; }
friend complex operator +
}
(complex &,complex&);
}; C1 = 1.5 + j2.5
complex operator + C2 = 1.7 + j2.6
(complex &obj1,complex &obj2) {
float x1,y1; C3 = 3.2 + j5.1
x1=obj1.x+obj2.x;
y1=obj1.y+obj2.y;
return complex(x1,y1); }
void main() {
complex c1(1,2),c2(3,4);
complex c3;
c3=c1+c2;
cout<<"\n C1 = ";c1.show();
cout<<"\n C2 = ";c2.show();
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// c1+ complex(2.0)
cout<<"\n C3 = ";c3.show();
//c3=2.0+c1; invalid
cout<<"\n C3 = ";c3.show();
}
void main() {
complex c1(1,2),c2(3,4);
complex c3;
c3=c1+c2;
cout<<"\n C1 = ";c1.show();
cout<<"\n C2 = ";c2.show();
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// no object creation; direct floating point data
cout<<"\n C3 = ";c3.show();
// invalid c3=2.0+c1;
cout<<"\n C3 = ";c3.show();
}
void main() {
complex c1(1,2),c2(3,4);
complex c3;
c3=c1+c2;
cout<<"\n C1 = ";c1.show();
cout<<"\n C2 = ";c2.show();
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// no object creation; direct floating point data
cout<<"\n C3 = ";c3.show();
c3=2.0+c1;
cout<<"\n C3 = ";c3.show();
}
Overloading [] Operator
class Array { class Array {
private: private:
int data[100]; int data[100];
public: public:
int& operator[] (unsigned i)
int& elem(unsigned i)
{ if (i > 99)
{ if (i > 99)
cout<<“error out of range”;
cout<<“error out of range”;
return data[i];
return data[i];
}
} };
};
void main() void main()
{ {
Array a; Array a;
a.elem(10) = 42; a[10] = 42;
a.elem(12) += a.elem(13) a[12] += a[13];
; ...
... }
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
204
void main() {
String str1("Welcome to ");
String str2("India");
String str3;
cout<<"String1 is :";str1.show();
cout<<"\nString2 is :";str2.show();
str3=str1+str2;
cout<<"\nString3 is :";str3.show();cout<<endl<<endl;
if(str1 < str3) {
str1.show();
cout<<"is smaller than "; str3.show(); }
else{str3.show();cout<<"is smaller than ";str1.show(); }
}
String1 is :'Welcome to '
String2 is :'India'
String3 is :'Welcome to India‘ +
'Welcome to 'is smaller than 'Welcome to India‘ <
When new and delete operators are for a specific class, the
use of these operators on any other type of data causes the
original new or delete to be employed
If so, those specific versions are used, if not, C++ uses the
globally defined new and delete
class meter {
float length;
public:
meter() { length=0.0;}
meter(float initlength) {//one argument constructor,converts
length=initlength/100.0; // centimeter to meter
}
operator float() {//converts meter to centimeter
return length*100.0; }
void getlength() { cout<<"\n enter length (in meters): ";
cin>>length; }
void showlength() {cout<<"\n length (in meter)= "<<length; }
};
void main() {
meter m1; // uses constructor0
float length1,length2;
cout<<"\n enter length in centimeter :"; cin>>length1;
m1=length1;// converts basic to userdefined, uses constructor1
m1.showlength();
meter m2; m2.getlength();
length2=m2;//converts userdefined to basic,uses operator float()
cout<<"\n length (in cms) ="<<length2; }
Example:
Angle in Radian = Angle in Degree*PI/180.0
Angle in Degree = Angle in Radian *180/PI, where PI=22/7
class degree {
const float PI = 3.1415;
float deg;
class radian {
public:
float rad;
degree() { deg=0.0; }
public:
operator radian() {
radian() { rad=0.0;}
return radian(deg*PI/180.0); }
radian(float initrad) {
void showdata() {
rad=initrad; }
cout<<"\n Degree= "<<deg; }
void showdata() {
void getdata() {
cout<<"\n Radian = "<<rad; }
cout<<"enter degree :";
};
cin>>deg; }
};
void main() {
degree deg1; radian rad1;
deg1.getdata();
rad1=deg1;
rad1.showdat a();
}
class radian {
const float PI = 3.1415;
float rad;
class degree {
public:
float deg;
radian() { rad=0.0;}
public: radian(float initrad) {
degree() { deg=0.0; } rad=initrad; }
void getdata() { radian(degree d) {
cout<<"enter degree :"; rad=d.getdegree()*PI/180.0; }
cin>>deg; } float getradian() {
float getdegree(){return deg; } return rad; }
}; void showdata() {
cout<<"\n Radian = "<<rad; }
};
void main() {
degree deg1; radian rad1;
deg1.getdata();
rad1=deg1;
rad1.showdata();
}
Complete Conversion
void main() {
degree deg1,deg2; radian rad1,rad2;
//degree to radian conversion
deg1.getdata();
rad1=deg1; // convert degree to radian, uses ‘operator radian()’
rad1.showdata();
//radian to degree conversion
rad2.getdata();
deg2=rad2; // convert radian to degree, uses degree(radian r)
deg2.showdata(); }
enter degree :90
Radian = 1.57075
enter radian :1.57075
Degree= 90
The trick is to use the classes without soiling the existing code
You literally take the form of the existing class and add code to it,
without modifying the existing class
This magical act is called inheritance, and most of the work is done
by the compiler.
Composition
class Y {
class X {
int i;
int i;
public:
public:
X x;
X() { i = 0; }
Y() { i = 0; }
void set(int ii) { i = ii; }
void f(int ii) { i = ii; }
int read() const { return i; }
int g() const { return i; }
int permute() {return i = i * 47; }
};
};
void main() {
Y y; y.f(47);
y.x.set(37);
}
Composition -Private
class Y {
int i;
class X { X x;
int i; public:
public: Y() { i = 0; }
X() { i = 0; } void f(int ii) {i=ii; x.set(ii);}
void set(int ii) { i = ii; } int g()const {return i *x.read(); }
int read() const { return i; } void permute() { x.permute(); }
int permute() {return i = i * 47; } };
}; void main() {
Y y; y.f(47);
y.permute();
}
Inheritance
class Y : public X{
int i;
class X { public:
int i; Y() { i = 0; }
public: void f(int ii) { i = ii; }
X() { i = 0; } int g() const { return i; }
void set(int ii) { i = ii; } };
int read() const { return i; } void main() {
int permute() {return i = i * 47; } Y y;
}; y.f(47);
y.set(37);
}
When you declare a class, you can indicate the name of the
class from which it derives
Syntax
class derived class name : visibility mode base class name
{
… // Members of derived class
}
Visibility Mode
For example:
class ABC : private XYZ // private derivation
{
Members of ABC
};
Go to slide 69
void main() {
C c1;
cout<<c1.publicdataA;
B b1;
cout<<b1.publicdataA;
}
class B {
public:
B()
{cout<<“No argument constructor of the base class B is executed”;}
};
class D: public B {
};
void main() {
D obj1;
}
class B {
// body of base class without constructors
};
class D: public B {
public:
D() {cout<<“constructors exists in only in derived class”;}
};
void main() {
D objd; }
class B {
public:
B() {
cout<“No-argument constructor of the base class B executed first”; }
};
class D: public B {
public:
D() {
cout<<“No-arg constructor of the derived class D executed next”; } };
void main() { D objd; }
No-argument constructor of the base class B executed first
No-argument constructor of the derived class D executed next
class B {
public:
B() {cout<“No-argument constructor of the base class B ”; }
B(int a){cout<“one argument constructor of the base class B ”; }
};
class D: public B {
public:
D(int a){cout<“one argument constructor of the derived class D ”; }
};
void main() { D objd(5); }
No-argument constructor of the base class B
one argument constructor of the derived class D
If the base class does not have a default constructor and has
an argument constructor, they must be explicitly invoked,
otherwise the compiler generates error
class B {
public:
B(int a){cout<“one argument constructor of the base class B ”; }
};
class D: public B {
public:
D(int a){cout<“one argument constructor of the derived class D ”;}
};
void main() { D objd(5); }
cannot find ‘default’ constructor to initialize base class ‘B’
class B {
public:
B(int a){cout<“one argument constructor of the base class B ”; }
};
class D: public B {
public:
D(int a): B(a){cout<“one arg constructor of the derived class D ”;}
};
void main() { D objd(5); }
one argument constructor of the base class B
one argument constructor of the derived class D
void main() {
gama g1(1,2,3); g1.showabc();
}
alpha class constructor called
beta class constructor called
gama class constructor called
a is 1
b is 2
c is 3
gama class destructor called
beta class destructor called
alpha class destructor called
Multilevel Inheritance
Student
void main() {
result r1;r1.processmark(); name is raja
} sex is m
age is 21
enter name :raja rollno:25
enter sex :m branch :mca
enter age :21 mark1 is :50
enter rollno :25 mark2 is :60
enter branch :mca mark3 is :70
enter sub1 mark :50 total is 180
enter sub2 mark :60
enter sub3 mark :70
Father Mother
Multiple Inheritance
Child
class father {
float salary;
public:
void assign_salary(float sal) { salary=sal; }
float get_salary() { return salary; }
};
class mother {
float salary;
public:
void assign_salary(float sal) { salary=sal; }
float get_salary() {return salary; }
};
class a {
int x;
public:
void get_x(int x1) {x=x1; }
void main() {
void show() {
b b1;
cout<<“\n x="<<x; }
b1.get_x(100);
};
b1.get_y(200);
class b:public a {
b1.show();
int y;
public :
b1.show();
void get_y(int y1) {y=y1;} }
void show() {
cout<<“\n y="<<y; } y=200
}; y=200
class a {
int x;
public: void main() {
void get_x(int x1) {x=x1; } b b1;
void show() { b1.get_x(100);
cout<<“\n x="<<x; } b1.get_y(200);
}; b1.show();
class b:public a { }
int y;
public : x=100
void get_y(int y1) {y=y1;} y=200
void show() {
a::show();
cout<<“\n y="<<y; }
};
class a {
int x;
void main() {
public: b b1;
void get_x(int x1) {x=x1; } b1.get_x(100);
void show() { b1.get_y(200);
cout<<“\n x="<<x; } b1.a::show();
};
b1.b::show();
class b:public a {
}
int y;
public : x=100
void get_y(int y1) {y=y1;} y=200
void show() {
cout<<“\n y="<<y; }
};
class b {
void main() {
public:
c c1; c1.show(); }
void show() {
cout<<" this is show from b this is show from a class
class”; }
this is show from b class
}; this is show from c class
void main() {
class b {
c c1; c1.a::show();
public:
c1.b::show(); c1.show();
void show() {
}
cout<<" this is show from b this is show from a class
class”; }
this is show from b class
}; this is show from c class
void main() {
c c1; c1.show();
}
this is show from c class
Parent
Child1 Child2
Grandchild
class parent {
protected : int basedata;
public: void main() {
void initdata(int x) {basedata=x;} grandchild g;
}; g.initdata(100); //Error
class child1: public parent { cout<<g.getdata();
}; }
class child2: public parent {
};
class grandchild: public child1,public child2 {
public:
int getdata() { Member is ambiguous:
return basedata; //Error 'parent::basedata' and
} 'parent::basedata'
}; Member is ambiguous:
'parent::initdata' and
'parent::initdata
class parent {
protected : int basedata; void main() {
public: grandchild g;
void initdata(int x) { g.initdata(100);
basedata=x; }
cout<<g.getdata();
};
class child1: virtual public parent { //share }
copy of parent};
class child2: public virtual parent { //share
copy of parent};
class grandchild: public child1,public child2 { 100
public:
int getdata() { return basedata;
// O.K: only one copy of parent} Note: Friendship is not
};
inheritive, transitive and
mutual
Virtual Functions
Polymorphism
//Declarations
int add(int a, int b); //prototype 1
int add(int a, int b ,int c); //prototype 2
double add(double x, double y); //prototype 3
double add(int p,double q); //prototype 4
double add(double p, int q); //prototype 5
//Function calls
cout<<add (5,10); //uses prototype 1
cout<<add (15,10.0); //uses prototype 4
cout<<add (12.5,7.5); //uses prototype 3
cout<<add (5,10,15); //uses prototype 2
cout<<add (0.75,5); //uses prototype 5
Base
Base
ptr->show()
Derv1
ptr Show()
&Derv2
ptr->show()
Derv2
Show()
Static Binding
class Base {
public:
virtual void show() { void main() {
cout<<“\n Base"; } Derv1 dv1;
}; Derv2 dv2;
class Derv1: public Base { Base *ptr;
public: ptr=&dv1;
void show() {
ptr->show();
cout<<“\n Derv1"; }
ptr=&dv2;
};
class Derv2: public Base {
ptr->show();
public: }
void show() { Derv1
cout<<“\n Derv2"; } Derv2
};
Base
ptr Show()
&Derv1
ptr->show()
Derv1
ptr Show()
&Derv2
ptr->show()
Derv2
Show()
Dynamic Binding
Now, as you can see, the member function of the derived classes,
not the base class are executed
The rule is that the compiler selects the function based on the
contents of the pointer ptr, not on the type of the pointer, as in the
earlier program
void main() {
x X; y Y; x *p;
class x { p=&X;
public: p->f();
void f() { p=&Y;
cout<<"\n this is x::f() of x class";} ((y*)p)->f();
void f1() { y *p1;
cout<<"\n x::f1()exeucting"; } p1->f1();
}; ((x*)p1)->f1();
class y:public x { }
public: this is x::f() of x class
void f() { this is y::f() of y class
cout<<"this is y::f() of y class";} y::f1()exeucting
void f1() { x::f1()exeucting
cout<<"\n y::f1()exeucting"; }
};
Virtual functions defined inside the base class normally serve as a framework
for future design of the class hierarchy
These functions can be overridden by the methods in the derived classes
In most of these cases, these virtual functions are defined with a null body; it
has no definition
Such functions in the base class are similar to do-nothing or dummy and in C+
+, they are called pure virtual functions
syntax of pure virtual function
class myclass
{
public
………
virtual ReturnType FunctionName(arguments)=0;
……..
}
Virtual Destructors
class father {
protected: char *fname; Son
public:
father(char *fn) {
fname=new char[strlen(fn)+1]; strcpy(fname,fn); }
virtual ~father(){delete fname;cout<<"~father() is invoked"; }
virtual void show() {cout<<"father name:"<<fname; }
};
class son:public father {
protected: char *sname;
public:
son(char *fn,char *sn):father(fn) {
sname=new char [strlen(sn)+1];strcpy(sname,sn); }
~son() {delete sname; cout<<"~son() is invoked"; }
void show(){cout<<"father name:"<<fname<<"son
name:"<<sname; }
};
The templates declared for functions are called function and classes
are called class template respectively
void main() {
int i=10, j=20; double x=10.1, y=23.3; char a='x', b='z';
cout << "Original i, j: " << i << ' ' << j ;
cout << "Original x, y: " << x << ' ' <<y;
cout << "Original a, b: " << a << ' ' << b;
swapargs(i,j); // swap integers
swapargs(x,y); // swap floats
swapargs(a,b); // swap chars
cout << "Swapped i, j: " << i << ' ' << j ;
cout << "Swapped x, y: " << x << ' ' << y;
cout << "Swapped a, b: " << a << ' ' << b;
}
Original i, j: 10 20
Original x, y: 10.1 23.3
Original a, b: x z
Swapped i, j: 20 10
Swapped x, y: 23.3 10.1
Swapped a, b: z x
The maximum of a ,b is b
The maximum of 5 ,7 is 7
The maximum of 34.5 ,56.8 is 56.8
If the program has both function and function template with the
same name, first the compiler selects the normal function, scans
for the match with the requested datatype, otherwise, it creates
a function using a function template
5
8.5
100
100
100
100
Good Morning
Good Morning
Good Morning
the maximum of a ,b is b
the maximum of 4 ,5 is 5
the maximum of 6.7 ,8.9 is 8.9
the maximum of mala ,kala is mala
the maximum of a ,b ,c is c
the maximum of mala ,kala ,rama is rama
// Push an object.
template<class StackType>void stack<StackType>::push(StackType ob)
{ if(tos==SIZE) { cout << "Stack is full.\n"; return; }
stck[tos] = ob; tos++; }
// Pop an object.
template <class StackType> StackType stack<StackType>::pop() {
if(tos==0) {cout << "Stack is empty.\n"; return 0; }
tos--; return stck[tos]; }
void main( ) {
// Demonstrate character stack
stack<char> cs; // create character stack
int i; cs.push('a'); cs.push('b'); cs.push('c');
cout<<"character stack :";
for(i=0; i<3; i++) cout << "Pop character stack : "<< cs.pop();
// demonstrate int stack
stack<int> is; // create integer stack
is.push(1); is.push(2); is.push(3);
cout<<"integer stack :";
for(i=0; i<3; i++) cout <<"Pop integer stack :"<< is.pop();
integer stack :
Record stack
Pop integer stack : 3
Pop integer stack : 2 Pop Record Stack0 rama 3 60 90
Pop integer stack : 1 Pop Record Stack1 ravi 2 50 80
Pop Record Stack2 raja 1 45 50
double stack :
Pop double stack : 3.3
Pop double stack : 2.2
Pop double stack : 1.1
A template class can have more than one generic data type
To use more than one data type, declare all the data types
required by the class in a comma-separated list within the
template specification class
class phonebook {
public: char name[80]; int areacode; int prefix; int num;
public: phonebook() { };
phonebook(char *n, int a, int p, int nm)
{ strcpy(name, n); areacode = a; prefix = p; num = nm; }
};
// Input name and telephone number.
istream &operator>>(istream &stream, phonebook &o) {
cout << "Enter name: "; stream >> o.name;
cout << "Enter area code: "; stream >> o.areacode;
cout << "Enter prefix: "; stream >> o.prefix;
cout << "Enter number: "; stream >> o.num;
return stream; }
What’s RTTI?
What it is for?
Type identification
Inheritance hierarchy
String based method invocation
Exception handling
void main()
Mammal AnyMammal;
Cat cat;
Platypus platypus;
WhatMammal(AnyMammal);
WhatMammal(cat);
WhatMammal(platypus);
}
ob is referencing an object of type class Mammal
ob is referencing an object of type class Cat
ob is referencing an object of type class Platypus
Exception Handling
What is exception?
C++ can detect run-time errors, but does not have any idea
what to do about them. The user may know how to cope with
such errors but cannot detect them. The notion of an exception
is provided to help deal with such problems.
Exception Types
Synchronous Exceptions:
Errors such as out-of-range index, divide by zero,
and overflow,underflow belong to synchronous
exceptions
Asynchronous Exceptions:
The errors that are caused by events beyond the
control of the program such as keyboard interrupts,
disk failure,hardware malfunctions and so on on are
called asynchronous exceptions
try block
Exception object
catch block
try
{
……
throw exception; // block of statements
// which detects and
// throws an exception
}
void main() {
int a,b;
cout<<“Enter values of a and b \n";
cin>>a; cin>>b;
int x= a-b;
try
{
if(x!=0)
{
cout<<"Result (a/x) =" <<a/x<<"\n";
}
else
{ // there is an exception
throw (x); // throws int object
}
}
Throw point
Throw exception Invoke
function Function that causes
an exception
try block
catch block
void main() {
try { cout<< ” inside the try block \n”;
divide(20,10,30); // Invoke divide
divide(30,30,60); // Invoke divide
}
catch (int i) {
cout<< “ caught the exception \n “;
}
}
inside the try block
inside the function
Result = -3
Caught the exception
Throwing Mechanism
Catching Mechanism
For example:
catch ( …)
{
// statements for processing all exceptions
}
Rethrowing an Exception
Restricting Exceptions
If you don’t do this, the base class catch will also catch
all derived classes
Applying Exception
void main() {
void divide(double a, double b) double i, j;
{ do {
try { cout<< "Enter numerator(0 to stop):";
if(!b) throw b; // check for cin >> i;
divide-by-zero
cout << "Enter denominator: ";
cout << "Result: " << a/b;
cin >> j;
}
divide(i, j);
catch (double b) {
} while(i != 0);
cout << "Can't divide by zero;}
}
}
Containers
Algorithms
These functions are probably the most common way that individual
elements are added to a sequence container
One of the most common ways to access the elements within a container
is through an iterator
These iterators are very useful when accessing the contents of a container
Since associative containers link a key with its value, find() is how most
elements in such a container are located
#include <iostream.h>
#include <vector.h>
#include <ctype.h>
void main() {
vector<char> v(10); // create a vector of length 10
int i;
// display original size of v
cout << "Size = " << v.size() << endl;
// assign the elements of the vector some values
for(i=0; i<10; i++) v[i] = i + 'a';
// display contents of vector
cout << "Current Contents:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
Size = 10
Current Contents:
abcdefghij
Expanding vector
Size now = 20
Current contents:
abcdefghijklmnopqrst
Modified Contents:
ABCDEFGHIJKLMNOPQRST
#include <vector.h>
#include <ctype.h>
void main() {
vector<char> v(10); // create a vector of length 10
int i; vector<char>::iterator p; // create an iterator
// assign elements in vector a value
p = v.begin();
i = 0;
while(p != v.end())
*p++ = i++ + 'a';
#include <iostream.h>
#include <vector.h>
void main() {
vector<char> v(10); vector<char> v2;
char str[] = "<Vector>"; int i;
// initialize v
for(i=0; i<10; i++) v[i] = i + 'a';
// copy characters in str into v2
for(i=0; str[i]; i++) v2.push_back(str[i]);
// display original contents of vector
cout << "Original contents of v:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
vector<char>::iterator p = v.begin();
p += 2; // point to 3rd element
// insert 10 X's into v
v.insert(p, 10, 'X');
// display contents after insertion
cout << "Size after inserting X's = " << v.size() << endl;
cout << "Contents after insert:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
// remove those elements
p = v.begin();
p += 2; // point to 3rd element
v.erase(p, p+10); // remove next 10 elements
// Insert v2 into v
v.insert(p, v2.begin(), v2.end());
cout << "Size after v2's insertion = ";
cout << v.size() << endl;
cout << "Contents after insert:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
}
Original contents of v:
abcdefghij
Size after inserting X's = 20
Contents after insert:
abXXXXXXXXXXcdefghij
Size after erase = 10
Contents after erase:
abcdefghij
Size after v2's insertion = 18
Contents after insert:
ab<Vector>cdefghij
#include <vector.h>
#include <stdlib.h>
class DailyTemp { int temp;
public:
DailyTemp() { temp = 0; }
DailyTemp(int x) { temp = x; }
double get_temp() { return temp; }
};
Contents modified: 100 101 102 103 104 105 106 107 108 109
#include <list.h>
void main() {
list<int> lst; // create an empty list int i;
for(i=0; i<10; i++) lst.push_back(i);
cout << "Size = " << lst.size() << endl;
cout << "Contents: ";
list<int>::iterator p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
// change contents of list
p = lst.begin();
while(p != lst.end()) { *p = *p + 100; p++; }
cout << "Contents modified: ";
p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
}
push_front() vs Push_back()
Original contents:
130 10982 1090 11656 7117 17595 6415
#include <list.h> 22948 31126 9004
#include <stdlib.h> Sorted contents:
void main() { 130 1090 6415 7117 9004 10982 11656
list<int> lst; int i; 17595 22948 31126
// create a list of random integers
for(i=0; i<10; i++)
lst.push_back(rand());
cout << "Original contents:\n";
list<int>::iterator p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
// sort the list
lst.sort();
cout << "Sorted contents:\n";
p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
}
The new list is left in the invoking list, and the second
list is left empty
#include <list.h>
void main() {
list<int> lst1, lst2; int i;
for(i=0; i<10; i+=2) lst1.push_back(i);
for(i=1; i<11; i+=2) lst2.push_back(i);
cout << "Contents of lst1:\n";
list<int>::iterator p = lst1.begin();
while(p != lst1.end()) { cout << *p << " "; p++; }
cout << "Contents of lst2:\n";
p = lst2.begin();
while(p != lst2.end()) { cout << *p << " "; p++; }
// now, merge the two lists
lst1.merge(lst2); if(lst2.empty()) cout<<"lst2 is now empty";
#include <list.h>
#include <string.h>
class myclass {
int a, b,sum;
public:
myclass() { a = b = 0; }
myclass(int i, int j) {
a = i; b = j; sum = a + b; }
int getsum() { return sum; }
friend bool operator<(const myclass &o1,const myclass &o2);
};
bool operator<(const myclass &o1, const myclass &o2)
{ return o1.sum < o2.sum; }
First list: 0 2 4 6 8 10 12 14 16 18
Second list: 0 5 10 15 20 25 30 35 40 45
Merged list: 0 0 2 4 5 6 8 10 10 12 14 15 16 18 20 25 30 35 40 45
The power of a map is that you can look up a value given its key
For example, you could define a map that uses a person's name
as its key and stores that person's phone number as its value
A map can hold only unique keys; duplicate keys are not allowed
Here, Key is the data type of the keys, T is the data type of the
values being stored (mapped), and Comp is a function that
compares two keys which defaults to the standard less() utility
function object
The following comparison operators are defined for map
==, <, <=, !=, >, >=
#include <map.h>
#include <string.h>
class name { Tom 555-4533
char str[40]; Chris 555-9678
public:
John 555-8195
name() { strcpy(str, ""); }
name(char *s) { strcpy(str, s); } Rachel 555-0809
char *get() { return str; }
};
// Must define less than relative to name objects.
bool operator<(name a, name b)
{ return strcmp(a.get(), b.get()) < 0; }
void main() {
map<name, phoneNum> directory;
// put names and numbers into map
directory.insert(pair<name,phoneNum>(name("Tom"),
phoneNum("555-4533")));
directory.insert(pair<name,phoneNum>(name("Chris"),
phoneNum("555-9678")));
directory.insert(pair<name,phoneNum>(name("John"),
phoneNum("555-8195")));
directory.insert(pair<name,phoneNum>(name("Rachel"),
phoneNum("555-0809")));
Exploring Algorithm
Algorithm - Counting
#include <vector.h>
#include <algorithm.h>
This is a unary predicate that determines if number is divisible by 3
bool dividesBy3(int i) {
return i%3== 0? true: false; }
void main() {
vector<int> v; int i;
for(i=1; i < 20; i++) v.push_back(i);
cout << "Sequence:\n";
for(i=0; i<v.size(); i++)
cout << v[i] << " ";
i = count_if(v.begin(), v.end(), dividesBy3);
cout << i << " numbers are divisible by 3.\n";
}
Input sequence:
The STL is power programming.
Result after repacing spaces with colons:
The:STL:is:power:programming.
Reversing a Sequence
Initial: 0 1 2 3 4 5 6 7 8 9
Reversed: 9 8 7 6 5 4 3 2 1 0
The other reason for the using standard string class is safety
There are three reasons for the inclusion of the standard string
class
consistency (a string now defines a data type),
convenience ( standard C++ operators can be applied)
safety (array boundaries will not be overrun)
To access to the string class, you must include <string> header
The string class is very large, with many constructors and
member functions
Operator Meaning
= Assignment
+ Concatenation
+= Concatenation
assignment
== Equality
!= Inequality
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
[] Subscripting
<< ,>> Output , Input
#include <string.h>
void main(){
string str1("String handling C++ style.");
string str2("STL Power"); cout << "Initial strings:\n";
cout << "str1: " << str1 << "str2: " << str2 << "\n\n";
// demonstrate insert()
cout <<"Insert str2 into str1:\n"; str1.insert(6, str2);cout << str1;
// demonstrate erase()
cout << "Remove 9 characters from str1:\n";
str1.erase(6, 9); cout << str1 <<"\n\n";
// demonstrate replace
cout << "Replace 8 characters in str1 with str2:\n";
str1.replace(7, 8, str2); cout << str1 << endl;
}
Initial strings:
str1: String handling C++ style.
str2: STL Power
i = s1.find("Pure");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size()); cout << s2;
}
// find list "of"
i = s1.rfind("of");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size()); cout << s2;
}
}
Match found at 15
Remaining string is:
Strong of Body, Pure of Heart
Match found at 31
Remaining string is:
Pure of Heart
Match found at 36
Remaining string is:
of Heart