Você está na página 1de 27

Topic 2:

Classes
I. Introduction:
A class is an extended type of structure. Unlike structures, which hold data
only, classes can hold both data and functions.

An object is an instantiation of the class. i.e. class would be a type and object is
the variable.

II. Class Declaration:


To declare a class we use the keyword ‘class’ instead of ‘struct’ and follow this
syntax:

class class_name
{
access_specifier1:
member1;
access_specifier2:
member2;
};

Members can be:


- Data declarations.
- Function declarations

Access Specifiers can be one of these keywords:


- public members of a class are accessible from anywhere where the object
is visible.
- private members of a class are accessible only from within other members
of the same class.
by default all members in a class are private.

Object X Access denied

Public Private Public


Members Members Functions Access can be
done directly
using the
member names

Access can be done using “.”


Operator after object name

© 2006, I. Sarah Al-Shareef 1


Topic 2: Classes

Example 2.1:
class Fraction
{
public:
int num, den;
};

void main()
{
Fraction x; //Declaring object of type Fraction.
cout<<“x=”<< x.num << “/” << x.den << endl;

Fraction *f; //Declaring pointer to an object

cout<<”*f=”<< (*f).num << “/” << (*f).den <<endl;

//Since f is a pointer we can use arrow operator instead.


//Syntax to use arrow operator:
// pointer_to_object->member_of_the_class_or_structure

cout<<”*f=”<< f->num << “/” << f->den <<endl;


}

Example 2.2:
class Fraction
{
private:
int num, den;
};

void main()
{
Fraction x;
cout<<“x=”<< x.num << “/” << x.den;
//ERROR:
//“num” and “den” are not accessible.
}

As you can see in the previous example we can’t use the private members
directly from the object name using the dot operator. That’s why we need to
declare member functions.

III. Member functions:


They are functions which can be used only by the class objects.

We can define the member functions as the following:


- Definition inside the class.
- Prototype inside the class and the definition is outside the class.

© 2006, I. Sarah Al-Shareef 2


Topic 2: Classes

Syntax to declare member function inside the class definition:


class class_name
{
access_specifier1:
return_type function_name(paramenters_list)
{
//function body
}
};

- return_type is specified according to the result return to caller from the


object. If there is nothing returned we use void.
- paramenters_type are what we need from outside the object.

Example 2.3: Defining member function inside the class definition.


class Fraction
{
private:
int num, den;
public:
void print()
{
cout<<num << “/” <<den;
}
void set(int a, int b)
{
num = a;
den = b;
}
float convert()
{
float a= float(num)/den;
return a;
}
};
void main()
{
Fraction x; //Declaring object of type Fraction.
x.set(2,5); //Call member function set(int,int)
x.print(); //Call member function print()
cout<<”=”<<x.convert();
//print the result returned by convert()
}

Notes:
- print() will print the object content to the screen. So there is no need for
return value. Also we don’t need anything from outside the object, so there
will be no parameters for this function.

© 2006, I. Sarah Al-Shareef 3


Topic 2: Classes

- set(int,int) will take two values from outside the object and assign them
to the object members. And it will not return anything to the caller.
- convert() will convert the fraction object to float by divide the members
and return the result to the caller.

Syntax to declare member function outside the class definition:


class class_name
{
access_specifier1:
return_type function_name(paramenters_type);
};

return_type class_name :: function_name(paramenters_type)


{
//function body
}

- We will just include the member function prototype inside the class
definition.
- We will write the function definition after the class definition, but we have to
prefix the class name that function belongs to and the scope operator “::”.
- If we didn’t include the class name and the scope operator it will produce
logical error.

Example 2.3: Defining member function outside the class definition.


class Fraction
{
private:
int num, den;
public:
void print();
void set(int a, int b);
float convert();
};

void main()
{
Fraction x; //Declaring object of type Fraction.
x.set(2,5); //Call member function set(int,int)
x.print(); //Call member function print()
cout<<”=”<<x.convert();
//print the result returned by convert()
}

void Fraction :: print()


{
cout<<num << “/” <<den;
}

© 2006, I. Sarah Al-Shareef 4


Topic 2: Classes

void Fraction :: set(int a, int b)


{
num = a;
den = b;
}
Float Fraction :: convert()
{
float a= float(num)/den;
return a;
}

Note:
If the member function is receiving an object from the same class, the
private members can be accessed through the object’s name.

