Lecture 19
Lecture 19
Puru
with
CS101 TAs and Staff
• Member functions
− New feature introduced in C++
− Actions/operations that effect the entity
Example
struct Book{
char title[50];
double price;
};
struct Point{
double x,y;
};
struct Disk{
Point center; // contains Point
double radius;
};
Disk d;
d.radius = 10;
d.center = {15, 20};
// sets the x {member of center member of d
int main(){
Point p={10,20}, q={50,60};
Point r = midpoint(p,q);
cout << r.x << endl;
cout << midpoint(p,q).x << endl;
}
int main(){
Point p={10,20}, q={50,60};
Point r = midpoint(p,q);
cout << r.x << endl;
}
• In C++, you can make the functions a part of the struct definition
itself.
Such functions are called member functions.
struct Queue{
int elements[N], nwaiting,front;
bool insert(int v){
…
}
struct Queue{
…
bool insert(int v){
if(nWaiting >= N) return false;
elements[(front + nWaiting)%N] = v; nWaiting++;
return true;
}
};
struct Queue{
…
bool remove(int &v){
if(nWaiting < 1) return false;
v=elements[front]; front=(front+1)%N; nWaiting--;
return true;
}
};
• Why useful?
};
Queue z=updateQueue(r);
}
~Queue(){ //Destructor
if(nWaiting>0) cout << “Warning:”
<<“ non-empty queue being destroyed.”
<< endl;
}
};
int main(){
V3 u(1,2,3), a(4,5,6), s;
double t=10;
s = u*t + a*t*t*0.5;
cout << s.x <<‘ ‘<< s.y <<‘ ‘
<< s.z << endl;
}
• dptr = &d1;
• (*dptr).radius = 5; //changes the radius of d1
• Operator ->
– (*x).y is same as x->y
• dptr->radius = 5; // same effect as above
struct Disk2{
double radius;
Point *centerptr;
}
Point p={10,20};
Disk2 d;
d.centerptr = &p;
cout << d.centerptr->x << endl; // will print 10.
• Within the body of a member function, the keyword this points to the receiver
i.e., the struct on which the member function has been invoked.
struct V3{
double x, y, z;
double length(){
return sqrt(this->x * this->x
+ this->y * this->y
+ this->z * this->z);
}
}
};
// only the relevant elements are copied
public:
Queue(){ … }
bool insert(int v){
..
}
bool remove(int &v){
..
}
};
class Queue{
int elements[N], nWaiting, front;
public:
Queue(){…}
bool remove(int &v){…}
bool insert(int v){…}
};
repeat(10){
int v;
infile >> v;
outfile << v;
}
// f1.txt must begin with 10 numbers. These will be read and
// written to file f2.txt
}
string message;
getline(cin, message);
int mx = message.size()-1;
while (mx >= 0) { Character at
position mx in
cout << message[mx]; string
--mx; message
}
• mx updated in a completely predictable way
• Ideal candidate to write as for loop
Autumn 2019 CS101@CSE IIT Bombay 63
Finding needles in a haystack
while (true) {
ans += base/fac;
base *= x;
fac *= (++ix);
if (base/fac < epsilon) {
break; Terminates
} immediately
cout << (base/fac) << endl;enclosing
while loop
}
Autumn 2019 CS101@CSE IIT Bombay 69