0% found this document useful (0 votes)
17 views

Chapter 3

Uploaded by

athilahnurin03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter 3

Uploaded by

athilahnurin03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

LECTURE 3

INTRODUCTION TO CLASSES
AND OBJECTS IN C++

Objective

At the end of this lecture, students should be able to :

 Understand the concept of classes.


 Declare and define class.
 Use the operations done by classes.
 Declare objects.
 Understand and use inline functions.

MULTIMEDIA UNIVERSITY 1
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3.0 Class

 A class is a blueprint or prototype that defines the variables (data) and methods (code)
common to all objects of a certain kind.
 The class serves as a user defined type.
 A class thus defines a data type that behaves like the built-in types of a programming
language.
 An object is an individual instance of a class.
 Access to the variables and methods declared in a class depend on whether they are
declared private or public.
 A variable declared as public is visible everywhere.
 A variable declared private is not visible outside the class.
 Classes contains a few objects.

General format in declaring classes :

class ClassName
{
// Data definition
// Method
definition
};

 Keyword class is a must in defining a class.


 Semicolon ( ; ) must be placed after closing braces each time you define a class.
 Example of class definition

Keyword for defining a class

Data member definition


ClassName

class Rectangle
{ int length, width;
public :

void set_data (int x,int y)


Access control { length=x;
width=y;
} Method definition

double calculate_area()
{ return length*width}
};

MULTIMEDIA UNIVERSITY 2
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3.1 Methods

 Methods are functions used to manipulate the data members of a class.


 Methods are written to do specific operations on the data member as needed by the user.
 There are two ways of defining method:
1. Define it in the class.
2. Using scope resolution operator (::) to define it outside the class.

1. The example below shows how to define a method in class.

class Student
{
int ID,age;
char name[30];
double mark;

public:
void set_data (int a,int b, char * c, double d)
{
ID=a;
age=b;
strcpy(name,c);
mark=d;
}
};

2. Example below shows how to define a method outside the class using the
scope resolution operator ( :: ).

class Student
{
int ID,age;
char name[30];
double mark;

public:
void set_data (int a,int b,char * c,double d);
};
Value that
will be return void Student::set_data(int a,int b,char * c,double d)
{
ID=a;
age=b;
strcpy(name,c);
mark=d;
}

Class name
Parameter list

Function/Method name

MULTIMEDIA UNIVERSITY 3
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3.2 Access control

 Data members and methods can be declared using access control to specifically specify
access to members of the class.
 There are three types of access control:
1. Public
2. Private
3. Protected
 Class members are private members by default but the situations can be changed by
using another keyword. For example, using public and protected keyword.

1. Public

 Public members are accessible from outside and also inside of the class
(for example in main() function).
 Members in the class must be declared in the public section to make it
accessible from outside the class.
 Definition of friend does not give any effect to this access control.
 Example of the use of this keyword in the real world: student name,
semester.

#include<iostream.h>

class SQUARE
{
public:
int length; //data member
void change(); //method
}S1;

void SQUARE :: change()


{
length = 24;
}

void main()
{
cout<<"length : "<<S1.length<<endl;
S1.length = 100;
cout<<"length : "<<S1.length<<endl;
S1.change();
cout<<"length : "<<S1.length<<endl;
}

 The program above shows the usage of public access mode.


 Data member length is declared as public, so the value of length can be set
using a method called change() or it can be set straight from the main().

MULTIMEDIA UNIVERSITY 4
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

2. Private

 Private members can only be retrieved by functional members and friends for
a class, which has been declared.
 Declaration of friend will not cause any effect to the access control.
 Example of the use of this keyword in the real world:
Usernames and passwords to open an e-mail or banking accounts is declared
privately so that it is not accessed by any other unauthorized person.

#include<iostream.h>

class SQUARE
{
private:
int length;//data member
public:
void display();
}S1;

void SQUARE :: display()


{
length = 100;
cout<<"length : "<<length<<endl;
}

void main()
{
cout<<"length : "<<S1.length<<endl;
S1.display();
}

 Observe the above code.


 The statement cout<<"length : "<<S1.length<<endl; is not valid.
 This is because length is declared to be a private data member, which can only
be retrieved using a member function.
 The correct way of accessing data member length is S1.display();