Example 2.3: Accessing private members from received object.


class Fraction
{ private:
int num, den;
public:
void print();
void set(int a, int b);
float convert();
bool isEqual(Fraction); //member function receiving
//an object of the class
};
void main()
{
Fraction x; //Declaring object of type Fraction.
x.set(2,5); //Call member function set(int,int)
x.print(); //Call member function print()
cout<<”=”<<x.convert();
//print the result returned by convert()
}
void Fraction :: print()
{
cout<<num << “/” <<den;
}

void Fraction :: set(int a, int b)


{
num = a;
den = b;
}
Float Fraction :: convert()
{
float a= float(num)/den;
return a;
}

© 2006, I. Sarah Al-Shareef 5


Topic 2: Classes

//This function will take one object of the class Fraction


//that will true if members is equal. Otherwise, it will
//return false.
bool Fraction :: isEqual( Fraction a )
{
//Although num and den are private members but we can
//access them through the object name. Because isEqual()
//is a member function.
if((num == a.num)&&(den == a.den))
return true;
return false;
}

IV. Initializing Class Objects using Constructor

To initialize structure object we were directly use this syntax:


Syntax:
Struct_Name x={v1,v2,v3,...};
//v1 : is initialization value for first member.
//v2 : is initialization value for second member.
//and so on...

But this will not work with class object . That’s why we need to use
constructors.

Constructor is a special member function which is automatically called


when declare a new object of the class. It will be provided with any class, which
is called default constructor, but it can’t initialize the object to the desired
value. Unless we define it by ourselves which is called overloaded constructor.

Overloading constructor:
- To overload a constructor we have to define it as a member function inside
the class.
- Constructor will have the same name of the class.
- We don’t specify a return type for a constructor even void. It will be
considered as a syntax error.
- Syntax: class_name(parameters);
- We can send parameter to the constructor.
- We can have more than one constructor but they must have different
signature (i.e. different parameter types, order and number).
- We can use default arguments with the constructor.
- We can’t use a version of a constructor that we don’t define by ourselves.
- To use the overloaded constructor with parameters put the parameters inside
( ) after the object name.

© 2006, I. Sarah Al-Shareef 6


Topic 2: Classes

Example 2.4: Using overloaded constructor


class Time
{
int hour, min, sec;
public:
Time();
Time(int a, int b, int c);
};
void main()
{
//To use the overloaded constructor with parameters in
//the declaration of the object put the parameters
//between () after the object name.

Time x(12,0,0);

//Now in the object x : hour=12, min=sec=0;

//To use the overloaded constructor without parameters


//just declare the object as usual.

Time y;

Time z(12);
//ERROR:
//We don’t have a constructor that take’ll one parameter
}
Time::Time()
{
hour = min = sec = 0;
}
Time::Time(int a, int b, int c)
{
hour = a;
min = b;
sec = c;
}

Example 2.5: Using overloaded constructor with default arguments


class Time
{
int hour, min, sec;
public:
Time(int =0, int b=0, int c=0);
};
void main()
{
//To use the overloaded constructor with parameters in
//the declaration of the object put the parameters
//between () after the object name.

© 2006, I. Sarah Al-Shareef 7


Topic 2: Classes

Time x;
//Now in the object x : hour=min=sec=0

Time y(12);
//Now in the object y : hour=12, min=sec=0

Time z(3,30);
//Now in the object z : hour=3, min=30, sec=0

Time a(3,30,50);
//Now in the object a : hour=3, min=30, sec=50
}
Time::Time(int a, int b, int c)
{
hour = a;
min = b;
sec = c;
}

Using Initializer in the Constructor:


- We can initialize the members in special way called initializer lists.
- Syntax: class_name(p1,p2,...):mem1(p1), mem2(p2),...{}
- p1,p2,... are send parameters.
- mem1,mem2,... are members of the class.
- After each member we put the wanted value or parameter between ( ).
- Between ( ), it can be a constant value or a sent parameter.
- The members are separated by comma.
- We don’t have to put all the member in the list. We can put part of them in
the list and some in the body of the constructor.

Example 2.6:
Using overloaded constructor with initializer lists and parameters
class Time
{
int hour, min, sec;
public:
Time(int =0, int b=0, int c=0);
};
void main()
{
Time x;
}
//We use initializer list for all members with parameters
Time::Time(int a, int b, int c):hour(a), min(b), sec(c)
{
}

