You are on page 1of 62

Inline Functions

• It is possible to define functions in C++ that are not


actually called but, rather, are expanded inline, at the point
of each call.
• The advantage is that there is no overhead associated
with the function call and return mechanism.
Example:
inline void myclass::init( int i, int j )
{ Disadv :
a=i; Code – More
Memory
b=j;
Faculty of IT, AFTC
Friend functions
It is possible to grant a non-member function access to the
private members of a class by using a friend.

A friend function has access to all private and protected


members of the class for which it is a friend.

To declare a friend function, include its prototype within the


class, preceding it with the keyword friend.

Faculty of IT, AFTC


Example of a friend function
#include <iostream.h>
class myclass
{
int a,b;
public:
friend int sum(myclass x);
void set_value(int i,int j)
{ a=i;
b=j;
Faculty of IT, AFTC
}
Example of a friend function(contd..)
int sum(myclass x)
{ /* Bcoz sum() is friend of myclass it can
directly access a and b*/
return x.a+x.b;
}
int main()
{ myclass n;
n.set_value(3,4);
cout <<sum(n);
} Faculty of IT, AFTC
Static Class members
Both function and data members of a class can be made static.
Static Data members
•When you precede a member variable’s declaration with
static, you are telling the compiler that only one copy of that
variable will exist and that all objects of the class will share
that variable.
•No matter how many objects of a class are created, only one
copy of a static data member exists.
•When you declare a static data member within a class, you
are defining it( no storage is allocated). Instead, you must
provide a global definition for it elsewhere, outside the class.
Faculty of IT, AFTC
Example of a static data member
#include<iostream.h>
class myclass
{
static int I;
public:
void seti(int n){ I=n;}
int geti(){ return I; }
};
/*Definition of I ,myclass::I.
I is still private to myclass.*/

int myclass::I ; (contd..)

Faculty of IT, AFTC


Example of a static data member(contd..)

int main()
{
myclass o1,o2;
o1.seti(10);
cout<<o1.geti()<<“\n”;
cout<<o2.geti()<<“\n”;
}

Faculty of IT, AFTC


Object Pointers
Members of an object can also be accessed via a pointer to that
object.
When a pointer is used, the arrow(->) operator is used rather
than the dot operator.
Example:
myclass ob; //create object
myclass *p; //create pointer to object
p=&ob; //put address of ob into p

Faculty of IT, AFTC


The this pointer
C++ contains a special pointer that is called this. this is a
pointer that is automatically passed to any member function
when it is called.
Example:
#include<iostream.h>
class inventory{
char item[20];
double cost;
public:
inventory(char *I,double c){
strcpy(this->item,I); (contd..)
Faculty of IT, AFTC
Example of this pointer(contd..)
this->cost=c; }
void show(); };
void inventory::show() {
cout<< this->item;
cout<< this->cost;
}
int main(){
inventory ob(“pen”,4.65);
ob.show();
Faculty of IT, AFTC
}
Using new and delete
In C++, one can allocate memory using new and release it
using delete.
These operators take these general forms:
p-var=new type;
delete p-var;
where type is the type specifier of the object for which you
want to allocate memory and p-var is a pointer to that type.
new and delete are similar to malloc() and free() used in C.

Faculty of IT, AFTC


Example of new and delete
#include<iostream.h>
int main()
{
int *p;
p=new int; //allocate room for an integer
if(!p){
cout<<“Allocation error\n”;
return 1;
} (contd..)
Faculty of IT, AFTC
Example of new and delete(contd..)

*p=1000;
cout<<“Integer at p:”<< *p << “\n” ;
delete p; //release memory
}

Faculty of IT, AFTC


Operator Overloading -
Introduction
Operator overloading
 Enabling C++’s operators to work with class objects
 Using traditional operators with user-defined objects
 Requires great care; when overloading is misused,
program difficult to understand
Not a new concept! C++ overloads many
operators already (so did C!)
 Examples of already overloaded operators
 Operator << is both the stream-insertion operator and the
bitwise left-shift operator
 + and -, perform arithmetic on multiple types
 Compiler generates the appropriate code based on the
manner in which the operator is used

Faculty of IT, AFTC


Fundamentals of
Operator Overloading
Overloading an operator
 Write function definition as normal
 Function header and body
 Function name is keyword operator followed by the symbol for the operator
being overloaded
 Ex: operator+ - used to overload the addition operator (+)
Using operators
 To use an operator on a class object it must be overloaded
 Example: add two sets of integers, set class must overload + operator
 Exception: the assignment operator(=)or the address operator(&)
 You can still do your own overloading
 Assignment operator by default performs memberwise assignment
 Address operator (&) by default returns the address of an object

Faculty of IT, AFTC


Operator Overloading
An operator is overloaded by writing a
function definition that has a function
name of operator followed by the
symbol for the operator to be
overloaded.
operator- will define a function that
overrides the built-in subtraction operator.

Faculty of IT, AFTC


1 // my example
2 // Overloading the == operator and
3 // using it
4 #include <iostream>
5
6 using std::cout;
7 using std::cin;
8 using std::endl;
9 using std::ostream;
10 using std::istream;
11
Account a (1, 500);
12 #include <iomanip>
13 Account b (2, 600);
14 using std::setw; if (a == b) {
15 cout << “They are equal”
16 class Account{
<< endl;
17 private:
}
18 float balance;
19 int id;
20 public:
21 bool operator==(const Account &rightA) const;
22};
23 bool Account::operator==(const Account &rightA) const {
24 if ((id == rightA.getId()) &&
25 (balance ==rightA.getBalance () )
return true;
return false;
}

Faculty of IT, AFTC


What operators can be
overloaded?
C++ operators that can be overloaded
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= ==
C++ Operators that !=
cannot<= be overloaded
>= && || ++
-- ->* , -> [] () new delete
new[] delete[]

Operators that cannot be overloaded


. .* :: ?: sizeof

Faculty of IT, AFTC


Restrictions on
Operator Overloading
Overloading restrictions
 Precedence of an operator cannot be changed
 Associativity of an operator cannot be changed
 Arity (number of operands) cannot be changed
 Unary operators remain unary, and binary operators remain
binary
 Operators &, *, + and - each have unary and binary
versions
 Unary and binary versions can be overloaded separately
No new operators can be created
 Use only existing operators
No overloading operators for built-in types
 Cannot change how two integers are added
 Produces a syntax error
Faculty of IT, AFTC
Operator Functions as Class
Functions

Member vs non-member
 Operator functions can be member or non-member functions
 When overloading ( ), [ ], -> or any of the assignment
operators, you must use a member function
Operator functions as member functions
 Leftmost operand must be an object (or reference to an
object) of the class
 If left operand of a different type, operator function must be a
non-member function
 Classic example << operator
Operator functions as non-member functions
 Must be friends if needs to access private or protected
members
 Enable the operator to be commutative
Example: Overloading the Stream-insertion (<<)
and Stream-extraction
Faculty of(>>)
IT, AFTC Operators
Operator Overloading
Overloading an operator does not
change:
 the operator precedence,
 the associativity of the operator,
 the meaning of how the operator works on
objects of built-in types.

Faculty of IT, AFTC


1 // Fig. 8.3: fig08_03.cpp
2 // Overloading the stream-insertion and
3 // stream-extraction operators.

An Example
4 #include <iostream>
5
6 using std::cout;
7 using std::cin;
8 using std::endl;
9 using std::ostream;
10 using std::istream;
11
12 #include <iomanip>
Notice function prototypes for
13
overloaded operators >> and <<
14 using std::setw; They must be friend functions.
15
16 class PhoneNumber {
17 friend ostream &operator<<( ostream&, const PhoneNumber & );
18 friend istream &operator>>( istream&, PhoneNumber & );
19
20 private:
21 char areaCode[ 4 ]; // 3-digit area code and null
22 char exchange[ 4 ]; // 3-digit exchange and null
23 char line[ 5 ]; // 4-digit line and null
24 };
25
26 // Overloaded stream-insertion operator (cannot be
27 // a member function if we would like to invoke it with
28 // cout << somePhoneNumber;).
29 ostream &operator<<( ostream &output, Faculty of IT, AFTC &num )
const PhoneNumber
30 {
31 output << "(" << num.areaCode << ") "
32 << num.exchange << "-" << num.line;
33 return output; // enables cout << a << b << c;
34 }
35
36
37
istream &operator>>( istream &input, PhoneNumber &num )
{
Example
38 input.ignore(); // skip (
39 input >> setw( 4 ) >> num.areaCode; // input area code
40 input.ignore( 2 ); // skip ) and space
41 input >> setw( 4 ) >> num.exchange; // input exchange
42 input.ignore(); // skip dash The
(-) function call
43 input >> setw( 5 ) >> num.line; // input line
44 return input; // enables cin >> a >> b >> c;
cin >> phone;
45 } interpreted as
46
47 int main() operator>>(cin, phone);
48 {
input is an alias for cin, and num
49 PhoneNumber phone; // create object phone
50
is an alias for phone.
51 cout << "Enter phone number in the form (123) 456-7890:\n";
52
53 // cin >> phone invokes operator>> function by
54 // issuing the call operator>>( cin, phone ).
55 cin >> phone;
56
57 // cout << phone invokes operator<< function by
58 // issuing the call operator<<( cout, phone ).
59 cout << "The phone number entered was: " << phone << endl;
60 return 0; Faculty of IT, AFTC
61 }
Overloading Unary Operators
Overloading unary operators
 Can be overloaded with no arguments or one
argument
 Should usually be implemented as member
functions
 Avoid friend functions and classes because they
violate the encapsulation of a class
 Example declaration as a member function:
class String {
public:
bool operator!() const;
...
};
 Example declaration as a non-member function
class String {
friend bool operator!( const String & )
Faculty of IT, AFTC
...
Overloading Binary Operators
Overloaded Binary operators
 Non-static member function, one argument
 Example:
class String {
public:
const String &operator+=(
const String & );
...
};
 y += z is equivalent to y.operator+=( z )

Faculty of IT, AFTC


Overloading Binary Operators
 Non-member function, two arguments
 Example:
class String {
friend const String &operator+=(
String &, const String & );
...
};
 y += z is equivalent to operator+=( y, z )

Faculty of IT, AFTC


Operator Overloading
Operator Overloading allows a
programmer to define new types from the
built-in types.
 Operator Overloading is useful for redefining
built-in operations for user defined types.
 Operator Overloading should be used to
perform the same function or similar function on
class objects as the built-in behavior.

Faculty of IT, AFTC


Operator Overloading
Each individual operator must be
overloaded for use with user defined
types.
 Overloading the assignment operator and
the subtraction operator does not overload
the -= operator.

Faculty of IT, AFTC


Operator Overloading
(continued)
Operator overloading means that the
operators:

 Have multiple definitions that are distinguished by


the types of their parameters, and

 When the operator is used, the C++ compiler uses


the types of the operands to determine which
definition should be used.

Faculty of IT, AFTC


Operator Overloading
(continued)
A programmer has the ability to re-define or
change how the operators (+, -, *, /, =, <<,
>>, etc.) work on their own classes.
Overloading operators usually consists of
defining a class member function called
operator+ (where + is any operator). Note
that operator is a reserved word in C++. If
anything usually follows that operator, it is
passed to the function. That function acts
exactly like any other member function; it has
the same scope as other member functions
and can return aFaculty
value just like any other
of IT, AFTC
Operator Overloading
(continued)
Steps for defining an overloaded operator:

1. Name the operator being overloaded.

2. Specify the (new) types of parameters


(operands) the operator is to receive.

3. Specify the type of value returned by the


operator.

4. Specify what action the


Faculty of IT, operator
AFTC is to
Operator Overloading
class A {
friend ostream &operator<< Similar to function
(ostream &out, const A &a);
private:
overloading
int m_a;  Resolved by signature
};
 Best match is used
ostream &operator<< But list of operators and
(ostream &out, const A &a) {
o << "A::m_a = " << a.m_a; “arity” of each is fixed
return o;  Can’t add operators
}
 Must use same number of
int main () { arguments as for built-in
A a; types (except operator())
cout << a << endl;
return 0;  Some operators off limits
}  Obey same precedence
rules as for built-in types
Faculty of IT, AFTC
Operator Overloading
Overview
Classes allow us to define our own data types
in addition to the built in primitive types.
It’s often convenient for our classes to model
the operations available on primitive types.
We can use the same concise notation for
expressing how to manipulate our objects.

Faculty of IT, AFTC


A Complex Class
class Complex {
public:
Complex (int real = 0, int imagine =
0);
int getReal ( void ) const;
int getImagine (void ) const;
void setReal (int n);
void setImagine (int d);
Faculty of IT, AFTC
Complex (cont’d)
private:
int real;
int imagine;
};

Faculty of IT, AFTC


Using Complex Class
It makes sense to want to perform
mathematical operations with Complex
numbers
Complex C1 (3, 5), C2 (5, 9), C3;
C3 = C1 + C2;
C2 = C3 * C1;
C1 = -C2;

Faculty of IT, AFTC


Operators are really functions
For user defined types, when you use
an operator, you are making a function
call

Consider the expression C2 + C1;


This is translated into a function call
The name of the function is
“operator+”

Faculty of IT, AFTC


operator+ as a member
function
What’s the full name of the function?

What should the return type be?

What are the parameters? (trick


question)

Should it be const?

Faculty of IT, AFTC


Declaring operator+
as a member function
class Complex {
public:
const Complex
operator+ (const Complex& rhs) const;
…..
};
Why just one parameter?????

Faculty of IT, AFTC


Complex::operator+
const Complex
Complex :: operator+ (const Complex & rhs)
const
{
Complex sum;
// accessor/mutators not required
sum.imagine = imagine + rhs.imagine;

// but preferred
sum.setReal( getReal( ) + rhs.getReal ( ) );
return sum; 40
Using operator+
We can now write (cascading operators)
C4 = C3 + C2 + C1;

We can also write (how does it work?) C3 =


C2 + 7;

But C3 = 7 + C2 is a compiler error (Why?)

Faculty of IT, AFTC


Operator+ as a non-member
(ordinary old) function
What’s the full name of the function?

What should the return type be?

What are the parameters?

‘const’ does not apply to non-member


functions

Faculty of IT, AFTC


Overloading unary operators
Complex C1(4, 5), C2;
C2 = -C1;
Is an example of a unary operator
(minus)

We can and should overload as member

Faculty of IT, AFTC


Restrictions
Not all operators can be overloaded
You can’t make up your own operators
You can’t overload operators for
primitive types (like int)
You can’t change the associativity
You can change the number of
operands

Faculty of IT, AFTC


Good Programming Practices
Overloaded binary arithmetic operators
should
 Return const objects by value
 Be written as non-member functions when
appropriate to allow commutativity
Overload unary operators as members
Always overload operator<<
Overload operators so that they mimic the
behavior of primitive data types

Faculty of IT, AFTC


Operator Overloading
Basics
•This resembles function overloading.When an operator is
overloaded, that operator loses none of its original meaning.
Instead it gains additional meaning relative to the class for
which it is defined.
•To overload an operator,you create an operator function.
Most often, an operator function is a member or a friend of the
class for which it is defined.
General form of a member operator function is:
Return-type class-name::operator#(arg-list)
{
//operation to be performed
}
Here, the # represents the operator that is being overloaded.
Faculty of IT, AFTC
For example,operator+ implies that + is being overloaded.
Most C++ operators can be overloaded. The only operators
that cannot be overloaded are:
. :: .* ?
Also, one cannot overload the preproceesor operators.
The two best examples of overloaded operators are << and >>.
Both are overloaded for console I/O.

Overloading Binary operators


When a member operator function overloads a binary
operator, the function will have only one parameter.
This parameter will receive the object that is on the right
side of the operator. The object on the left side is the object
that generates the call to the operator function and is passed
implicitly by this.
Faculty of IT, AFTC
Example of overloading a binary operator:
#include<iostream.h>
class coord{
int x,y;
public:
coord(){ x=0; y=0; }
coord(int i, int j){ x=i; y=j; }
void get_xy(int &i,int &j){
i=x;j=y; }
coord operator+(coord ob2);
};

//overload + relative to coord class


coord coord::operator+(coord ob2){
coord temp; (contd..)
Faculty of IT, AFTC
Example(contd..)
temp.x=x + ob2.x;
temp.y=y + ob2.y;
return temp;
}
int main(){
coord o1(10,10), o2(5,4), o3;
int x,y;
o3 = o1 + o2; //add two objects, this calls
operator+()
o3.get_xy(x,y);
cout<< “(o1+o2) X:”<< x<< “,Y:”<< y <<”\n”;
}

Faculty of IT, AFTC


Overloading Unary operators
This is similar to overloading a binary operator except
that there is only one operand to deal with. When you
overload a unary operator using a member function, the
function has no parameters.
Example:
#include<iostream.h>
class coord
{
int x,y; //coordinate values
public:
coord() { x=0;y=0; }
coord(int i, int j) { x=i;y=j; }
void get_xy(int &i,int &j){ i=x;j=y; }
coord operator++();
Faculty of IT, AFTC
}; (contd…)
Example(cond..)
//Overload ++ for coord class.
coord coord::operator++(){
x++;
y++;
return *this;
}
int main() {
coord o1(10,10);
int x,y;
++o1; //increment an object
o1.get_xy(x,y);
cout<<”(++o1)X:” << x << “,Y:” << y <<”\n”;
}
Faculty of IT, AFTC
Operator Functions
Operator functions may be defined as
either member functions or as non-
member functions.
 Non-member functions are usually made
friends for performance reasons.
 Member functions usually use the this
pointer implicitly.

Faculty of IT, AFTC


Operator Functions
The operator overloading functions for
overloading (), [], -> or the assignment
operators must be declared as a class
member.
All other operators may be declared as
non-member functions.

Faculty of IT, AFTC


Member Functions
When an operator function is
implemented as a member function:
 The leftmost operator must be a class
object or reference to a class object of the
operator’s class.
 If the function must access private or
protected data, then the function must be
defined as a friend function.

Faculty of IT, AFTC


Complex Numbers
Complex numbers consist of two pairs
the real and the imaginary parts.
realPart + imaginaryPart * i where i has
a value

 A program should be able to input and output


complex numbers.
 A program should be able to add, subtract, and
multiply complex numbers.
 A program should also be able to compare
complex numbers.
Faculty of IT, AFTC
Overloading Unary Operators
Unary operators can be overloaded as:
 non-static member functions with no
arguments,or as
 non-member functions with one argument
where the argument must be either an
object of the class or a reference to an
object of the class.

Faculty of IT, AFTC


Overloading Unary Operators
The preference for overloading unary
operators is to make the operator
functions class members instead of non-
member friend functions.

Faculty of IT, AFTC


Overloading Binary Operators
Binary operators can be overloaded as:
 non-static member functions with one
argument, or as
 a non-member function with two
arguments where one of the arguments
must be either a class object or a reference
to a class object.

Faculty of IT, AFTC


Form of Operator-Overloading
Function

To overload op as in
A op B
we define a function of the form
operator op(B) (member function)
Or
operator op(A, B) (non-member)
where op can be +,-,/, %, =, !=, [ ], +=,
etc Faculty of IT, AFTC
Overloading Binary Operators

Overloading +=
y += z translate to operator+=(y,z)
where
class String {
public:
friend const String &operator+=(String &, const
String &);

};
Faculty of IT, AFTC
Operator Overloading
Chapter 8
Faculty of IT, AFTC

You might also like