MULTIMEDIA UNIVERSITY 5
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3. Protected

 Protected members are accessible in the class where it is declared and also
any other classes, which are inherited from that class.
 Definition of friend does not give any effect to this access control.
 Will be explained in later chapters

MULTIMEDIA UNIVERSITY 6
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3.3 Class Operations

 Constructor
o Create data storage for an object in memory space.
o A constructor is automatically called whenever an instance/object of a class is
created.
o Must be the same name as the class name.
o A constructor has no return type.

 Destructor
o Release any computer resources, which has been specified to an object.
o A destructor has no return type.

Constructor name must be same as the class name

class Employee
{
public :

Employee();/* constructor declaration */


~Employee();/* Destructor declaration */
};

Destructor name must also be same as the class name.


Must be added with “~” at the beginning of destructor

 I/O
o Enable data to be received as input or displayed as output.

cout<<”Enter Your GPA:”; Output


cin>>gp; Input

 Copying or cloning
o Enable an object to be copied but both of the objects must be of the same type.

Both object R1 and R are objects which are of the Rectangle R,R1;
same type. Therefore object copying can be done.
R1=R;

 Iterator
o At is used for a class, which has a collection of data item. By using iterator, each
data can be accessed individually.
class sequentialList
{ private :
Iterator int item[MAX] ,num_item;
public: ……………};

MULTIMEDIA UNIVERSITY 7
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

 Comparison operator
o Compare between one object with another, which are of the same type.

class AB
{ :
:
};
main()
{
AB ob1,ob2;
if(ob1==ob2)
cout <<”ob1 is equal to ob2”;
else
cout <<”ob1 is not equal to ob2”;
}

 Accessor
o Can access or compute values from object without doing any modification to the
object.

 Mutator
o Modify the object using certain ways (may be by changing one value or more value)

MULTIMEDIA UNIVERSITY 8
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

Example of a program which uses accessor and mutator

# include <iostream.h>
# include <string.h>

class student
{
// If the access method is not specified,
// by default it will be set to private

char id[20];
char name[30],status[15];
double gpa;

public:

//member functions prototypes

void set_data( char[], char[], double);


char* get_status();
void print_data();
};

//member functions declared outside of the class

void student::set_data(char i[20], char n[30], double gp)


{ This method will
strcpy(id,i);
strcpy(name,n);
change the value of
gpa=gp; data field
}

char* student::get_status()
{
if(gpa>=2.0)
strcpy(status,"PASS"); This method will manipulate the data
else
strcpy(status,"FAIL");
(gpa) but cannot change the value of
data field
return status;
}

void student::print_data()
{
cout<<"Student's id : "<<id<<endl;
cout<<"Student's name : "<<name<<endl;
cout<<"Student's gpa : "<<gpa<<endl;
}

main()
{
student s; // create an object called s
char name[30],id[10];
double gp;
Output
cout<<"Enter your name:";
cin.getline(name,30);
cout<<"Enter your ID:"; Enter your name:Albert
cin.getline(id,10); enter your ID:1234
cout<<"Enter Your GPA:"; Enter Your GPA:3.33
cin>>gp;
cout<<'\n'; Student's id : 1234
s.set_data(id,name,gp);
Student's name : Albert
s.print_data();
cout<<"Status : "<<s.get_status(); Student's gpa : 3.33
cout<<'\n'; Status : PASS
return 0;
} Press any key to continue

MULTIMEDIA UNIVERSITY 9
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3.4 Objects

 Objects are the basic entities in an object-oriented system.


 Each object is denoted by a name and has state.
 The variables within the object express everything about the object (state) and the
methods specify how it can be used (behavior).
 For example, a bicycle has a state (the number of wheels and the current gear), and
behavior (braking, accelerating, slowing down, changing gears).
 So what is a method? A method is a function or procedure that has access to the internal
state of the object needed to perform some operation.

Declaring an object

 Syntax: className objectName;

 Example:
Assuming that you have created an object from the class Staff. Example of declaration is
shown as below:
Staff S1;
 When an object has been declared, it can be manipulated by any function, which is
declared inside the object class.
 Syntax is used to call a data or method: ObjectName . MemberName

