0% found this document useful (0 votes)
83 views43 pages

L5b OO-in-C++

This document provides an overview of object-oriented concepts in C++, including: 1. Classes in C++ define the private and public sections to control access to member variables and functions. Constructors and destructors are special member functions used to initialize and cleanup class objects. 2. Member functions can access private members of the class and be overridden in derived classes. Access control rules govern whether members are public, private, or protected. 3. Friend functions are granted access to private and protected members of a class. Inheritance and polymorphism allow defining relationships between classes and overriding methods.

Uploaded by

Sharifah Amiza
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)
83 views43 pages

L5b OO-in-C++

This document provides an overview of object-oriented concepts in C++, including: 1. Classes in C++ define the private and public sections to control access to member variables and functions. Constructors and destructors are special member functions used to initialize and cleanup class objects. 2. Member functions can access private members of the class and be overridden in derived classes. Access control rules govern whether members are public, private, or protected. 3. Friend functions are granted access to private and protected members of a class. Inheritance and polymorphism allow defining relationships between classes and overriding methods.

Uploaded by

Sharifah Amiza
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/ 43

TME2413/TMI2113/TMN2223/TMS2833/TMT2673

Object Oriented Software Development

Lecture 05b:
Object-Oriented
in C++

Ref: R.S. Pressman, 2001, A. Bahrami, 1999, A. Eliens, 2000, G. Booch,


1994

1
1
Topics
 Analysis of Class Concept
 Class in C++
 Member Functions
 Constructor and Destructors
 Member Function (Methods)
 Access Control Rules
 Friend Function
 Derived Class in C++
 Full Example Program:Constructor & Destructor
 Analysis of Inheritance Concepts
 Inheritance in C++
 Full Example Program: Inheritance
 Full Example Program: Polymorphism 2
Analysis of Class Concept
 Class facilitates the classification of objects with similar
properties, and sub-classing can be employed to specify
specialization of the general properties.

 There are 2 views of class:


1. Its external view (its specification).
- Described by the interface functions which define the
operations that can be performed on instances of the class.
2. Its internal view (its implementation)
- Composed of the details of the data representation and the
implementation of interface functions and other ancillary
operations. 3
Analysis of Class Concept
(cont..)
 In some OO languages (Smalltalk), the interface
function are called ‘methods’ while in C++, they
are referred to as ‘member functions’.
 Abstract classes are defined for the purpose of
deriving other classes (subclasses) from it. It
acts as a template for other classes rather than
as a template for objects.
 The implementations of the abstract function can be dummy implementations.

4
Class in C++
 The syntax for class specification as
follows:

class class_name {
declaration of the ??? members of
the class
public:
declarations of the ??? members of
the class
}
5
Class in C++
 The syntax for class specification as follows:
class class_name {
declaration of the private members of the class
public:
declarations of the public members of the class
}

 The actual body of the class is enclosed within a pair of


braces {}.
 The body of the class is made up of declarations of variables
called instance variables and functions called member
functions (methods)
 The member functions that are declared after the keyword
public in the class definition are the ‘interface function’ or
‘methods’ for the users of the class.
 The declaration occur before keyword public are considered
6

private members of the class by default.


Class in C++ (con’t)
 Consider the following example:
class square {
int side;
int x,y;
public:
void square (int);
void move(int, int);
void display();
}
 The operation which can be performed on instance of the class
square are move and display.
 The private section of the class square contains 3 variables:
 side of the square and the position in term of x and y
coordinates. 7

 Constructor function
Class in C++ (con’t)
 Consider the following example:
class square {
int side;
int x,y;
public:
void square (int);
void move(int, int);
void display();
}
 The operation which can be performed on instance of the class square
are move and display.
 The private section of the class square contains 3 variables:
 side of the square and the position in term of x and y coordinates.
 Constructor function
 First member function defined in the public section.
 Same name as the name of the class. (e.g., void square(int))
8

 Used to initialize the instance variable of a class.


Class in C++ (con’t)
 To declare instances of a class, the syntax is as follows:
class_name an_object; OR
class_name list_of_comma_separated_objects;
 Objects declared can be used as follows:
object_name.instance_variable_name OR
object_name.member_function_name(list_of_comma_separated_argu
ments)
 For example, object of class ‘square’ can be declared as
below:
square squaresize4; OR
square square1, square2;
 The member functions of class ‘square’ can be invoked.
9

Squaresize4.move(10,8);
Class in C++ (con’t)
 A class square, circle, rectangles, and other geometric objects have