© 2006, I. Sarah Al-Shareef 8


Topic 2: Classes

Example 2.7: Using overloaded constructor with initializer lists and


constants
class Time
{
int hour, min, sec;
public:
Time();
Time(int, int, int);
};
void main()
{
Time x;
}
//We use initializer list for all members with constants
Time::Time():hour(0), min(0), sec(0)
{
}
//We use initializer list for some members with parameters
Time::Time(int a, int b, int c):hour(a), min(b)
{
sec(c);
}

Note:
- Although a constructor is a member function but we can’t call it by ourselves
as we do it with other member functions. It will cause a syntax error.
- The constructor is called only ONCE in the object’s lifetime.

Example 2.8: Error: Calling constructor through object name


class Time
{
int hour, min, sec;
public:
Time(int=0, int=0, int=0);
};
void main()
{
Time x; //Constructor is called.

x.Time();
//Error: We can’t call constructor by object name.
}
Time::Time(int a, int b, int c):hour(a), min(b), sec(c)
{
}

© 2006, I. Sarah Al-Shareef 9


Topic 2: Classes

V. The Class Destructor:

When an object is created a constructor is called automatically to manage


its birth. Similarly, when an object comes to the end of its life, another special
member function is called automatically. This function is called destructor.

The destructor is called when the object reaches the end of its scope. If
we didn’t built our own destructor, a default destructor is used. But if we built it
with ourselves it’s called overloaded destructor.

Overloading destructor:
- To overload a destructor we have to define it as a member function inside the
class.
- Destructor will have the same name of the class with ~ sign before it.
- We don’t specify a return type for a constructor even void. It will be
considered as a syntax error.
- We can’t send parameters to the destructor. It will be considered as a syntax
error.
- Syntax: ~class_name();
- We can’t have more than one destructor.

Example 2.9: Destructor


class Letter
{
char name;
public:
Letter(char);
~Letter();
};
void main()
{
Letter a(‘a’); //Object a is born
{
Letter b(‘b’); //Object b is born
} //Object b is died
} //Object a is died
Letter:: Letter (char a):name(a)
{
cout<<”Object ”<<name<<” is born.\n”;
}
Letter::~ Letter ()
{
cout<<”Object ”<<name<<” is died.\n”;
}

© 2006, I. Sarah Al-Shareef 10


Topic 2: Classes

Note:
- We have to build our own destructor when we use a dynamic allocation for a
member or more in object. This destructor will contain the delete statement
for the dynamic member.

Example 2.10: Dynamic allocation for a member in constructor


class Person
{
char *name;
public:
Person(char []);
~Person();
};
void main()
{
cout<<”Block starting.\n”; //Block staring.
{
Person x(“Sami”); //Sami is created.
} //Sami is deleted.
cout<<”Block ending.\n”; //Block ending.
}
Person :: Person(char a[])
{
name = new char[strlen(a)];

//We used dynamic memory allocation, so we need a


//destructor to delete it.

strcpy(name, a);
cout<<name<<” is created.\n”;
}
Person :: ~Person ()
{
cout<<name<<” is deleted.\n”;
delete name;
}

VI. Composition (Nested Classes):

When we use one class within definition of another class. i.e. when one of
the data member is an object of another class.

When we want to initialize an object member we use the initializer lists.

We have to define the inner class before using it inside the other class.

© 2006, I. Sarah Al-Shareef 11


Topic 2: Classes

Example 2.11: Log file for employees by using a composition class


class Time
{
int hour, min, sec;
public:
Time(int=0, int=0, int=0);
void print();
void set(int,int,int);
};
class Log
{
int id;
Time in, out;
bool att;
public:
Log();
void login(int, int, int, int);
void logout(int, int, int);
void print();
};
void main()
{
Log x, y, z;
x.login(111222333, 8, 0, 0);
y.login(222333444, 8,30, 0);
z.login(333444555, 9,15,54);
x.logout(2, 30, 0);
y.logout(1, 15, 0);
z.logout(3, 30, 40);
cout<<setw(10)<<”ID”<<setw(16)<<”In Time”
<<setw(16)<<”Out Time”<<endl;
x.print();
y.print();
z.print();
}
Time::Time(int a, int b, int c)
{
hour = a; min = b; sec = c;
}
void Time::print()
{
cout<<setw(10)<<hour<<’:’<<setw(2)<<min<<’:’
<<setw(2) <<sec;
}
void Time::set(int a, int b, int c)
{
hour = a; min = b; sec = c;
}

