KEMBAR78
Object Oriented Programming (OOP) using C++ - Lecture 2 | PDF
Object Oriented
Programming using C++
By Mohamed Gamal
© Mohamed Gamal 2024
The topics of today’s lecture:
Agenda
#include <iostream>
using namespace std;
class smallobj {
private:
int somedata;
public:
void setdata(int d) {
somedata = d;
}
void showdata() {
cout << "Data is " << somedata << endl;
}
};
int main() {
smallobj s1;
s1.setdata(1066);
s1.showdata();
return 0;
}
#include <iostream>
using namespace std;
//English Distance class
class Distance {
private:
int feet;
float inches;
public:
//constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() { //get length from user
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() { //display distance
cout << feet << "' - " << inches << '"';
}
void add_dist(Distance, Distance); //declaration
};
//add lengths d2 and d3
void Distance::add_dist(Distance d2, Distance d3) {
inches = d2.inches + d3.inches; //add the inches
feet = 0; //(for possible carry)
if (inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet by 1
}
feet += d2.feet + d3.feet; //add the feet
}
int main()
{
Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25); //define and initialize dist2
dist1.getdist(); //get dist1 from user
dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2
//display all lengths
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
cout << "ndist3 = ";
dist3.showdist();
cout << endl;
return 0;
}
Member Functions
Defined Outside the
Class
– So far we’ve seen member functions
defined inside the class definition.
– However, we can define member
functions outsize the class.
#include <iostream>
using namespace std;
// English Distance class
class Distance
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0) //constructor (no args)
{ }
Distance(int ft, float in) : feet(ft), inches(in) //constructor (two args)
{ }
void getdist() {
cout << "nEnter feet : ";
cin >> feet;
cout << "Enter inches : ";
cin >> inches;
}
void showdist() {
cout << feet << "' - " << inches << '"';
}
void add_dist(Distance, Distance); //declaration
};
void Distance::add_dist(Distance d2, Distance d3)
{
inches = d2.inches + d3.inches; //add the inches
feet = 0; //(for possible carry)
if (inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet by 1
}
feet += d2.feet + d3.feet; //add the feet
}
Example
Objects as arguments
Explanation
const Member Functions
– A const member function guarantees that it will never modify any of its class’s
member data.
– A function is made into a constant function by placing the keyword const after
the declarator but before the function body.
class Example
{
private:
int alpha;
public:
void nonFunc() //non-const member function
{
alpha = 99; //OK
}
void conFunc() const //const member function
{
alpha = 99; //ERROR: can’t modify a member
}
};
Member functions that do nothing
but acquire data from an object are
obvious candidates for being made
const, because they don’t need to
modify any data.
const Objects
– In several example programs, we’ve seen that we can apply const to
variables of basic types such as int to keep them from being modified.
– In a similar way, we can apply const to objects of classes. When an object
is declared as const, you can’t modify it.
– It follows that you can use only const member functions with it, because
they’re the only ones that guarantee not to modify it.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() {
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() const {
cout << feet << "' - " << inches << '"';
}
};
int main()
{
const Distance football(300, 0);
// football.getdist(); //ERROR: getdist() not const
cout << "football = ";
football.showdist(); //OK
cout << endl;
return 0;
}
const
Objects
Example
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
//constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() {
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() {
cout << feet << "' - " << inches << '"';
}
Distance add_dist(Distance); //add
};
//--------------------------------------------------------------
//add this distance to d2, return the sum
Distance Distance::add_dist(Distance d2)
{
Distance temp; //temporary variable
temp.inches = inches + d2.inches; //add the inches
if (temp.inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
temp.inches -= 12.0; //by 12.0 and
temp.feet = 1; //increase feet by 1
}
temp.feet += feet + d2.feet; //add the feet
return temp;
}
int main()
{
Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25); //define, initialize dist2
dist1.getdist(); //get dist1 from user
dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2
//display all lengths
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
cout << "ndist3 = ";
dist3.showdist();
cout << endl;
return 0;
}
Returning
Objects
from
Functions
#include <iostream>
using namespace std;
enum Suit { clubs, diamonds, hearts, spades };
const int jack = 11; //from 2 to 10 are
const int queen = 12; //integers without names
const int king = 13;
const int ace = 14;
class card
{
private:
int number; //2 to 10, jack, queen, king, ace
Suit suit; //clubs, diamonds, hearts, spades
public:
card() //constructor (no args)
{ }
//constructor (two args)
card(int n, Suit s) : number(n), suit(s)
{ }
void display(); //display card
bool isEqual(card); //same as another card?
};
void card::display() //display the card
{
if (number >= 2 && number <= 10)
cout << number << " of ";
else
switch (number)
{
case jack:
cout << "jack of ";
break;
case queen:
cout << "queen of ";
break;
case king:
cout << "king of ";
break;
case ace:
cout << "ace of ";
break;
}
switch (suit)
{
case clubs: cout << "clubs"; break;
case diamonds: cout << "diamonds"; break;
case hearts: cout << "hearts"; break;
case spades: cout << "spades"; break;
}
}
bool card::isEqual(card c2) //return true if cards equal
{
return (number == c2.number && suit == c2.suit) ? true : false;
}
int main()
{
card temp, chosen, prize; //define various cards
int position;
card card1(7, clubs); //define & initialize card1
cout << "nCard 1 is the ";
card1.display(); //display card1
card card2(jack, hearts); //define & initialize card2
cout << "nCard 2 is the ";
card2.display(); //display card2
card card3(ace, spades); //define & initialize card3
cout << "nCard 3 is the ";
card3.display(); //display card3
prize = card3; //prize is the card to guess
cout << "nI'm swapping card 1 and card 3";
temp = card3;
card3 = card1;
card1 = temp;
cout << "nI'm swapping card 2 and card 3";
temp = card3;
card3 = card2;
card2 = temp;
cout << "nI'm swapping card 1 and card 2";
temp = card2;
card2 = card1;
card1 = temp;
cout << "nNow, where (1, 2, or 3) is the ";
prize.display(); //display prize card
cout << " ? ";
cin >> position; //get user’s guess of position
switch (position)
{ //set chosen to user’s choice
case 1:
chosen = card1;
break;
case 2:
chosen = card2;
break;
case 3:
chosen = card3;
break;
}
if (chosen.isEqual(prize)) //is chosen card the prize?
cout << "That's right! You win!";
else
cout << "Sorry. You lose.";
cout << " You chose the ";
chosen.display(); //display chosen card
cout << endl;
return 0;
}
A Card-
Game
Example
The Standard C++ string Class
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, nickname, address;
string greeting("Hello, ");
cout << "Enter your full name : ";
getline(cin, full_name); //reads embedded blanks
cout << "Your full name is : " << full_name << endl;
cout << "Enter your nickname : ";
cin >> nickname; //input to string object
greeting += nickname; //append name to greeting
cout << greeting << endl; //output: "Hello, Mohamed"
cout << "Enter your address on separate linesn";
cout << "Terminate with '$'n";
getline(cin, address, '$'); //reads multiple lines
cout << "Your address is : " << address << endl;
return 0;
}
Example 2
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("Man"); //initialize
string s2 = "Beast"; //initialize
string s3;
s3 = s1; //assign
cout << "s3 = " << s3 << endl;
s3 = "Neither " + s1 + " nor "; //concatenate
s3 += s2; //concatenate
cout << "s3 = " << s3 << endl;
s1.swap(s2); //swap s1 and s2
cout << s1 << " nor " << s2 << endl;
return 0;
}
#include <iostream>
#include <cstring> // for strcpy(), strcat()
using namespace std;
class String
{
private:
enum { SZ = 80 }; //max size of Strings
char str[SZ]; //array
public:
String() //constructor, no args
{
str[0] = '0’;
}
String(char s[]) //constructor, one arg
{
strcpy(str, s);
}
void display() //display string
{
cout << str;
}
void concat(String s2) //add arg string to this string
{
if (strlen(str) + strlen(s2.str) < SZ)
strcat(str, s2.str);
else
cout << "nString is too long!";
}
};
int main()
{
String s1("Merry Christmas!"); //uses constructor 2
String s2 = "Season's Greetings!"; //alternate form of 2
String s3; //uses constructor 1
//display them all
cout << "ns1 = ";
s1.display();
cout << "ns2 = ";
s2.display();
cout << "ns3 = ";
s3.display();
s3 = s1; //assignment
cout << "ns3 = "; //display s3 before
s3.display();
s3.concat(s2); //concatenation
cout << "ns3 = "; //display s3 after
s3.display();
return 0;
}
String
Class
Example 3
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("Quick! Send for Count Graystone.");
string s2("Lord");
string s3("Don't ");
s1.erase(0, 7); //remove "Quick! " → "Send for Count Graystone."
s1.replace(16, 5, s2); //replace "Count" with "Lord"
s1.replace(7, 1, "s"); //replace 'S' with 's’
s1.insert(0, s3); //insert "Don't " at beginning
s1.erase(s1.size() - 1, 1); //remove '.' (30)
s1.append(3, '!'); //append "!!!"
int x = s1.find(' '); //find a space (6)
while (x < s1.size()) //loop while spaces remain
{
s1.replace(x, 1, "/"); //replace with slash
x = s1.find(' '); //find next space (11, 15, 21)
}
cout << "s1: " << s1 << endl;
return 0;
}
String Class
Example 4
#include <iostream>
#include <string>
using namespace std;
int main() {
string aName = "Mohamed";
string userName;
cout << "Enter your first name: ";
cin >> userName;
if (userName == aName) //operator ==
cout << "Greetings, " << userName << endl;
else if (userName < aName) //operator <
cout << "You come before Mohamed" << endl;
else
cout << "You come after Mohamed" << endl;
//compare() function
int n = userName.compare(0, 2, aName, 0, 2);
cout << "The first two letters of your name ";
if (n == 0)
cout << "match ";
else if (n < 0)
cout << "come before ";
else
cout << "come after ";
cout << aName.substr(0, 2) << endl;
return 0;
}
String Class
Example 5
compare()
#include <iostream>
#include <string>
using namespace std;
int main()
{
char charray[80];
string word;
cout << "Enter a word: ";
cin >> word;
//getline(cin, word);
int wlen = word.length(); //length of string object
// int wlen = word.size();
cout << "One character at a time: ";
for (int j = 0; j < wlen; j++)
cout << word.at(j); //exception if out-of-bounds
// cout << word[j]; //no warning if out-of-bounds
word.copy(charray, wlen, 0); //copy string object to array
charray[wlen] = 0; //terminate with ‘0’
cout << "nArray contains: " << charray << endl;
return 0;
}
String Class
Example 6
Accessing Characters
in string Objects using
the overloaded []
operator
Structures and Classes
– The only formal difference between class and struct is that in a class the
members are private by default, while in a structure they are public by
default.
class foo {
private:
int data1;
public:
void func();
};
class foo {
private:
int data1;
public:
void func();
};
#include <iostream>
using namespace std;
class Stack
{
private:
enum { MAX = 10 }; //(non-standard syntax)
int st[MAX]; //stack: array of integers
int top; //number of top of stack
public:
Stack() //constructor
{
top = 0;
}
void push(int var) //put number on stack
{
st[++top] = var;
}
int pop() //take number off stack
{
return st[top--];
}
};
int main()
{
Stack s1;
s1.push(11);
s1.push(22);
cout << "1: " << s1.pop() << endl; //22
cout << "2: " << s1.pop() << endl; //11
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
cout << "3: " << s1.pop() << endl; //66
cout << "4: " << s1.pop() << endl; //55
cout << "5: " << s1.pop() << endl; //44
cout << "6: " << s1.pop() << endl; //33
return 0;
}
Stack
Operator Overloading
– Operator overloading gives you the opportunity to redefine the C++ language.
– The term operator overloading refers to giving the normal C++ operators such
as +, *, <=, and +=, additional meanings when they are applied to user-defined
data types.
– Another kind of operation, data type conversion, is closely connected with
operator overloading.
– C++ handles the conversion of simple types, such as int and float,
automatically; but conversions involving user-defined types require some work
on the programmer’s part.
1) Unary Operator Overloading
– Unary operators act on only one operand. (An operand is simply a
variable acted on by an operator).
– Examples of unary operators are the increment and decrement
operators ++ and --, and the unary minus, as in -33
#include <iostream>
using namespace std;
class Counter {
private:
unsigned int count;
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{
return count;
}
void operator ++ () //increment (prefix)
{
count++;
}
};
int main() {
Counter c1, c2; //define and initialize
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 1
A subtle defect
if you use the
statement:
'c1 = ++c2'
(Prefix)
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{
return count;
}
Counter operator ++ () //increment count
{
++count; //increment count
Counter temp; //make a temporary Counter
temp.count = count; //give it same value as this obj
return temp; //return the copy
}
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 2
Solution
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() //return count
{
return count;
}
Counter operator ++ () //increment count
{
++count; // increment count, then return
return Counter(count); // an unnamed temporary object
} // initialized to this count
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 2
Solution 2
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() const //return count
{
return count;
}
Counter operator ++ () //increment count (prefix)
{
return Counter(++count);
}
Counter operator ++ (int) //increment count (postfix)
{
return Counter(count++);
}
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2 (prefix)
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
c2 = c1++; //c1=3, c2=2 (postfix)
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 3
(Prefix and Postfix)
int is a signal to indicate postfix
✓ You can use this same approach
with the decrement operator (--)
as well.
2) Overloading Binary Operators
– Binary operators can be overloaded just as easily as unary operators.
– We’ll look at examples that overload arithmetic operators, comparison
operators, and arithmetic assignment operators.
#include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() //get length from user
{
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() const //display distance
{
cout << feet << "' - " << inches << '"';
}
Distance operator + (Distance) const; //add 2 distances
};
//add this distance to d2
Distance Distance::operator + (Distance d2) const //return sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if (i >= 12.0) //if total exceeds 12.0
{ //then decrease inches by 12.0 and increase feet by 1
i -= 12.0;
f++;
}
return Distance(f, i); //return a temporary Distance initialized to sum
}
int main()
{
Distance dist1, dist3, dist4; //define distances
dist1.getdist(); //get dist1 from user
Distance dist2(11, 6.25); //define, initialize dist2
dist3 = dist1 + dist2; //single ‘+’ operator
dist4 = dist1 + dist2 + dist3; //multiple ‘+’ operators
//display all lengths
cout << "dist1 = "; dist1.showdist(); cout << endl;
cout << "dist2 = "; dist2.showdist(); cout << endl;
cout << "dist3 = "; dist3.showdist(); cout << endl;
cout << "dist4 = "; dist4.showdist(); cout << endl;
return 0;
}
Example 1 Output:
#include <iostream>
#include <string.h> //for strcpy(), strcat()
#include <stdlib.h> //for exit()
using namespace std;
class String //user-defined string type
{
private:
enum { SZ = 80 }; //size of String objects
char str[SZ]; //holds a string
public:
String() //constructor, no args
{
strcpy(str, "");
}
String(char s[]) //constructor, one arg
{
strcpy(str, s);
}
void display() const //display the String
{
cout << str;
}
String operator + (String ss) const //add Strings
{
String temp; //make a temporary String
if (strlen(str) + strlen(ss.str) < SZ)
{
strcpy(temp.str, str); //copy this string to temp
strcat(temp.str, ss.str); //add the argument string
}
else
{
cout << "nString overflow"; exit(1);
}
return temp; //return temp String
}
};
int main()
{
String s1 = "nHello, Mohamed!"; //uses constructor 2
String s2 = "Welcome abroad."; //uses constructor 2
String s3; //uses constructor 1
s1.display(); //display strings
s2.display();
s3.display();
s3 = s1 + s2; //add s2 to s1, assign to s3
s3.display(); //display s3
return 0;
}
Example 2
(String Class)
3) Overloading Comparison Operator
– The following example overloads the less than operator (<) in the
Distance class in order to be used in comparing two distances.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() //get length from user
{
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() const //display distance
{
cout << feet << "' - " << inches << '"';
}
bool operator < (Distance d2) const //compare distances
{
float bf1 = feet + inches / 12;
float bf2 = d2.feet + d2.inches / 12;
return (bf1 < bf2) ? true : false;
}
};
int main()
{
Distance dist1;
dist1.getdist();
Distance dist2(6, 2.5);
//display distances
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
if (dist1 < dist2) //overloaded '<' operator
cout << "ndist1 is less than dist2";
else
cout << "ndist1 is greater than(or equal to) dist2";
return 0;
}
Example 1
Two distances comparison
using the < operator
#include <iostream>
#include <string.h> //for strcmp()
using namespace std;
class String //user-defined string type
{
private:
enum { SZ = 80 }; //size of String objects
char str[SZ]; //holds a string
public:
String() {
strcpy(str, "");
}
String(char s[]) {
strcpy(str, s);
}
void display() const //display a String
{
cout << str;
}
void getstr() //read a string
{
cin.get(str, SZ);
}
bool operator == (String ss) const //check for equality
{
return (strcmp(str, ss.str) == 0) ? true : false;
}
};
int main()
{
String s1 = "yes";
String s2 = "no";
String s3;
cout << "nEnter 'yes' or 'no': ";
s3.getstr(); //get String from user
if (s3 == s1) //compare with "yes"
cout << "You typed 'yes'.n";
else if (s3 == s2) //compare with "no"
cout << "You typed 'no'.n";
else
cout << "You didn't follow instructions.n";
return 0;
}
Example 2
String Comparison using
== operator
#include <iostream>
#include <string.h> //for strlen()
using namespace std;
class String {
private:
enum { SZ = 80 };
char str[SZ];
public:
String() {
strcpy(str, "");
}
String(char s[]) {
strcpy(str, s);
}
void display() const {
cout << str;
}
void getstr() {
cin.get(str, SZ);
}
bool operator < (String ss) const {
return strlen(str) < strlen(ss.str);
}
};
int main() {
String s1 = "Mohamed";
String s2 = "Ahmed";
if (s1 < s2) {
cout << "The length of ";
s1.display();
cout << " is less than ";
s2.display();
} else {
cout << "The length of ";
s1.display();
cout << " is greater than ";
s2.display();
}
return 0;
}
Example 3
String Comparison using
< operator
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() {
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() const {
cout << feet << "' - " << inches << '"';
}
void operator += (Distance d2) {
feet += d2.feet; //add the feet
inches += d2.inches; //add the inches
if (inches >= 12.0) //if total exceeds 12.0
{
inches -= 12.0;
feet++;
}
// return Distance(feet, inches);
}
};
int main()
{
Distance dist1;
dist1.getdist();
cout << "ndist1 = "; dist1.showdist();
Distance dist2(11, 6.25);
cout << "ndist2 = "; dist2.showdist();
dist1 += dist2; //add the two distances
cout << "nAfter addition, dist1 = "; dist1.showdist();
return 0;
}
Example 4
Overloaded += assignment
operator
#include <iostream>
#include <process.h> // for exit()
using namespace std;
const int LIMIT = 5;
class safearay
{
private:
int arr[LIMIT];
public:
void putel(int n, int elvalue) //set value of element
{
if (n < 0 || n >= LIMIT) {
cout << "Index out of bounds.";
exit(1);
}
arr[n] = elvalue;
}
int getel(int n) const //get value of element
{
if (n < 0 || n >= LIMIT)
{
cout << "Index out of bounds.";
exit(1);
}
return arr[n];
}
};
int main()
{
safearay sa1;
for (int i = 0; i < LIMIT; i++) // insert elements
sa1.putel(i, i * 10);
for (int i = 0; i < LIMIT; i++) // display elements
cout << "Element " << i << " is " << sa1.getel(i) << endl;
return 0;
}
Safe Array
Class
Example 1
#include <iostream>
#include <process.h> //for exit()
using namespace std;
const int LIMIT = 5; //array size
class safearay
{
private:
int arr[LIMIT];
public:
int& operator [] (int n) //note: return by reference
{
if (n < 0 || n >= LIMIT)
{
cout << "Index out of bounds.";
exit(1);
}
return arr[n];
}
};
int main()
{
safearay sa1;
for (int i = 0; i < LIMIT; i++) //insert elements
sa1[i] = i * 10;
for (int i = 0; i < LIMIT; i++) //display elements
cout << "Element " << i << " is " << sa1[i] << endl;
return 0;
}
Safe Array
Class
Example 2
Overloading the subscript [ ]
operator
The Standard C++ string Class
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, nickname, address;
string greeting("Hello, ");
cout << "Enter your full name : ";
getline(cin, full_name); //reads embedded blanks
cout << "Your full name is : " << full_name << endl;
cout << "Enter your nickname : ";
cin >> nickname; //input to string object
greeting += nickname; //append name to greeting
cout << greeting << endl; //output: "Hello, Mohamed"
cout << "Enter your address on separate linesn";
cout << "Terminate with '$'n";
getline(cin, address, '$'); //reads multiple lines
cout << "Your address is : " << address << endl;
return 0;
}
Example
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("Man"); //initialize
string s2 = "Beast"; //initialize
string s3;
s3 = s1; //assign
cout << "s3 = " << s3 << endl;
s3 = "Neither " + s1 + " nor "; //concatenate
s3 += s2; //concatenate
cout << "s3 = " << s3 << endl;
s1.swap(s2); //swap s1 and s2
cout << s1 << " nor " << s2 << endl;
return 0;
}
Operator Overloading – Summary
– Use similar meanings (i.e., semantics), you could overload the + sign to perform
subtraction, for example, but that would hardly make your listings more
comprehensible.
– You can’t overload a binary operator to be a unary operator, or vice versa.
– Not all operators can be overloaded, the following operators cannot be
overloaded:
▪ the member access or dot operator (.)
▪ the scope resolution operator (::)
▪ the conditional operator (?:)
▪ the pointer-to-member operator (->)
▪ you can’t create new operators (like *&) and try to overload them; only existing operators
can be overloaded.
End of lecture 2
ThankYou!