Dot operator

 Object of type Staff is accessible by the members from Staff class only.

MULTIMEDIA UNIVERSITY 10
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

 Example of object creation in a class and also in the main() function.

#include<iostream.h>
#include<string.h>

class Staff
{
private :
char staff_name[30];
int staff_id;

public :
void get_input()
{
strcpy(staff_name, "David Johnson");
staff_id = 1234;
}

void display()
{
cout<<"Staff Name : "<<staff_name<<endl;
cout<<"Staff ID : "<<staff_id<<endl;
}
}S1, S2; Object declaration in class

void main()
{
Staff S3; Object declaration in main()
S3.get_input();
S3.display();
}

MULTIMEDIA UNIVERSITY 11
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

 Example below shows how an object can access members from a class.

#include<iostream.h>
#include<math.h>

class Square
{
//by default length is private
int length;

public:

void set_data(int x)
{
length=x;
}
double area()
{
return pow(length,2);
}
};

void main ()
{
// object declaration
Square S1, S2;

// not valid because length is a private data


S1.length = 10;

//this statement is valid


// it calls method set_data() to set the value of length
S2.set_data(12);

cout<<"Area of S2 is:"<<S2.area()<<endl;

Object list

 You can declare as many objects as you want from the same class.
 The example shows how objects are declared from the a class.

Class Box
{
private:
int length, width;
public:
void set_data();
}B1, B2;

void main()
{
Box B3, B4;
}

MULTIMEDIA UNIVERSITY 12
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

Array of objects

 The syntax for declaring an array of objects is the same as declaring an array of any
variables.
 The way of accessing array of object is also the same as accessing an array of any
variables.
 Example shown below is a program, which has an object samp with four array elements.

#include<iostream.h>

class Box
{ Output
//by default length is private
int length, width;
Area of B[0] is:0
public: Area of B[1] is:2
Area of B[2] is:6
void set_data(int x, int y) Area of B[3] is:12
{ Area of B[4] is:20
length=x;
width = y; Press any key to continue
}
double area()
{
return length * width;
}
}B1[5];

void main ()
{

for (int i = 0; i <= 4 ; i++)


B1[i].set_data(i, i+1);

for (i = 0; i <= 4 ; i++)


cout<<"Area of B["<<i<<"]"<<" is:"<<B1[i].area()<<endl;

 This program has an object B1, which has 5 array elements where each element has the
value between 0 to 4.

MULTIMEDIA UNIVERSITY 13
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

Assigning object

 An object can be assigned to another object given that both of the objects must be of
the same type.
 Automatically, when an object is assigned to another object, all data members will be
copied.
 Example below shows how an object is assigned to another object.

#include<iostream.h>

class Box Output


{
//by default length is private
int length, width; BEFORE COPYING B1 TO B2
Area of B1 is:12
public: Area of B2 is:10
void set_data(int x, int y)
{
AFTER COPYING B1 TO B2
length=x; Area of B1 is:12
width = y; Area of B2 is:12
} Press any key to continue
double area()
{
return length * width;
}
}B1;

void main ()
{
Box B2;

B1.set_data(3,4);
B2.set_data(5,2);

cout<<"BEFORE COPYING B1 TO B2"<<endl;


cout<<"Area of B1 is:"<<B1.area()<<endl;
cout<<"Area of B2 is:"<<B2.area()<<endl;

B2 = B1;

cout<<"AFTER COPYING B1 TO B2"<<endl;


cout<<"Area of B1 is:"<<B1.area()<<endl;
cout<<"Area of B2 is:"<<B2.area()<<endl;
}

MULTIMEDIA UNIVERSITY 14
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

Passing object to function

 An object can be passed to a function. When an object is passed to a function,


automatically all data members for that object will be sent to the function.
 Any changes done to the object passed to a function does not give any effect to the
object. (Which is used as argument to the function)
 The example below shows how an object is passed to a function.

# include <iostream.h>

class OBJECT
{ int length;
public:
void set_length (int x)
{
length=x;
}

void print()
{
cout<<length<<endl;
}
};

void PRINTOBJ (OBJECT X)


{
X.print(); //output 10
X.set_length(100); // this only effect on the copy in the function
X.print(); //output 100
}

void main()
{
OBJECT OB;
OB.set_length(10);
PRINTOBJ(OB);
OB.print(); // the output remain 10, value of length has not
// been changed
}

Output
10
100
10
Press any key to continue

Pointer to object

 You can access an object either by direct access or using pointer to object. Recall: A
pointer to an object is a variable that contains the memory address of another object.
 In order to access the specified element in an object
o dot operator (.) can be used, with indirection operator(*)
o arrow operator (->) instead of the dot operator. This -> is called the indirect
member access operator.
 The syntax to declare a pointer to an object is shown as below:

MULTIMEDIA UNIVERSITY 15
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

#include<iostream>
using namespace std; * Name of pointer to an object
class Point{
private: double x, y, z;
public:

void set_val(double x_arg, double y_arg, double z_arg){

x=x_arg;
y=y_arg;
z=z_arg;
}
double X( ){return x;}
double Y( ){return y;}
double Z( ){return z;}

};

void main( ){
Point p;

p.set_val(1.0,2.0,3.0);

Point *p_ptr; Declaring a pointer of type Point


p_ptr = &p;

cout<<"accessing through object"<<endl;


cout << p.X( ) << endl;
cout << p.Y( ) << endl; The memory address of object p is assigned to p_ptr
cout << p.Z( ) << endl;

cout<<"accessing through pointer object"<<endl;


cout << (*p_ptr).X( ) << endl;
cout << (*p_ptr).Y( ) << endl; Invoking member functions through pointer to
cout << (*p_ptr).Z( ) << endl; object using (.) and *
cout<<"using ->"<<endl;
cout<<p_ptr -> X( ) <<endl; Invoking member functions through pointer to
cout<<p_ptr -> Y( ) <<endl; object using ->
cout<<p_ptr -> Z( ) <<endl;

cout<<"Modifying x, y, z values of object p through pointer p_ptr"<<endl;


(*p_ptr).set_val(5.0,6.0, 7.0);
Invoking member function through
cout<<"accessing through pointer object"<<endl; pointer to change values of x, y, z. This
cout << (*p_ptr).X( ) << endl; will also change the values of the
cout << (*p_ptr).Y( ) << endl; original object that this pointer is
cout << (*p_ptr).Z( ) << endl; pointing to
cout<<"using ->"<<endl;
cout<<p_ptr -> X( ) <<endl;
cout<<p_ptr -> Y( ) <<endl;
cout<<p_ptr -> Z( ) <<endl;

cout<<"accessing through object"<<endl;


cout << p.X( ) << endl;
cout << p.Y( ) << endl;
cout << p.Z( ) << endl;

MULTIMEDIA UNIVERSITY 16
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

accessing through object


Output: 1
2
3
accessing through pointer object
1
2
3
using ->
1
2
3
Modifying x, y, z values of object p through pointer p_ptr
accessing through pointer object
5
6
7
using ->
5
6
7
accessing through object
5
6
7
Press any key to continue

MULTIMEDIA UNIVERSITY 17
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

Pass by reference with pointers, objects to functions


#include<iostream>
using namespace std;

class TheClass
{
private:
int a,b;
public:
void SetValues(int aa, int bb)
{
a=aa;
b=bb;
PrintValues();

void PrintValues(){
cout<<"a : "<<a<<", b : "<<b<<endl;

};
Prototypes includes pointers
void Func2(TheClass*);

void main() address of obj is passed to a pointer of TheClass, meaning ptr


{ contains a memory address of obj. Using *ptr, we can access the
values of the data members of obj and invoke the operations from
TheClass obj; the class.
Func2(&obj);
obj.PrintValues();
This will call PrintValues to print out the values of the obj
}

void Func2(TheClass *ptr)


{
ptr->SetValues(2,3); When using a pointer object, we need to use -> to invoke the class
} member function. We can also use in this case:
(*ptr).SetValues(2,3)
Output:
a : 2, b : 3
a : 2, b : 3
Press any key to continue

Note: The first line is through pointer, the second line is the output through the object. Notice
that when a pointer is pointing to an object (when you assign the address of an object to a
pointer), the pointer can modify the properties of the object by invoking the member functions
defined in the same class of the object.

Pass by reference with reference parameters, objects to functions

#include<iostream>
using namespace std;

class TheClass
{
private:
int a,b;
public:

MULTIMEDIA UNIVERSITY 18
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

void SetValues(int aa, int bb)


{
a=aa;
b=bb;
PrintValues();

void PrintValues(){
cout<<"a : "<<a<<", b : "<<b<<endl;

};

void Func2(TheClass&); Prototype has reference types

void main()
{

TheClass obj;
Func2(obj); Pass the address of obj implicitly to &ref
obj.PrintValues();

void Func2(TheClass &ref)


{
ref.SetValues(2,3);
}

Output:
a : 2, b : 3
a : 2, b : 3
Press any key to continue

Note: See that output is the same as the example(pass by pointer) example above. The
difference in the program is just the function prototype, call and actual function. There are no
changes to the class

MULTIMEDIA UNIVERSITY 19
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

3.5 Inline function

 The purpose of applying the inline function is to increase efficiency in executing a


program.
 In an inline function, rather than transferring control to a called function, the called
function’s code replaces the call in the calling function.
 A good inline function is a function that is smaller in size.
 The function, which is big in size, is unsuitable to be an inline and should remain as
normal.
 When the compiler expands the inline function, it actually replaces each of the
occurence with the function’s definition(the actual code of the function).
 The advantage in using inline function is that tha overhead of the function call is
avoided so that the program can be executed more efficiently.
 The inline function is expanded by the compiler and not by the processor
 We can make an inline function by using these technique:
1. Explicit Inline Definition (outside of the class).
2. Implicit Inline Definition (inside the class).

1. Explicit Inline Definition (outside of the class).

 When a class function is defined explicitly outside of the class, the


function declaration in the class must have the inline function specifier.
 This is replaced at the beginning of the function prototype.
 Example of a program which uses the explicit inline definition

#include<iostream.h>

class SQUARE
{
private:
int length;
Output
public:
inline void set_length();
inline void display(); Length : 10
}SQ1; Press any key to continue
void SQUARE :: set_length()
{
length = 10;
}

void SQUARE :: display()


{
cout<<"Length : " <<length<<endl;
}

void main()
{
SQ1.set_length();
SQ1.display();
}

MULTIMEDIA UNIVERSITY 20
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

2. Implicit Inline Definition (inside the class).

 An inline function can also be defined in a class by coding it in the class


declaration itself.
 In this case, no function declaration is needed, and the function is defined
without the function specifier inline.

#include<iostream.h>

class SQUARE
{
private:
int length;

public:
void set_length() // automatically inline
{
length = 10;
}
void display()// automatically inline
{
cout<<"Length : " <<length<<endl;
}
}SQ1;

void main()
{
SQ1.set_length();
SQ1.display();
}

MULTIMEDIA UNIVERSITY 21
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 3

Summary through example:

# include <iostream.h>
# include <string.h>

class club Class definition


{
char id[10],name[30], status[15];
int point;

public: Access control


club(void) Constructor
{cout<<"\nWelcome To The Club";
cout<<'\n';}

~club(void)
{cout<<"\nThank You";} Destructor
void set_data(char [], char [], int);
void print_data();
char* get_status();
};

void club::set_data( char a[], char b[], int pt) Mutator


{
strcpy(id, a);
strcpy(name,b);
point = pt; Iterator
}

char* club::get_status()
{ Accessor
if(point >= 1000)
strcpy(status,"VIP");
else Comparison
strcpy(status,"Executive");
return status;
}

void club::print_data()
{
cout<<"ID: "<<id<<endl;
cout<<"Name: "<<name<<endl; I/O
cout<<"Point: "<<point<<endl;
}

int main()
{ Object declaration
club s, s1;
char name[30], id[10];
int pt;

cout<<"Enter your name: ";


cin.getline(name, 30);
cout<<"Enter your ID: ";
cin.getline(id, 10);
cout<<"Enter your point: ";
cin>>pt;
cout<<'\n';
s.set_data(name, id, pt);
Object is accessing member of a class
s.print_data();

cout<<s.get_status()<<endl;
cout<<'\n';

s1=s;
Copying and cloning
s1.print_data();
cout<<s1.get_status()<<endl;
return 0;
}

MULTIMEDIA UNIVERSITY 22

You might also like