//We use initializer lists for the object data members. And
//give them the needed valused or parameters.

© 2006, I. Sarah Al-Shareef 12


Topic 2: Classes

Log::Log():in(0,0,0), out(0,0,0)
{ id=0;
att=false;
}
void Log::login(int i, int h, int m, int s)
{
id = i;
in.set(h,m,s);
att = true;
}
void Log::logout(int h, int m, int s)
{
out.set(h,m,s);
att = false;
}
void Log::print()
{
cout<<setw(10)<<id;
in.print();
out.print();
cout<<endl;
}

VII. Constant Objects and Member Functions:

The basic for declaring any constant variable from primitive types are:
const type x = initialization;
- Include the keyword: const before the type.
- Declare the wanted variable: int x;
- Must initialize the variable or it will be a syntax error.

The same thing is for declaring a constant object:


const class_name object(initialization);
- Include the keyword: const before the class name.
- Declare the wanted object: class_name object;
- Must initialize the object (i.e. have an overloaded constructor) or
it will be a syntax error.

What does constant object mean?


It mean that the values of all its member will be NEVER changed from
their initialized values.

So when a constant object is defined, the compiler will disallow all


member functions specially those which modify the values of member. To
inform the complier that a function is safe to be using with constant object we
have to declare the member function as constant member function.

© 2006, I. Sarah Al-Shareef 13


Topic 2: Classes

So if we call member function that is not a constant function that will be a


syntax error.

Constant member function:


- They are member functions whose are safe to use with constant objects.
i.e. they don’t modify the value of data members.
- We have to include the keyword const at the end of the prototype or at
the end of the definition header.
- Prototype syntax:
return_type function_name(parameters) const;
- Definition syntax:
return_type function_name(parameters) const
{ /* function body */ }
- It will be a syntax error if we use the keyword const with function that
modify a data member.
- We can have two versions of a member function: one as a constant
member function and the other as a non-constant member function.
- If we define the member function outside the class, we have to include
the keyword const after both the prototype inside the class and the
definition header outside the class.
- We can’t declare constructor and destructor as constant member
functions.

Example 2.12: Declaring a constant object


class Time
{
int hour, min, sec;
public:
//If we plan to use a const object we MUST declare
//a constructor. Syntax error if we don’t.
//It’ll be a syntax error if we declare it as const.
Time(int=0, int=0, int=0);
//To make a member function constant it MUST NOT
//changing any data member.
void print() const;
//We can NOT declare a member function that modify
//data members as const (Syntax Error)
void set(int,int,int);
};
void main()
{
Time x; //x is a non-const object
const Time y(12,0,0); //y is a const object.

x.set(1,1,1);
y.set(2,2,2); //Error set() isn’t const func.

© 2006, I. Sarah Al-Shareef 14


Topic 2: Classes

x.print();
y.print();
}
Time::Time(int a, int b, int c) : hour(a),min(b),sec(c){}
//We have to include the keyword const in both prototype and
//definition header.
void Time::print() const
{
cout<<setw(10)<<hour<<’:’<<setw(2)<<min<<’:’
<<setw(2) <<sec;
}
void Time::set(int a, int b, int c)
{
hour = a; min = b; sec = c;
}

VIII. Constant Data Members:

As we know that every variable or object which is defined as constant


must be initialized.

But if we have a constant data members inside the class, we can’t


initialize them inside the class definition. We have to use the constructor with
initializer lists for the constant members.

Note:
We MUST initialize the constant data members with intializer lists in
constructor, so:
- If we don’t have a constructor when using constant data members, it’ll be
a syntax error.
- If we don’t’ use the initializer lists when using constant data members,
it’ll be a syntax error.

- If any member function tried to modify a constant data member, it’’ be a


syntax error.

Example 2.13: Using constant data members


class Person
{
char *name;
const char gender; //a constant data member
public:
Person(char *n=””,char g=’f’);
void print();
~Person();
};

© 2006, I. Sarah Al-Shareef 15


Topic 2: Classes