different shapes, they can be viewed as belonging to a class of ‘generic
shapes’ or ‘shapes’.
 These shapes (square, circle, etc) are instances of class ‘shapes’.
 All instances of class ‘shapes’ have some common operations that can
be performed on shapes (e.g., move & display)
 Thus, the class shapes can be defined as follows:
class shapes {
int x,y;
public:
void move (int, int);
void display();
}
10
 the specific instances of class shapes (square, circle, rectangles, etc) can
be derived from the generic class of shapes.
Constructor and Destructors
 When object is created, a constructor function for
that object is invoked, if an appropriate
constructor function is declared in the class. It has
the same name as that of the class.
 The constructor for base class and the derived class
can be implemented as shown in the example
below.
employee::employee(String e_name) {
name = e_name;
}

manager::manager(String m_name) :
employee(m_name) {
}
11
Constructor and Destructors (con’t)
 When the instance objects are no longer needed
they can be destroyed to release memory occupied
by using special kind of a member function called
destructors (opposite of constructor function)
 The name of destructors function is the name of
the class preceded by a tilde (~) character.
 Example, the destructors for class ‘manager’ as
follow:
manager::~ manager()

12
Member Functions (Methods)
 Member function for the base class & the derived class can be
implemented as shown in the following examples:
void employee::set_salary(int sal) {
salary = sal;
tax = (18/100) * sal;
}

void manager::set_salary(int sal) {


salary = sal;
tax = (20/100) * sal;
}
 % of tax collected for ‘manager’ is different from an
‘employee’, thus, there is 2 version of set_salary.
 The set_salary member function of the base class is overridden
13

by the one in the derived class (overriding).


Member Functions (methods)
 The term overloading is used to describe the situation
where a name or an operator has different meanings when
used with object of different types. (Example ‘+’ can be
‘plus’ or ‘join’)
 manager::set_salary tries to access the instance variables
‘salary’ and ‘tax’ which is private section member of the
class.
 This will cause error:
‘manager::set_salary() cannot access
employee::set_salary private member’
 To make private attribute (‘salary’ & ‘tax’) accessible from
member function (set_salary) of class ‘ manager’. Define
these attribute in protected section of class ‘employee’
 Member function & instance variable can be specified as
protected 14
Member Function (continue…)

class employee {
String name;
String id;
protected:
int salary;
int tax;
public:
employee(String e_name); /* constructor function */
employee(String m_name, String e_id);
set_emplname(String e_name);
void set_salary(int sal);
void set id(String e_id); 15

}
Access Control Rules

 Public section often no protection to access.


 Private section of a class indicate that the access is
provided to member functions and the ‘friend’
function. Access to members of the protected section
of a class is provided to member functions, friend
functions, and the members of the derived class.
 The public & protected members of the base classes
will be private in the derived class when the base
classes are derived as private.

16
Access Control Rules(cont..)
 Several rules govern the access control mechanism:
1.A protected member of a base class is a
protected member of the derived class if the
derivation is public.
2.A protected member of a base class is a
private member of derived class if the
derivation is private.
3.When the base class is used as a private base
class, all its members are considered to be
private members of the derived class.
4.A member of a derived class or a friend of a
derived class has access only to protected
and public members of the base class.
17
Friend Functions

 In C++, the ‘friend’ function of a class are allowed


access to the encapsulated data. (breach of
encapsulation).
 The syntax for declaring friend functions is shown
below:
friend return-type friend-function-name (argument-
declaration-list)
 This declaration is the way an external function
access to private members of a class

18
Friend Functions (con’t)

 The friend function can be implemented as follow:

#include <String.h>
#include <iostream.h>
class employee {
char name;
char id;
protected:
int salary;
int tax;
public:
employee(string e_name); /* constructor function */
void set_salary(int sal);
friend void display_emp_info(employee &);
};
void display_emp_info(employee & emp) {
cout << " Employee : " << emp.name<< "\n";
cout << " ID : " << emp.id;
}
19
Full Example program: Constructor & Destructor
Let us declare a class Point as: // constructor implementation without
// parameter
//This program declares a class Point Point::Point() {
// for variables x and y // initialize the private data to zero
#include <iostream.h> x = 0; y = 0;
};
class Point{
private: //constructor implementation with
int x, y; // point coordinate // parameters
public: Point::Point(int val1, int val2) {
Point(); // constructor //initialize the private data to user data
// declaration without parameter setX(val1); setY(val2);
Point(int val1, int val2); };
// constructor declaration with
// parameters //destructor implementation
~Point(); // destructor Point::~Point(){
// declaration //print the message to indicate the
void setX(int val); // deletion of an object
void setY(int val); cout << "The object has been
int getX(); deleted.\n";
int getY(); };
}; // class Point