Object Oriented Programming (OOP) using C++ - Lecture 2

  • 1.
    Object Oriented Programming usingC++ By Mohamed Gamal © Mohamed Gamal 2024
  • 2.
    The topics oftoday’s lecture: Agenda
  • 4.
    #include <iostream> using namespacestd; class smallobj { private: int somedata; public: void setdata(int d) { somedata = d; } void showdata() { cout << "Data is " << somedata << endl; } }; int main() { smallobj s1; s1.setdata(1066); s1.showdata(); return 0; }
  • 5.
    #include <iostream> using namespacestd; //English Distance class class Distance { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() { //get length from user cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() { //display distance cout << feet << "' - " << inches << '"'; } void add_dist(Distance, Distance); //declaration }; //add lengths d2 and d3 void Distance::add_dist(Distance d2, Distance d3) { inches = d2.inches + d3.inches; //add the inches feet = 0; //(for possible carry) if (inches >= 12.0) //if total exceeds 12.0, { //then decrease inches inches -= 12.0; //by 12.0 and feet++; //increase feet by 1 } feet += d2.feet + d3.feet; //add the feet } int main() { Distance dist1, dist3; //define two lengths Distance dist2(11, 6.25); //define and initialize dist2 dist1.getdist(); //get dist1 from user dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2 //display all lengths cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); cout << "ndist3 = "; dist3.showdist(); cout << endl; return 0; }
  • 6.
    Member Functions Defined Outsidethe Class – So far we’ve seen member functions defined inside the class definition. – However, we can define member functions outsize the class.
  • 7.
    #include <iostream> using namespacestd; // English Distance class class Distance { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) //constructor (no args) { } Distance(int ft, float in) : feet(ft), inches(in) //constructor (two args) { } void getdist() { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() { cout << feet << "' - " << inches << '"'; } void add_dist(Distance, Distance); //declaration }; void Distance::add_dist(Distance d2, Distance d3) { inches = d2.inches + d3.inches; //add the inches feet = 0; //(for possible carry) if (inches >= 12.0) //if total exceeds 12.0, { //then decrease inches inches -= 12.0; //by 12.0 and feet++; //increase feet by 1 } feet += d2.feet + d3.feet; //add the feet } Example Objects as arguments
  • 8.
  • 9.
    const Member Functions –A const member function guarantees that it will never modify any of its class’s member data. – A function is made into a constant function by placing the keyword const after the declarator but before the function body. class Example { private: int alpha; public: void nonFunc() //non-const member function { alpha = 99; //OK } void conFunc() const //const member function { alpha = 99; //ERROR: can’t modify a member } }; Member functions that do nothing but acquire data from an object are obvious candidates for being made const, because they don’t need to modify any data.
  • 10.
    const Objects – Inseveral example programs, we’ve seen that we can apply const to variables of basic types such as int to keep them from being modified. – In a similar way, we can apply const to objects of classes. When an object is declared as const, you can’t modify it. – It follows that you can use only const member functions with it, because they’re the only ones that guarantee not to modify it.
  • 11.
    #include <iostream> using namespacestd; class Distance { private: int feet; float inches; public: Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() const { cout << feet << "' - " << inches << '"'; } }; int main() { const Distance football(300, 0); // football.getdist(); //ERROR: getdist() not const cout << "football = "; football.showdist(); //OK cout << endl; return 0; } const Objects Example
  • 12.
    #include <iostream> using namespacestd; class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() { cout << feet << "' - " << inches << '"'; } Distance add_dist(Distance); //add }; //-------------------------------------------------------------- //add this distance to d2, return the sum Distance Distance::add_dist(Distance d2) { Distance temp; //temporary variable temp.inches = inches + d2.inches; //add the inches if (temp.inches >= 12.0) //if total exceeds 12.0, { //then decrease inches temp.inches -= 12.0; //by 12.0 and temp.feet = 1; //increase feet by 1 } temp.feet += feet + d2.feet; //add the feet return temp; } int main() { Distance dist1, dist3; //define two lengths Distance dist2(11, 6.25); //define, initialize dist2 dist1.getdist(); //get dist1 from user dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2 //display all lengths cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); cout << "ndist3 = "; dist3.showdist(); cout << endl; return 0; } Returning Objects from Functions
  • 14.
    #include <iostream> using namespacestd; enum Suit { clubs, diamonds, hearts, spades }; const int jack = 11; //from 2 to 10 are const int queen = 12; //integers without names const int king = 13; const int ace = 14; class card { private: int number; //2 to 10, jack, queen, king, ace Suit suit; //clubs, diamonds, hearts, spades public: card() //constructor (no args) { } //constructor (two args) card(int n, Suit s) : number(n), suit(s) { } void display(); //display card bool isEqual(card); //same as another card? }; void card::display() //display the card { if (number >= 2 && number <= 10) cout << number << " of "; else switch (number) { case jack: cout << "jack of "; break; case queen: cout << "queen of "; break; case king: cout << "king of "; break; case ace: cout << "ace of "; break; } switch (suit) { case clubs: cout << "clubs"; break; case diamonds: cout << "diamonds"; break; case hearts: cout << "hearts"; break; case spades: cout << "spades"; break; } } bool card::isEqual(card c2) //return true if cards equal { return (number == c2.number && suit == c2.suit) ? true : false; } int main() { card temp, chosen, prize; //define various cards int position; card card1(7, clubs); //define & initialize card1 cout << "nCard 1 is the "; card1.display(); //display card1 card card2(jack, hearts); //define & initialize card2 cout << "nCard 2 is the "; card2.display(); //display card2 card card3(ace, spades); //define & initialize card3 cout << "nCard 3 is the "; card3.display(); //display card3 prize = card3; //prize is the card to guess cout << "nI'm swapping card 1 and card 3"; temp = card3; card3 = card1; card1 = temp; cout << "nI'm swapping card 2 and card 3"; temp = card3; card3 = card2; card2 = temp; cout << "nI'm swapping card 1 and card 2"; temp = card2; card2 = card1; card1 = temp; cout << "nNow, where (1, 2, or 3) is the "; prize.display(); //display prize card cout << " ? "; cin >> position; //get user’s guess of position switch (position) { //set chosen to user’s choice case 1: chosen = card1; break; case 2: chosen = card2; break; case 3: chosen = card3; break; } if (chosen.isEqual(prize)) //is chosen card the prize? cout << "That's right! You win!"; else cout << "Sorry. You lose."; cout << " You chose the "; chosen.display(); //display chosen card cout << endl; return 0; } A Card- Game Example
  • 15.
    The Standard C++string Class #include <iostream> #include <string> //for string class using namespace std; int main() { //objects of string class string full_name, nickname, address; string greeting("Hello, "); cout << "Enter your full name : "; getline(cin, full_name); //reads embedded blanks cout << "Your full name is : " << full_name << endl; cout << "Enter your nickname : "; cin >> nickname; //input to string object greeting += nickname; //append name to greeting cout << greeting << endl; //output: "Hello, Mohamed" cout << "Enter your address on separate linesn"; cout << "Terminate with '$'n"; getline(cin, address, '$'); //reads multiple lines cout << "Your address is : " << address << endl; return 0; }
  • 16.
    Example 2 #include <iostream> #include<string> using namespace std; int main() { string s1("Man"); //initialize string s2 = "Beast"; //initialize string s3; s3 = s1; //assign cout << "s3 = " << s3 << endl; s3 = "Neither " + s1 + " nor "; //concatenate s3 += s2; //concatenate cout << "s3 = " << s3 << endl; s1.swap(s2); //swap s1 and s2 cout << s1 << " nor " << s2 << endl; return 0; }
  • 17.
    #include <iostream> #include <cstring>// for strcpy(), strcat() using namespace std; class String { private: enum { SZ = 80 }; //max size of Strings char str[SZ]; //array public: String() //constructor, no args { str[0] = '0’; } String(char s[]) //constructor, one arg { strcpy(str, s); } void display() //display string { cout << str; } void concat(String s2) //add arg string to this string { if (strlen(str) + strlen(s2.str) < SZ) strcat(str, s2.str); else cout << "nString is too long!"; } }; int main() { String s1("Merry Christmas!"); //uses constructor 2 String s2 = "Season's Greetings!"; //alternate form of 2 String s3; //uses constructor 1 //display them all cout << "ns1 = "; s1.display(); cout << "ns2 = "; s2.display(); cout << "ns3 = "; s3.display(); s3 = s1; //assignment cout << "ns3 = "; //display s3 before s3.display(); s3.concat(s2); //concatenation cout << "ns3 = "; //display s3 after s3.display(); return 0; } String Class Example 3
  • 18.
    #include <iostream> #include <string> usingnamespace std; int main() { string s1("Quick! Send for Count Graystone."); string s2("Lord"); string s3("Don't "); s1.erase(0, 7); //remove "Quick! " → "Send for Count Graystone." s1.replace(16, 5, s2); //replace "Count" with "Lord" s1.replace(7, 1, "s"); //replace 'S' with 's’ s1.insert(0, s3); //insert "Don't " at beginning s1.erase(s1.size() - 1, 1); //remove '.' (30) s1.append(3, '!'); //append "!!!" int x = s1.find(' '); //find a space (6) while (x < s1.size()) //loop while spaces remain { s1.replace(x, 1, "/"); //replace with slash x = s1.find(' '); //find next space (11, 15, 21) } cout << "s1: " << s1 << endl; return 0; } String Class Example 4
  • 19.
    #include <iostream> #include <string> usingnamespace std; int main() { string aName = "Mohamed"; string userName; cout << "Enter your first name: "; cin >> userName; if (userName == aName) //operator == cout << "Greetings, " << userName << endl; else if (userName < aName) //operator < cout << "You come before Mohamed" << endl; else cout << "You come after Mohamed" << endl; //compare() function int n = userName.compare(0, 2, aName, 0, 2); cout << "The first two letters of your name "; if (n == 0) cout << "match "; else if (n < 0) cout << "come before "; else cout << "come after "; cout << aName.substr(0, 2) << endl; return 0; } String Class Example 5 compare()
  • 20.
    #include <iostream> #include <string> usingnamespace std; int main() { char charray[80]; string word; cout << "Enter a word: "; cin >> word; //getline(cin, word); int wlen = word.length(); //length of string object // int wlen = word.size(); cout << "One character at a time: "; for (int j = 0; j < wlen; j++) cout << word.at(j); //exception if out-of-bounds // cout << word[j]; //no warning if out-of-bounds word.copy(charray, wlen, 0); //copy string object to array charray[wlen] = 0; //terminate with ‘0’ cout << "nArray contains: " << charray << endl; return 0; } String Class Example 6 Accessing Characters in string Objects using the overloaded [] operator
  • 21.
    Structures and Classes –The only formal difference between class and struct is that in a class the members are private by default, while in a structure they are public by default. class foo { private: int data1; public: void func(); }; class foo { private: int data1; public: void func(); };
  • 22.
    #include <iostream> using namespacestd; class Stack { private: enum { MAX = 10 }; //(non-standard syntax) int st[MAX]; //stack: array of integers int top; //number of top of stack public: Stack() //constructor { top = 0; } void push(int var) //put number on stack { st[++top] = var; } int pop() //take number off stack { return st[top--]; } }; int main() { Stack s1; s1.push(11); s1.push(22); cout << "1: " << s1.pop() << endl; //22 cout << "2: " << s1.pop() << endl; //11 s1.push(33); s1.push(44); s1.push(55); s1.push(66); cout << "3: " << s1.pop() << endl; //66 cout << "4: " << s1.pop() << endl; //55 cout << "5: " << s1.pop() << endl; //44 cout << "6: " << s1.pop() << endl; //33 return 0; } Stack
  • 24.
    Operator Overloading – Operatoroverloading gives you the opportunity to redefine the C++ language. – The term operator overloading refers to giving the normal C++ operators such as +, *, <=, and +=, additional meanings when they are applied to user-defined data types. – Another kind of operation, data type conversion, is closely connected with operator overloading. – C++ handles the conversion of simple types, such as int and float, automatically; but conversions involving user-defined types require some work on the programmer’s part.
  • 25.
    1) Unary OperatorOverloading – Unary operators act on only one operand. (An operand is simply a variable acted on by an operator). – Examples of unary operators are the increment and decrement operators ++ and --, and the unary minus, as in -33
  • 26.
    #include <iostream> using namespacestd; class Counter { private: unsigned int count; public: Counter() : count(0) //constructor { } unsigned int get_count() //return count { return count; } void operator ++ () //increment (prefix) { count++; } }; int main() { Counter c1, c2; //define and initialize cout << "nc1 = " << c1.get_count(); //display cout << "nc2 = " << c2.get_count(); ++c1; //increment c1 ++c2; //increment c2 ++c2; //increment c2 cout << "nc1 = " << c1.get_count(); //display again cout << "nc2 = " << c2.get_count() << endl; return 0; } Example 1 A subtle defect if you use the statement: 'c1 = ++c2' (Prefix)
  • 27.
    #include <iostream> using namespacestd; class Counter { private: unsigned int count; public: Counter() : count(0) //constructor { } unsigned int get_count() //return count { return count; } Counter operator ++ () //increment count { ++count; //increment count Counter temp; //make a temporary Counter temp.count = count; //give it same value as this obj return temp; //return the copy } }; int main() { Counter c1, c2; //c1=0, c2=0 cout << "nc1 = " << c1.get_count(); //display cout << "nc2 = " << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 cout << "nc1 = " << c1.get_count(); //display again cout << "nc2 = " << c2.get_count() << endl; return 0; } Example 2 Solution
  • 28.
    #include <iostream> using namespacestd; class Counter { private: unsigned int count; public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() //return count { return count; } Counter operator ++ () //increment count { ++count; // increment count, then return return Counter(count); // an unnamed temporary object } // initialized to this count }; int main() { Counter c1, c2; //c1=0, c2=0 cout << "nc1 = " << c1.get_count(); //display cout << "nc2 = " << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 cout << "nc1 = " << c1.get_count(); //display again cout << "nc2 = " << c2.get_count() << endl; return 0; } Example 2 Solution 2
  • 29.
    #include <iostream> using namespacestd; class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() const //return count { return count; } Counter operator ++ () //increment count (prefix) { return Counter(++count); } Counter operator ++ (int) //increment count (postfix) { return Counter(count++); } }; int main() { Counter c1, c2; //c1=0, c2=0 cout << "nc1 = " << c1.get_count(); //display cout << "nc2 = " << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 (prefix) cout << "nc1 = " << c1.get_count(); //display cout << "nc2 = " << c2.get_count(); c2 = c1++; //c1=3, c2=2 (postfix) cout << "nc1 = " << c1.get_count(); //display again cout << "nc2 = " << c2.get_count() << endl; return 0; } Example 3 (Prefix and Postfix) int is a signal to indicate postfix ✓ You can use this same approach with the decrement operator (--) as well.
  • 30.
    2) Overloading BinaryOperators – Binary operators can be overloaded just as easily as unary operators. – We’ll look at examples that overload arithmetic operators, comparison operators, and arithmetic assignment operators.
  • 31.
    #include <iostream> using namespacestd; class Distance //English Distance class { private: int feet; float inches; public: //constructor (no args) Distance() : feet(0), inches(0.0) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() const //display distance { cout << feet << "' - " << inches << '"'; } Distance operator + (Distance) const; //add 2 distances }; //add this distance to d2 Distance Distance::operator + (Distance d2) const //return sum { int f = feet + d2.feet; //add the feet float i = inches + d2.inches; //add the inches if (i >= 12.0) //if total exceeds 12.0 { //then decrease inches by 12.0 and increase feet by 1 i -= 12.0; f++; } return Distance(f, i); //return a temporary Distance initialized to sum } int main() { Distance dist1, dist3, dist4; //define distances dist1.getdist(); //get dist1 from user Distance dist2(11, 6.25); //define, initialize dist2 dist3 = dist1 + dist2; //single ‘+’ operator dist4 = dist1 + dist2 + dist3; //multiple ‘+’ operators //display all lengths cout << "dist1 = "; dist1.showdist(); cout << endl; cout << "dist2 = "; dist2.showdist(); cout << endl; cout << "dist3 = "; dist3.showdist(); cout << endl; cout << "dist4 = "; dist4.showdist(); cout << endl; return 0; } Example 1 Output:
  • 32.
    #include <iostream> #include <string.h>//for strcpy(), strcat() #include <stdlib.h> //for exit() using namespace std; class String //user-defined string type { private: enum { SZ = 80 }; //size of String objects char str[SZ]; //holds a string public: String() //constructor, no args { strcpy(str, ""); } String(char s[]) //constructor, one arg { strcpy(str, s); } void display() const //display the String { cout << str; } String operator + (String ss) const //add Strings { String temp; //make a temporary String if (strlen(str) + strlen(ss.str) < SZ) { strcpy(temp.str, str); //copy this string to temp strcat(temp.str, ss.str); //add the argument string } else { cout << "nString overflow"; exit(1); } return temp; //return temp String } }; int main() { String s1 = "nHello, Mohamed!"; //uses constructor 2 String s2 = "Welcome abroad."; //uses constructor 2 String s3; //uses constructor 1 s1.display(); //display strings s2.display(); s3.display(); s3 = s1 + s2; //add s2 to s1, assign to s3 s3.display(); //display s3 return 0; } Example 2 (String Class)
  • 33.
    3) Overloading ComparisonOperator – The following example overloads the less than operator (<) in the Distance class in order to be used in comparing two distances.
  • 34.
    #include <iostream> using namespacestd; class Distance { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() const //display distance { cout << feet << "' - " << inches << '"'; } bool operator < (Distance d2) const //compare distances { float bf1 = feet + inches / 12; float bf2 = d2.feet + d2.inches / 12; return (bf1 < bf2) ? true : false; } }; int main() { Distance dist1; dist1.getdist(); Distance dist2(6, 2.5); //display distances cout << "ndist1 = "; dist1.showdist(); cout << "ndist2 = "; dist2.showdist(); if (dist1 < dist2) //overloaded '<' operator cout << "ndist1 is less than dist2"; else cout << "ndist1 is greater than(or equal to) dist2"; return 0; } Example 1 Two distances comparison using the < operator
  • 35.
    #include <iostream> #include <string.h>//for strcmp() using namespace std; class String //user-defined string type { private: enum { SZ = 80 }; //size of String objects char str[SZ]; //holds a string public: String() { strcpy(str, ""); } String(char s[]) { strcpy(str, s); } void display() const //display a String { cout << str; } void getstr() //read a string { cin.get(str, SZ); } bool operator == (String ss) const //check for equality { return (strcmp(str, ss.str) == 0) ? true : false; } }; int main() { String s1 = "yes"; String s2 = "no"; String s3; cout << "nEnter 'yes' or 'no': "; s3.getstr(); //get String from user if (s3 == s1) //compare with "yes" cout << "You typed 'yes'.n"; else if (s3 == s2) //compare with "no" cout << "You typed 'no'.n"; else cout << "You didn't follow instructions.n"; return 0; } Example 2 String Comparison using == operator
  • 36.
    #include <iostream> #include <string.h>//for strlen() using namespace std; class String { private: enum { SZ = 80 }; char str[SZ]; public: String() { strcpy(str, ""); } String(char s[]) { strcpy(str, s); } void display() const { cout << str; } void getstr() { cin.get(str, SZ); } bool operator < (String ss) const { return strlen(str) < strlen(ss.str); } }; int main() { String s1 = "Mohamed"; String s2 = "Ahmed"; if (s1 < s2) { cout << "The length of "; s1.display(); cout << " is less than "; s2.display(); } else { cout << "The length of "; s1.display(); cout << " is greater than "; s2.display(); } return 0; } Example 3 String Comparison using < operator
  • 37.
    #include <iostream> using namespacestd; class Distance { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) { } Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() { cout << "nEnter feet : "; cin >> feet; cout << "Enter inches : "; cin >> inches; } void showdist() const { cout << feet << "' - " << inches << '"'; } void operator += (Distance d2) { feet += d2.feet; //add the feet inches += d2.inches; //add the inches if (inches >= 12.0) //if total exceeds 12.0 { inches -= 12.0; feet++; } // return Distance(feet, inches); } }; int main() { Distance dist1; dist1.getdist(); cout << "ndist1 = "; dist1.showdist(); Distance dist2(11, 6.25); cout << "ndist2 = "; dist2.showdist(); dist1 += dist2; //add the two distances cout << "nAfter addition, dist1 = "; dist1.showdist(); return 0; } Example 4 Overloaded += assignment operator
  • 38.
    #include <iostream> #include <process.h>// for exit() using namespace std; const int LIMIT = 5; class safearay { private: int arr[LIMIT]; public: void putel(int n, int elvalue) //set value of element { if (n < 0 || n >= LIMIT) { cout << "Index out of bounds."; exit(1); } arr[n] = elvalue; } int getel(int n) const //get value of element { if (n < 0 || n >= LIMIT) { cout << "Index out of bounds."; exit(1); } return arr[n]; } }; int main() { safearay sa1; for (int i = 0; i < LIMIT; i++) // insert elements sa1.putel(i, i * 10); for (int i = 0; i < LIMIT; i++) // display elements cout << "Element " << i << " is " << sa1.getel(i) << endl; return 0; } Safe Array Class Example 1
  • 39.
    #include <iostream> #include <process.h>//for exit() using namespace std; const int LIMIT = 5; //array size class safearay { private: int arr[LIMIT]; public: int& operator [] (int n) //note: return by reference { if (n < 0 || n >= LIMIT) { cout << "Index out of bounds."; exit(1); } return arr[n]; } }; int main() { safearay sa1; for (int i = 0; i < LIMIT; i++) //insert elements sa1[i] = i * 10; for (int i = 0; i < LIMIT; i++) //display elements cout << "Element " << i << " is " << sa1[i] << endl; return 0; } Safe Array Class Example 2 Overloading the subscript [ ] operator
  • 40.
    The Standard C++string Class #include <iostream> #include <string> //for string class using namespace std; int main() { //objects of string class string full_name, nickname, address; string greeting("Hello, "); cout << "Enter your full name : "; getline(cin, full_name); //reads embedded blanks cout << "Your full name is : " << full_name << endl; cout << "Enter your nickname : "; cin >> nickname; //input to string object greeting += nickname; //append name to greeting cout << greeting << endl; //output: "Hello, Mohamed" cout << "Enter your address on separate linesn"; cout << "Terminate with '$'n"; getline(cin, address, '$'); //reads multiple lines cout << "Your address is : " << address << endl; return 0; }
  • 41.
    Example #include <iostream> #include <string> usingnamespace std; int main() { string s1("Man"); //initialize string s2 = "Beast"; //initialize string s3; s3 = s1; //assign cout << "s3 = " << s3 << endl; s3 = "Neither " + s1 + " nor "; //concatenate s3 += s2; //concatenate cout << "s3 = " << s3 << endl; s1.swap(s2); //swap s1 and s2 cout << s1 << " nor " << s2 << endl; return 0; }
  • 42.
    Operator Overloading –Summary – Use similar meanings (i.e., semantics), you could overload the + sign to perform subtraction, for example, but that would hardly make your listings more comprehensible. – You can’t overload a binary operator to be a unary operator, or vice versa. – Not all operators can be overloaded, the following operators cannot be overloaded: ▪ the member access or dot operator (.) ▪ the scope resolution operator (::) ▪ the conditional operator (?:) ▪ the pointer-to-member operator (->) ▪ you can’t create new operators (like *&) and try to overload them; only existing operators can be overloaded.
  • 43.
    End of lecture2 ThankYou!