void main()
{
Person x(“Sami”,’m’);
x.print();
Person y(“Ola”, ‘f’);
y.print();
}
Person :: Person(char a[], char g): gender(g)
{
name = new char[strlen(a)];
strcpy(name, a);
}
void Person :: print()
{
cout<<”Hi my name is ”<<name;
if(toupper(gender)==’F’)
cout<<”. And I’m a girl.\n”;
else
cout<<”. And I’m a boy.\n”;
}
Person :: ~Person ()
{
delete name;
}

IX. Static Class Members:

If we declare two objects: x, y of class Time. Each object will have a


version or a copy of its own data members and functions.
So if the object x changes its hour. The hour in y will not be affected.

But sometimes we need to have a global data member for all objects such
as their count. Here when we need to use the static data members.

Object X Object Y

Private Static Private


Public Members Public Public Members Public
Members Functions Members Members Functions

Object X and Y has the If any object change the value


same version of static of static member, it will be
members seen by other objects too.

© 2006, I. Sarah Al-Shareef 16


Topic 2: Classes

Declaring a Static Data Member:


We put the keyword static before the data declaration.
Syntax :
static type name;

Initializing a Static Data Member:


We can initialize it once only outside the class definition. We don’t
include the keyword static outside the class definition. As following:
Syntax :
type class_name :: name = value;

Accessing a Static Data Member:


- Static data members can be declared as public or private.
- If the they were public, they can be accessed from outside the object
through:
o Object name as usual object_name.name
o Class name class_name::name
- If they were private, they can be accessed through a member functions
only.
- To access the static members from member functions, we use their name
directly even if they were private.

Object X Object Y

Private Static Private


Public Members Public Public Members Public
Members Functions mem Members Functions

cout<<mem;
cout<<x.mem;
cout<<y.mem;
cout<<className::mem;

Example 2.14: Using static data members


class Person
{
char *name;
public:
static int count;
Person(char *n=””);
~Person();
};

© 2006, I. Sarah Al-Shareef 17


Topic 2: Classes

void main()
{
//We can use the static members through the class name
//even before we declaring any objects.
cout<<”No. of objects: ”<<Person::count;
Person x(“Ali”); //Person::count=1

//We also can access the static members through an


//object name.
cout<<”No. of objects: ”<<x.count;

{
Person y(“Sami”); //Person::count=2
cout<<”No. of objects: ”<<Person::count;
} //Person::count=1

cout<<”No. of objects: ”<<Person::count;


} //Person::count=0

//Initializing static member. We don’t include the keyword


//static here, it will be a syntax error if we do.
int Person::count = 0;

Person :: Person(char a[])


{
name = new char[strlen(a)];
strcpy(name, a);

//Accessing the static members inside member function


//by using their names directly.
count++;
}
Person :: ~Person ()
{
delete name;
count--;
}
As we mentioned before, if we declare a static data member as a private
we can access them through member functions only. But we can’t use member
functions unless we declare an object. i.e. we can’t access to the private static
data members if we have no objects defined. Unless we have a static member
function.

Static member function is a member function which can access static


members ONLY. It’ll be a syntax error if it access to non-static members.

© 2006, I. Sarah Al-Shareef 18


Topic 2: Classes

Declaring a Static Member Function:


We put the keyword static before the member function prototype inside
the class.
Syntax :
static return_type fun_name(parameters);
Defining a Static Member Function Outside the Class:
We define it as we define any member function. We don’t include the
keyword static outside the class definition:
Syntax :
return_type class_name::fun_name(parameters)
{ /*member function body */ }

Accessing a Static Member Function:


- As we did with static data member.

Example 2.15: Using static member functions


class Person
{
char *name;
static int count;
public:
static int getCount();
Person(char *n=””);
~Person();
};

void main()
{
//We can use the static members through the class name
//even before we declaring any objects.
cout<<”No. of objects: ”<<Person::getCount();
Person x(“Ali”); //Person::count=1

//We also can access the static members through an


//object name.
cout<<”No. of objects: ”<<x.getCount();

{
Person y(“Sami”); //Person::count=2
cout<<”No. of objects: ”<<Person::getCount();
} //Person::count=1

cout<<”No. of objects: ”<<Person::getCount();


} //Person::count=0

//Even when the static data is private we could initialize it


//outside the class.
int Person::count = 0;

© 2006, I. Sarah Al-Shareef 19


Topic 2: Classes

Person :: Person(char a[])