20
void Point::setX(int val){
x = val;
};

void Point::setY(int val){


y = val;
};

int Point::getX() {
return x;
};

int Point::getY() {
return y;
};

21
The driver for the class Point
//This program serves as a driver (main) // create a new instance of a class
for class Point. // Point via a constructor with
//It instantiates the class Point and call // initialization of the user numbers
methods from class Point
Point bpoint(4,5);
#include <iostream.h> cout << "\nThe numbers from the
#include "Ptwc.cpp" Point object are x = " <<
int main() { bpoint.getX();
// create a new instance of a class Point cout << " and y = " <<
bpoint.getY()<< "\n";
// via a constructor with initialization
cout << "\n";
// of the class numbers.
Point apoint;
return 0;
cout << "\nThe numbers from the Point
object are x = " << apoint.getX(); };
cout << " and y = " << apoint.getY()<<
"\n";
cout << "\n"; 22
23
Constructor & Destructor: Few Points to
Note
 Two ways of creating an object via
constructor methods
 The first case, “Point apoint;”, instantiates a
class Point without passing parameters. This
will automatically initialize the data of an
object (variables x and y are assigned to zero).
 The second case, “Point bpoint(4,5);”,
instantiates a class Point with parameters
(values 4 and 5). This will automatically
initialize the data of an object to user’ defined
values (variables x and y are assigned to 4 and
5, respectively). 24
Constructor & Destructor:
Few Points to Note (cont…)
 The destructor method is not called in program. The
C++ compiler will automatically call the destructor
method before the program terminates.
 Since the objects are created twice, the compiler
calls the destructor method two times in order to
delete the two created objects.
 The destructor method is a simple method with a
print statement. For this reason, the destructor is
usually not declared and used in a class. The
destructor is important when dynamic allocation
storage is used (for example, pointers).
25
Analysis of Inheritance
Concept
 Inheritance has been used in OO paradigm
as a mechanism for creating new classes
from existing class. Thus the hierarchy of
classes is created where the subclasses Employee
name : string
are derived from superclasses. salary : integer
IC_No : string

 By identifying the common behaviour & set_salary( )

characteristics between classes, a


hierarchy of classes can be establish. Manager Officer
Dept : String Dept : string

 Inheritance can also be used as a Set_Dept( ) Set_Dept( )

mechanism for sharing and mechanism for


code reusability.
26
Inheritance in C++
 C++ permits new classes to be created from
an existing class by inheritance
 The syntax for deriving a new class, using an
existing class as a a public base class is show
below:
class derived_class_name: public base_class_name {
// private members of the derived class
public:
// public members of the derived class
}
 Type of access control are ‘private’ and
‘public’.
27
Inheritance in C++ (continue…)
 The existing class which serves as a source for inheritance
referred to as ‘base class’ and the new class derived from
base class is referred to as the ‘derived class’.
 Derived class obtain access to the information encapsulated
in the base class.
 One significant advantage of inheritance is that it supports
the creation of a new class of objects by making small
changes to an existing class.
 Other advantages are - code reuse & sharing, all bug (error)
fixes and enhancements made to the base class are
automatically propagated to derived classes.
 Implementation of inheritance is appropriate for situations
where the derived class is either a subset or a specialization
of the base class.
28
Derived Class in C++
 New classes are derived from existing classes using inheritance
mechanism. Example of implementation details of the inheritance as
below:
// the base class
class base_class {
int baseint;
float basefloat;
};
// the derived class
class derived_class: base_class {
int deriveint;
float derivedfloat;
};
// the main function
main() {
base_class B;
derived_class D;
}

 in main(), create a base_class B, and derived_class D. derived_class


D will inherits members function from base_class B. 29
Inheritance in C++ (continue…)
 Example
class employee {
int salary;
int tax;
String name;
String id;
public:
employee(String e_name); //constructor function
employee(String m_name, String e_id);
set_emplname(String e_name);
void set_salary(int sal);
void set id(String e_id);
};

class manager: public employee {


employee(*e_list)[20];
String dept;
public:
manager(String m_name);
void set_dept(String d_name);
void set_salary(int sal);
void add_employee(employee *empl);
}; 30
Inheritance in C++ (continue…)
 Class ‘manager’ is derived from base class ‘employee’. That
is the manager is ‘kind-of’ an employee.
 Notice that ‘manager’ inherits the following instance
variables from the base class ‘employee’
int salary
int tax
String name
String id
 Since employee is inherited as public base class, the private
section members of the employee class are not accessible to
members function (methods) of the derived class manager.
 For example, method set_salary of class manager cannot
access attribute salary of class employee.
 The public section member of base class employee are also
part of the public section of the derived class manager.
31
Another Full Example program: Inheritance
Let us declare a class Circle as:

//This program declares a class Circle based


void Circle::GetPoint(){
// on derived class Point
int x, y;
//It illustrates single inheritance in C++
cout << "Type coordinate x: ";
#include <iostream.h>
cin >> x;
#include "Point.cpp"
cout << "Type coordinate y: ";
cin >> y;
class Circle: public Point
setX(x); setY(y);
{ private :
};
float Result;
public:
void Circle::GetResult() {
Circle(); //constructor declaration
const float Pi = 3.14151296;
void GetPoint();
Result = 2 * Pi * getX();
void GetResult();
cout << "\nThe circumference of a circle from
}; center point 0 to ";
cout << getX() << " is "<< Result << "\n";;
//constructor implementation };
Circle::Circle() {
Result = 0;
};

32
The driver of the class Circle
//This program serves as a driver (main)
// for class Circle.
//It instantiates the class Circle and call
// method from class Circle
//which will indirectly call methods from
// class Point
#include "Circle.cpp"
int main()
{
Circle circle;
circle.GetPoint();
circle.GetResult();
return 0;
};
33
34
Inheritance: Few Points to
Note
 Since inheritance means the subclass will inherit all the
data and methods from the superclass, the declaration of
class Circle above will automatically make the methods
from class Point available in Class Circle.
 Since the data from class Point is declared private, it is not
accessible in class Circle. The data can only be accessed
through methods getX() and getY(). If class Circle wants to
access directly the data, the type in class Point needs to
be changed to protected. This will allow the subclass to
access the data from the superclass.
 Class Circle inherits all the methods from class Point and at
the same time introduces one data (Result of type float)
and two new methods: GetPoint() and GetResult().
35
Polymorphism

36
Polymorphism: Few Points to Note

 Polymorphism is a term used to refer to more


than one method that has the same name. The
methods must belong to different kinds of
objects.
 Example program shows a class Point with 2
different classes, Circle and Rectangle that
inherit from class Point.
 Class Point declares a method DisplayDetails and
class Circle redefines the same method
DisplayDetails.
 The method DisplayDetails behaves differently in
the different classes.
37
Another Full Example program: Polymorphism
Let us declare a class Point as:
void Point::setX(int val){ x = val; };
//Filename: PtPoly.cpp
//This program declares a class
//Point for variables x and y void Point::setY(int val){ y = val; };
//It illustrates Polymorphsim in
//C++ int Point::getX() { return x; };
#include <iostream.h>
int Point::getY() { return y; };
class Point{
void Point::DisplayDetails() {
private: // display output via methods getX and
int x, y; // point coordinate //getY
public: cout << "\nThe coordinates from the
void setX(int val); Point object are x = " << getX();
void setY(int val); cout << " and y = " << getY()<<
"\n";
int getX(); cout << '\n';
int getY(); };
void DisplayDetails();
}; // class Point

38
Another Full Example program: Polymorphism
Let us declare a class Circle as:

//Filename: CirPoly.cpp
//This program declares a class Circle based on
void Circle::GetResult() {
//derived class Point
//It illustrates Polymorphism in C++ const float Pi = 3.14151296;
#include <iostream.h> Result = 2 * Pi * getX();
#include "PtPoly.cpp" cout << "\nThe circumference of a
circle from center point 0 to ";
class Circle: public Point cout << getX() << " is "<< Result
{ private : << "\n";;
float Result; };
public:
void SetPoint(); void Circle::DisplayDetails() {
void GetResult(); // display output via methods getX and //getY
void DisplayDetails(); cout << "\nThe coordinates from the
}; Circle object are x = " << getX();
cout << " and y = " << getY()<< "\n";
void Circle::SetPoint(){
int x, y;
cout << '\n';
cout << "Type coordinate x: "; };
cin >> x;
cout << "Type coordinate y: ";
cin >> y;
setX(x); setY(y);
}; 39
The driver of the class Circle
//Filename: PolyDr.cpp
//This program serves as a driver (main) for
// class Point and Circle.
// It illustrates Polymorphism in C++
#include "CirPoly.cpp"

int main() {
Point apoint;
apoint.setX(4); apoint.setY(5);

Circle circle;
circle.SetPoint();
circle.GetResult();
apoint.DisplayDetails();
circle.DisplayDetails();

return 0;
};
40
41
Summary

 OO in C++
 Constructors and Destructors
 Member functions
 Friend functions
 Inheritance
 Polymorphism

42
Questions???

?
43

You might also like