Professional Documents
Culture Documents
DITP 2113 Struktur Data & Algoritma: Lecture 1: Class & Object
DITP 2113 Struktur Data & Algoritma: Lecture 1: Class & Object
2
Class & Object
Data hiding : it is implemented by combining the data and
operations into an object.
The data in the class are physically located inside the class
object and therefore can be hidden from the application
program.
It cannot be accessed or changed except by functions
or methods that are part of the class.
Data hiding is important to ensure the data integrity.
A class is able to encapsulate the data structure and the
data operations inside the class (as one entity or collection)
and only allow access through controlled methods.
3
Class & Object
Encapsulation has several advantages:
Easy to access any information regarding the class.
Any other classes that need to interact with the class
doesn’t need to know about what’s inside the class
or how it works.
A class describes the attributes that each object includes
as a variable and it is also known as data member.
For example: name, age, accountNum, numOfTyre
A class describes the behaviors (operations) that each
object exhibits through functions or methods.
For example: setAccount(), getAge(), calcAve()
The functions will use the data members in its operations.
4
Access Specifiers
There are three access specifiers that can be used with
either the class member data or the member functions
(methods).
private: the data or functions can only be accessed by
the member of the class
public: the data or functions can be accessed by the
member of the class and other classes
protected: the data or functions can be accessed by
the member of the class and its subclasses
5
Access Specifiers
6
Class Declaration
Class Declaration Syntax
class ClassName {
private:
//private attribute and method();
public:
//public attribute and method();
};
Example:
class Fraction {
private:
int numerator;
int denominator;
public:
void store (int numer, int denom);
void print ();
};
7
Object Declaration
Defining an object of a class type is called instantiation.
Each instance of a class is known as an object.
Object Declaration Syntax :
Class_Name object_Name;
8
Object Declaration
Scope resolution operator ‘::’ is used when an identifier
that is referred to is not within the current scope.
For example, the function definition is defined outside of
the class.
Therefore, it is needed to use scope resolution operator to
specify that the function is belong to the class.
Syntax Declaration: Class_Name :: member_name
Example:
void Fraction :: store (int numer, int denom)
{ }
9
Program Example
Example: Creating a class and using object to refer to data member and
functions.
#include<iostream>
using namespace std;
//Header file for simple Fraction class.
class Fraction {
private:
int numerator;
int denominator;
public:
void store (int numer, int denom);
void print () const;
};
//Methods definition
void Fraction :: store (int numer, int denom) {
numerator = numer;
denominator = denom;
}
void Fraction :: print () const {
cout << numerator << “/” << denominator;
} 10
Program Example
Example: Creating a class and using object to refer to data member and
functions (cont).
//Create object and use Fraction class.
int main() {
int numer;
int denom;
Fraction frac;
cout << “This program creates a fraction\n”;
cout << “Please enter the numerator: ”;
cin >> numer;
cout << “Please enter the denominator: ”
cin >> denom;
frac.store(numer, denom);
cout << “\nYour fraction contains: ”;
frac.print();
return 0;
}
11
Program Example
Example: Creating a class and using object to refer to data member and
functions (cont).
15
Constructor & Destructor
Destructor are the opposite of constructors. It is used
when the object dies, either because it is no longer in
scope or it has been deleted.
A destructor cannot have a return type.
The argument list of the destructor must be empty.
It cannot be overloaded.
The name of the destructor is the name of the class
preceded by a tilde (~).
Class_Name :: ~Class_Name() { }
A class must have one and only one destructor.
A destructor usually is a default destructor. It does nothing.
But if there is a class uses dynamic memory allocation, it is
needed to release memory in the destructor.
16
Program Example
Example: Creating a class and using object to refer to constructors.
#include<iostream>
using namespace std;
//Fraction class declaration. –Filename: Fraction.cpp
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction ();
Fraction (int numer);
Fraction (int numer, int denom);
~Fraction() { } //destructor
void print () const;
};
19
Program Example
Example: Creating a class and using object to refer to constructors (cont).
20
Mutators & Accessors
The data member of the class is usually private. This is
to assure the data integrity. In order to access the data,
the class should have certain method to control data
usage.
The methods of the class is usually public and accessible
to the member of the class and other classes.
There are two types of functions:
Mutator Functions
Accessor Functions
21
Mutators & Accessors
An accessor is a function that cannot change the state of
its invoking object.
It is called either for its side effects such as to print or for
its return value.
Accessor must always have a return type.
By adding the keyword const is to ensure that an accessor
does not change the state of the host object.
It is also known as the get() method.
22
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods.
//Account class declaration. – Filename: Account.cpp
#include <iostream>
#include <iomanip>
using namespace std;
class Account {
private:
double balance;
public:
Account ();
double getBalance () const;
void deposit (double amount);
void withdraw (double amount);
};
23
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods (cont).
//Constructor definition – without parameter
Account :: Account () {
balance = 0.0;
}
Account acc;
acc.deposit(100.0);
cout << “Your account balance is : ”
<< setw(5) << acc.getBalance() << endl;
acc.withdraw(50.0);
cout << “Your account balance is : ”
<< setw(5) << acc.getBalance() << endl;
return 0;
}
25
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods(cont).
26
Interface & Implementation
The separation of program interface and its implementation
will ease of the programmer to read or change the program.
27
Interface & Implementation
The class declaration is usually kept in the header files
(.h or .hpp) while the definition for methods is kept in a
source files (.cpp) that usually has the same name as the
header.
The class implementation is kept in another source files
(.cpp). It has to include all classes needed.
28
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods.
public:
Account ();
double getBalance () const;
void deposit (double amount);
void withdraw (double amount);
};
#endif
29
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods (cont).
Account :: Account () {
balance = 0.0;
}
double Account :: getBalance () const {
return balance;
}
void Account :: deposit (double amount) {
balance += amount;
}
void Account :: withdraw (double amount) {
balance -= amount;
}
30
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods (cont).
//Program implementation – Filename: AccountMain.cpp
#include <iostream>
#include <iomanip>
#include “Account.h”
using namespace std;
int main() {
Account acc;
cout << “Your account balance is : ”
<< setw(5) << acc.getBalance() << endl;
acc.deposit(100.0);
cout << “Your account balance is : ”
<< setw(5) << acc.getBalance() << endl;
acc.withdraw(50.0);
cout << “Your account balance is : ”
<< setw(5) << acc.getBalance() << endl;
return 0;
}
31
Program Example
Example: Maintain a bank account balance using deposit and withdraw
methods(cont).
32
Interface & Implementation
The preprocessor code as shown in the example:
#ifndef ACCOUNT_H
#define ACCOUNT_H
….
#endif
33
Using other class members
A class (base class) that always being used by other
classes needs to avoid using access specifier private for
its members.
The accessibility for data member is usually a private.
The solution for this is by using the access specifier
protected to allow the derived classes to use the data
member from the base class.
The derived class is allowed to use all protected and public
data member and methods from the base class.
This concepts is also known as inheritance.
34
Program Example
Example: Using protected for data member
class Account {
protected:
int accNum;
char *name;
public:
Account ();
double openAcc (const int, const char*);
void printAcc ();
};
#endif
35
Program Example
Example: Using protected for data member (cont).
//Source files – Filename: Account_v3.cpp
#include <iostream>
#include <cstring>
#include “Account_v3.h”
Account :: Account () {
accNum = 0;
strcpy(name, “”);
}
void Account :: openAcc (const int num, const char *pname)
{
accNum = num;
strcpy(name, pname);
}
void Account :: printAcc () {
cout << “Account Number: ” << accNum << endl;
cout << “Name : ” << name << endl;
}
36
Program Example
Example: Using protected for data member (cont).
public:
Current ();
void deposit (const double);
void printBalance ();
};
#endif
37
Program Example
Example: Using protected for data member (cont).
//Source files – Filename: Current.cpp
#include <iostream>
#include “Account_v3.h”
#include “Current.h”
using namespace std;
Current :: Current () {
balance = 0.0
}
void Current :: deposit (const double dep) {
balance += dep;
}
void Current :: printBalance () {
cout << “From current Account:\n”;
cout << “Current Account Number: ” << accNum << endl;
cout << “Name : ” << name << endl;
cout << “Balance account: ” << balance << endl;
}
38
Program Example
Example: Using protected for data member (cont).
//Program implementation – Filename:
CurrentAccountMain.cpp
#include “Account_v3.h”
#include “Current.h”
using namespace std;
int main() {
Current acc;
acc.openAcc(111, “Milah”);
acc.printAcc();
acc.deposit(1000.0);
acc.printBalance();
acc.deposit(50.0);
acc.printBalance();
return 0;
}
39
Program Example
Example: Using protected for data member (cont).
40
Overloading
Overloading is the definition of two or more methods using
the same name.
Every methods must have different parameters.
The compiler will recognize the methods from its different
parameters and signature.
Example:
void calcAve(); //return nothing, no parameter
void calcAve(int num); //return nothing, 1 parameter
int calcAve(int n, int s); //return integer, 2 parameter
41
Program Example
Example: Calculate average for numbers.
public:
Average ();
~Average ();
void calculate (int, int);
void calculate (double, double, double);
};
#endif
42
Program Example
Example: Calculate average for numbers (cont).
Average :: Average () {}
Average :: ~Average () {}
int main() {
Average avei, aved;
avei.calculate(4,4);
aved.calculate(2.5,2.5,2.5);
return 0;
}
44
Overloading
Program Description:
The calculate() method will be called according to
its equivalent parameter with the data send by its caller.
From the program, object avei will call the first
calculate() method that will receive two integers
while object aved will call the second calculate()
method that has three double parameters.
45
Program Example
Example: Calculate total for numbers.
public:
Addition ();
Addition(int);
Addition(int, int);
~Addition ();
void calculate ();
};
#endif
46
Program Example
Example: Calculate total for numbers (cont).
//Source files – Filename: Addition.cpp
#include “Addition.h”
#include <iostream>
using namespace std;
Addition :: Addition () {
x = y = 0;
}
Addition :: Addition (int a) {
x = a;
y = 1;
}
Addition :: Addition(int x1, int y1) {
x = x1;
y = y1;
}
Addition :: ~Addition() { }
int main() {
Addition tot, total(1), sum(2,2);
tot.calculate();
total.calculate();
sum.calculate();
return 0;
}
Total: 0
Output: Total: 2
Total: 4
48
Overriding
Overriding allow the programmer to change the program
implementation in the base class to be included and use in the
derived class.
When the object is created for the derived class, the current
method inside the derived class will be called rather than the
original method in the base class.
The override method must have the same name with the
original method but it doesn’t necessary to have the same
signature or function prototype.
The implementation of the override method can be different
or not.
49
Overriding
The difference between overloading and overriding:
The overloading concepts happens in the same class.
The overriding concepts happens between two different
classes that are the base class and its derived classes.
50
Program Example
Example: Overriding method.
public:
Mammal ();
~Mammal ();
void setAgeWeight (int, double);
void sleep (); //original method
void eat ();
};
#endif
51
Program Example
Example: Overriding method (cont).
//Source files – Filename: Mammal.cpp
#include “Mammal.h”
#include <iostream>
using namespace std;
Mammal :: Mammal () { }
Mammal :: ~Mammal () { }
void Mammal :: setAgeWeight(int a, double w) {
age = a;
weight = w;
}
void Mammal :: sleep() {
cout << “At the age of ” << age
<< “ years old I like to sleep.\n”;
cout << “Shhhhhhh\n” << endl;
}
void Mammal :: eat () {
cout << “I eat until my weight reach ”
<< weight << endl;
}
52
Program Example
Example: Overriding method (cont).
53
Program Example
Example: Overriding method (cont).
//Source files – Filename: Cat.cpp
#include “Mammal.h”
#include “Cat.h”
#include <iostream>
using namespace std;
Cat :: Cat () { }
Cat :: ~Cat () { }
54
Program Example
Example: Override method (cont).
int main() {
Mammal Dino;
Cat Siti;
Dino.setAgeWeight(400, 1050.34);
Siti.setAgeWeight(12,25.6);
cout << “The original method sleep\n”;
Dino.sleep();
cout << “The override method sleep\n”;
Siti.sleep();
return 0;
}
55
Program Example
Example: Override method (cont).
The derived class object can call the original method by:
derived_class_object.Base_Class_Name::method();
Example:
Siti.Mammal::sleep();
56
Friend
A class can grant friend status to a nonmember function or
to another class. All member functions of the class granted
friendship have unrestricted access to the members of the
class granting the friendship.
Class friendship is not reciprocal; the member functions of
the class granting friendship cannot access the members of
the friend class.
Class friendship is granted in the prototype declarations of
the granting class.
class FirstClass {
friend class SecondClass;
private:
………
}
57
Friend
The programmer can use the friend concept to allow other
classes to access private data members or functions.
For example, class B use friend concept to access data from
class A. Class A will grant the friendship to class B. All data
members or functions in class A will be public to Class B.
Friend can not be transferred or inherited.
For example, although Siti and Minah is a friend while Siti is
also a friend to Dayang but doesn’t mean that Minah and
Dayang is a friend.
Another example, although Siti and Minah share secrets
together doesn’t mean that Siti wants to share the secrets with
Minah’s children.
58
Program Example
Example: Friend concept.
public:
FirstClass ();
~FirstClass ();
void setX (int);
void printData ();
};
#endif
59
Program Example
Example: Friend concept (cont).
//Source files – Filename: FirstClass.cpp
#include “FirstClass.h”
#include <iostream>
using namespace std;
FirstClass :: FirstClass () {
x = 5;
}
FirstClass :: ~FirstClass () { }
61
Program Example
Example: Friend concept (cont).
//Source files – Filename: SecondClass.cpp
#include “SecondClass.h”
#include “FirstClass.h”
#include <iostream>
using namespace std;
SecondClass :: SecondClass () {
y = 2;
}
SecondClass :: ~SecondClass () { }
62
Program Example
Example: Friend concept (cont).
int main() {
SecondClass S;
FirstClass M;
cout << “Y from Second Class\n”;
S.print(M);
M.setX(4);
cout << “X from First Class\n”;
M.printData();
cout << “Y from Second Class\n”;
S.print(M);
return 0;
}
63
Program Example
Example: Friend concept (cont).
64
Friend Method
Friend function are not members of a class but are
associated with the class and are given special privileges.
The function can access the private members of the class as
though they were members. This means that it can refer to the
private data and call any private functions.
When a function is declared to be a friend, it is called as any
other nonmember function.
To declare that a function is a friend of a class, its prototype
declaration within the class is prefixed with the keyword friend.
class FriendClass {
friend void setX (int a);
private:
………
}
65
Program Example
Example: Friend method concept.
private:
int x;
public:
FriendClass ();
void printData ();
};
#endif
66
Program Example
Example: Friend method concept (cont).
//Source files – Filename: FriendClass.cpp
#include “FriendClass.h”
#include <iostream>
using namespace std;
FriendClass :: FriendClass () {
x = 0;
}
int main() {
FriendClass F;
cout << “Friend.x after definition:”;
F.printData();
cout << endl;
cout << “Friend.x after friend method setX is called:”;
setX(F, 8);
F.printData();
return 0;
}
68
Program Example
Example: Friend method concept (cont).
69
The End
Q&A
70