{
name = new char[strlen(a)];
strcpy(name, a);

//Accessing the static members inside member function


//by using their names directly.
count++;
}
Person :: ~Person ()
{
delete name;
count--;
}

X. Operations Allowed with Objects:

a. Assignment
We can assign one object to another.

Example 2.16: Assign one object to another.


class Person
{ char* name;
int age;
public:
Person(char *n=””);
void print();
~Person();
};
void main()
{
Person x(“Sami”), y;
x.print();

//Assignment is allowed between two objects of the


//same class
y=x;
y.print();
}
Person :: Person(char a[])
{
name = new char[strlen(a)];
strcpy(name, a);
}
Person :: ~Person ()
{ delete name; }
void Person::print()
{ cout<<” Hi! I’m ”<<name<<”.\n”; }

© 2006, I. Sarah Al-Shareef 20


Topic 2: Classes

b. Passing Objects to Functions


We can pass an object to a function as we do with any data type.
They are passed to functions by value. But if we want to pass them by
reference we have to put ‘&’ before the object name in the function
declaration and definition header.

Example 2.17: Pass object to function.


//displayAsc() is a function that will take two objects
//of class Person and display them in ascending order
//according to their ages.
//swap() is a function that will swap two objects
//together.
class Person
{ char* name;
int age;
public:
Person(char *n=””, int a=0);
void print();
int getAge() {return age;}
~Person();
};
void displayAsc( Person , Person ); //By-value
void swap( Person &, Person &); //By-reference
void main()
{ Person x(“Sami”,20), y(“Ali”,”18”);
display(x,y); //Call
x.print();
y.print();
swap(x,y); //Call
x.print();
y.print();
}
void displayAsc( Person a, Person b ) //By-value
{ if(a.getAge() < b.getAge())
{ a.print();
b.print();
}
else
{ b.print();
a.print();
}
}
void swap( Person &a, Person &b) //By-reference
{ Person temp=a;
a=b;
b=temp;
}
//Other member fuctions definition in Example 2.16

© 2006, I. Sarah Al-Shareef 21


Topic 2: Classes

c. Return Objects from Functions


We can return and receive an object or it’s address from a function.

Example 2.18: Return an object from function.


//Add() it get two objects of Time and returns their sum.
class Time
{ int hour, min, sec;
public:
Time(int a=0, int b=0, int c=0);
int getHour(){return hour;}
int getMin(){return min;}
int getsec(){return sec;}
void set(int a, int b, int c);
};
Time Add(Time, Time); //Prototype
void main()
{
Time x(1,2,3), y(4,5,6);
Time z = Add(x,y); //Call
}
Time Add(Time a, Time b) //Definition
{
int h = a.getHour()+ b.getHour();
int m = a.getMin() + b.getMin();
int s = a.getSec() + b.getSec();
Time result(h,m,s);
return result;
}
Time::Time(int a, int b, int c):hour(a),min(b),sec(c){}
void Time::set(int a, int b, int c)
{ hour=a; min=b; sec=c;
}

XI. Operator Overloading:

If we have this class of Time:


class Time
{
int hour, min, sec;
public:
Time(int a=0, int b=0, int c=0);
};

If we declare three objects of Time:


Time x(12,0,0), y(0,30,0), z;

The following statement will not be allowed:


z = x + y;

© 2006, I. Sarah Al-Shareef 22


Topic 2: Classes

Because x, y and z are user-defined type. And the operator + can’t decide
how to work with them. But it will be allowed if we tell the compiler how the
operator + will word with objects of class Time. This is called operator
overloading.

Operator overloading will be accomplished by declaring operator


functions, which are functions start with keyword operator followed by the
sign of the operator we want to overload or re-define.
These functions will be used as member functions.

Syntax of operator overloading prototype:


return_type operator sign(second_operand_if_any);

Syntax of operator overloading definition (outside the class):


return_type classN::operator sign(second_operand_if_any)
{ /* overloading body */

How to decide the parameters for an operator:


Operators are categorized based on how many operands it need to be
performed, for example:
A+B //Addition have two operand. i.e. Binary operation.
A ++ //Increment have one operand. i.e. Unary operation.

Back to class Time, if we have the three objects: x, y and z.


Time x(12,0,0), y(0,30,0), z;

If we want to overload the operator + to perform the addition of two Time


objects and return the sum Time:
z = x + y; //it’s same to: z = x.operator+(y);

So the prototype inside class definition for this operator will be:
Time operator +(Time a);

But if we want to make the operation of increment valid. This operation will
increase all members of Time by one, so it will have no return but just updating
the members:
x++; //It’s same to: x.operator++();

So the prototype inside class definition for this operator will be:
void operator ++();

© 2006, I. Sarah Al-Shareef 23


Topic 2: Classes

Example 2.19: Full program for overloading operator + and ++


class Time
{
int hour, min, sec;
public:
Time(int a=0, int b=0, int c=0);
int getHour(){return hour;}
int getMin(){return min;}
int getsec(){return sec;}
void set(int a, int b, int c);
Time operator +(Time);
void operator ++();
};
void main()
{
Time x(12,0,0), y(0,30,0), z;
z = x + y;
x++;
}
Time::Time(int a, int b, int c):hour(a),min(b),sec(c){}

void set(int a, int b, int c)


{ hour=a; min=b; sec=c; }
Time Time::operator +(Time a)
{
//Compute the new hours, minutes and seconds.
//Since hour, min and sec are private we can’t access
//them for the object ‘a’ so have to get its values by
//using the member functions.
int h = hour+ a.getHour();
int m = min + a.getMin();
int s = sec + a.getSec();

//Declare a new Time object and initialize it to the


//result values.
Time result(h,m,s);

//Return the object result.


return result;
}
void Time::operator ++()
{
hour++;
min++;
sec++;
}

Note:
- Here are some of the common operators that can be overloaded:
o Arithmetic: + – * / % ++ – –

© 2006, I. Sarah Al-Shareef 24


Topic 2: Classes

o Assignments: += –= *= /= %= =
o Relational: == > < >= <= !=
o Boolean: ! || &&
- We can have more than one version of the overloaded operator since the type
of the second operand is differ.

Example 2.20: Another operator + overloading


class Time
{
int hour, min, sec;
public:
Time(int a=0, int b=0, int c=0);
int getHour(){return hour;}
int getMin(){return min;}
int getsec(){return sec;}
void set(int a, int b, int c);
Time operator +(Time);
Time operator +(int);
void operator ++();
};

void main()
{
Time x(12,0,0),y;
y = x + 10;
}
//See member functions definition in Example 2.15
//Here is the second version of overloaded operator +
Time Time::operator +(int a)
{
//Compute the new hours, minutes and seconds.
int h = hour+ a;
int m = min + a;
int s = sec + a;

//Declare a new Time object and initialize it to the


//result values.
Time result(h,m,s);

//Return the object result.


return result;
}

XII. Array of Objects:

a. Declaration Syntax:
Class_Name objName[row_number];

© 2006, I. Sarah Al-Shareef 25


Topic 2: Classes

Person x[2]; //x is an array of 2 elements of Person

//the first object element is x[0].


//So to access members of the first element is:
//x[0].print();

//the second object element is x[1].


//So to access members of the second element is:
//x[1].print();

b. Initialization Syntax:
Class_name objName[row_number]={ Class_name(mem1, mem2),
Class_name(mem1,mem2),...};

To initialize an array of objects, we must have a constructor that will take


parameters.

Example 2.21: Using Array of Objects


class Person
{ char* name;
int age;
public:
Person(char *n=””, int a=0);
void print();
void set(char *n, int a);
~Person();
};

//This function will display all elements of the array.


void display(Person [], int);

void main()
{
//Declare an array and initialize part of it.
Person family[4]={Person(“Sami”,7),Person(“Ali”,8)};

//Set the other elements using member functions


family[2].set(“Ola”,35);
family[3].set(“Omar”,40);

//Send the array to the function


//Array will be sent by-reference.
display(family,4);
}
void display(Person f[], int size);
{
for(int i=0; i<size; i++)
f[i].print();
}

© 2006, I. Sarah Al-Shareef 26


Topic 2: Classes

Person :: Person(char a[])


{
name = new char[strlen(a)];
strcpy(name, a);
}
Person :: set(char* n, int a)
{
delete name; //To remove the previous name
name = new char[strlen(a)];
strcpy(name, a);
}
Person :: ~Person ()
{ delete name;
}
void Person::print()
{ cout<<” Hi! I’m ”<<name<<” and I’m ”<<age<<”.\n”;
}

© 2006, I. Sarah Al-Shareef 27

Você também pode gostar