0% found this document useful (0 votes)
9 views112 pages

C++ Object-Oriented Programming Guide

The document provides an overview of Object-Oriented Programming (OOP) using C++, detailing its principles, benefits, and common traits such as encapsulation, polymorphism, and inheritance. It includes programming concepts like variable declaration, input/output statements, control structures, functions, and arrays, along with examples of syntax and code snippets. The document serves as a guide for understanding and implementing OOP in C++.

Uploaded by

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

C++ Object-Oriented Programming Guide

The document provides an overview of Object-Oriented Programming (OOP) using C++, detailing its principles, benefits, and common traits such as encapsulation, polymorphism, and inheritance. It includes programming concepts like variable declaration, input/output statements, control structures, functions, and arrays, along with examples of syntax and code snippets. The document serves as a guide for understanding and implementing OOP in C++.

Uploaded by

o.bamibanks
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Object-Oriented Programming

with C++
CSC 204
By
DR. O. R. VINCENT

Textbooks: (i) Teach Yourself C++ (Second


Edition) by Herbert Schildt
(ii) Computer Programming with C++ by Kunal
Pimparkhede 1
Programming Style
• Input Phase
– Variable Declaration of input(s)
– Read in input
– Initialisation
• Process Phase
– Compute the method

• Output Phase
– Output result
2
• Object-oriented programming (OOP) is a
programming language organized around objects
rather than "actions" and data rather than logic.
Historically, a program has been viewed as a logical
procedure that takes input data, processes it, and
produces output data.
• Object-oriented programming takes the view that
what we really care about are the objects we want to
manipulate rather than the logic required to
manipulate them. Examples of objects range from
human beings (described by name, address, and so
forth) to buildings and floors (whose properties can
be described and managed) down to the little 3
The concepts and rules used in object-oriented
programming provide these important benefits:
i)The concept of a data class makes it possible to define
subclasses of data objects that share some or all of the main
class characteristics, called inheritance. This property of OOP
forces a more thorough data analysis, reduces development
time, and ensures more accurate coding.
ii) Since a class defines only the data it needs to be concerned
with, when an instance of that class (an object) is run, the
code will not be able to accidentally access other program
data. This characteristic of data hiding provides greater
system security and avoids unintended data corruption.

4
iii) The definition of a class is reuseable not only by
the program for which it is initially created but also
by other object-oriented programs (and, for this
reason, can be more easily distributed for use in
networks).
iv) The concept of data classes allows a programmer
to create any new data type that is not already defined
in the language itself.

Java, Python, C++, Visual Basic .NET and Ruby are


the most popular OOP languages today.
5
OOP languages, like C++,
share three common defining
traits:
• Encapsulation
– Binding code and data
• Polymorphism- A quality that allows one
name to be used for two or more related but
technically different purposes
• Inheritance
– Process by which one object can acquire the
properties of another
6
• In OOP,
• Header e.g #include <iostream.h>
• Main()
• Input Stage
– Declaration of input(s) e.g int j
– Read in input cin >>
– Initialisation e.g sum = 0
• Process Stage
• Output stage
– Output result e.g cout <<

7
Declaration of inputs
• Variables
– Location in memory where value can be
stored
– Common data types
•int - integer numbers
•char - characters
•double - floating point numbers

8
• main() function is the entry point of any C+
+ program. It is the point at which
execution of program is started.
• When a C++ program is executed, the
execution control goes directly to the
main() function. Every C++ program have a
main() function.
• It appears once in every C++ program

9
Syntax
void main()
{
............
............
}
In above syntax;
•void: is a keyword in C++ language, void means
nothing, whenever we use void as a function return
type, then that function returns no value.
•In place of void we can also use int return type of
main() function, at that time main() return integer
type value.
•main: is a name of function which is a predefined
function in C++ library. 10
Example
#include<iostream>
void main()
{
cout<<"This is main
function";
}

Output
This is main function 11
A C++ program
//include headers; these are modules that include functions that you may use in
your
//program; we will almost always need to include the header that
// defines cin and cout; the header is called iostream

#include <iostream>

int main() {

//variable declaration
//read values input from user
//computation and print output to user
return 0;
}
12
Hello world program
When learning a new language, the first program people
usually write is one that salutes the world :)

Here is the Hello world program in C++.

#include <iostream>
int main() {
cout << “Hello world! ”;

return 0;
}
13
return
• Keyword return is one of several means
to exit function; value 0 indicates program
terminated successfully.

14
Variable Declaration: Data Type in C++
type variable-name;
Meaning: variable <variable-name> will be a variable of type
<type>

Where type can be:


– int //integer
– double //real number
– char //character

Example:
int a, b, c;
double x;
int sum;
char my-character;
15
Input statements
cin >> variable-name;
Meaning: read the value of the variable called
<variable-name> from the user

Example:
cin >> a;
cin >> b >> c;
cin >> x;
cin >> my-character;

16
Output statements
cout << variable-name;
Meaning: print the value of variable <variable-name> to
the user
cout << “any message “;
Meaning: print the message within quotes to the user
cout << endl;
Meaning: print a new line
Example:
cout << a;
cout << b << c;
cout << “This is my character: “ << my-
character << “ he he he” << endl;
17
• #include <iostream>
using namespace std;
main()
{
int i, j;
double d;
i = 10;
j = 20;
d = 99.101;
cout << “Here are some values: “;
cout << i << ‘ ’ << j << ‘ ’ << d;
return 0;
}
18
Repetitive Loop, Functions and
Prototyping Functions

Repetition structures, or loops, are used when a


program needs to repeatedly process one or
more instructions until some condition is met,
at which time the loop ends.
Many programming tasks are repetitive,
having little variation from one item to the
next.
19
C++ FUNCTIONS
A function is a block of code which only runs
when it is called.

One can pass data, known as parameters, into a


function.

Functions are used to perform certain actions,


and they are important for reusing code: Define
the code once, and use it many times.
20
A function prototype is a definition
that is used to perform type checking
on function calls when the system
code does not have access to the
function itself.

A function prototype begins with the


keyword function, then lists the
function name, its parameters (if any),
and return value (if any). 21
Creating a Function

C++ provides some pre-defined functions, such as


main(), which is used to execute code. But one can
also create his own functions to perform certain
actions.

To create (often referred to as declare) a function,


specify the name of the function, followed by
parentheses ():
22
Syntax

void myFunction() {
// code to be executed
}
*myFunction() is the name of the function
*void means that the function does not have a
return value.
*inside the function (the body), add code that
defines what the function should do 23
Call a Function

Declared functions are not executed immediately. They


are "saved for later use", and will be executed later,
when they are called.

To call a function, write the function's name followed


by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print


a text (the action), when it is called:
24
// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!“

NB: A function can be called multiple times: 25


Function Declaration and Definition

A C++ function consist of two parts:

*Declaration: the function's name, return type, and


parameters (if any)
*Definition: the body of the function (code to be
executed)
void myFunction() { // declaration
// the body of the function (definition)
}
26
NB: If a user-defined function, such as
myFunction() is declared after the main()
function, an error will occur.

It is because C++ works from top to bottom;


which means that if the function is not
declared above main(), the program is
unaware of it:

27
FUNCTIONS cont.
Some Process Statements
Control statement
control flow statement
•If statement
•If … else statement
•Switch statement
Control Flow statement
– While statement
– For statement
– Do .. While statement
28
If statements
True False
condition
if (condition) {
S1;
}
S1 S2
else {
S2;
}
S3;
S3

29
Boolean conditions
- Relational Operator
• Comparison operators
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal
• Boolean operators
&& and
|| or
! Not 30
Examples
Assume we declared the following variables:
int a = 2, b=5, c=10;

Here are some examples of boolean conditions we can


use:
• if (a == b) …
• if (a != b) …
• if (a <= b+c) …
• if(a <= b) && (b <= c) …
• if !((a < b) && (b<c)) …
31
Loop in C++
To form loop in C++. the following statements can
be used:
•The IF statement
•For statement
•While statement
•Switch statement

32
• #include <iostream>
• using namespace std;
• int main() {
• int a,b,c;
• cin >> a >> b >> c;
• if ((a <= b) && (b <= c)) {
• cout << "min is" << ' ' << a << endl;
• }
• if ((b <= a) && (a <= c)) {
• cout << "min is" << ' ' << b << endl;
• }
• if ((c <= a) && (a <= b)){
• cout << "min is" << ' ' << b << endl;
• }
• return 0; 33


While statements

while (condition) { True False


condition
S1;
}
S1
S2;

S2

34
While example
//read 100 numbers from the user and output their
sum
#include <iostream>

void main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
}
cout << “sum is “ << sum << endl;
35
}
Switch Statement

• A switch statement allows a variable to be


tested for equality against a list of values.
Each value is called a case, and the variable
being switched on is checked for each case.

36
37
The syntax for a switch statement
• The syntax for a switch statement in C++ is as follows −
• switch(expression) {
• case constant-expression :
• statement(s);
• break; //optional
• case constant-expression :
• statement(s);
• break; //optional
• // you can have any number of case statements.
• default : //Optional
• statement(s);
• } 38
Example of Switch Statement
• #include <iostream>
• using namespace std;
• int main(){
• int num=5;
• switch(num+2) {
• case 1:
• cout<<"Case1: Value is: "<<num<<endl;
• case 2:
• cout<<"Case2: Value is: "<<num<<endl;
• case 3:
• cout<<"Case3: Value is: "<<num<<endl;
• default:
• cout<<"Default: Value is: "<<num<<endl;
• }
• return 0; 39
For Statement
• #include <iostream>
• using namespace std;
• int main() { // The counter variable can be declared in the init-
expression.
• for (int i = 0; i < 2; i++ ){
• cout << i; } // The counter variable can be declared outside the for
loop.
• int i;
• for (i = 0; i < 2; i++){
• cout << i; } // These for loops are the equivalent of a while loop.
• i = 0;
• while (i < 2){
• cout << i++; }
• }
40
#include <iostream>
using namespace std;
int main(){
int sum = 0;
int n;
cout << "Enter a positive integer: ";
cin >> n;
for (int i= 0; i<=n; i++){

sum +=i;
}
cout<< "sum=" << sum;
return 0;
} 41
#include <iostream>
using namespace std;
int main(){
int sum = 0;

for (int i= 0; i<=100; i++){

sum +=i;
}
cout<< "sum=" << sum;
return 0;
}
42
Exercise
• Write a program that asks the user
– Do you want to use this program? (y/n)
• If the user says ‘y’ then the program terminates
• If the user says ‘n’ then the program asks
– Are you really sure you do not want to use
this program? (y/n)
– If the user says ‘n’ it terminates, otherwise it prints
again the message
– Are you really really sure you do not want to
use this program? (y/n)
– And so on, every time adding one more “really”.

43
Arrays in C++
• The syntax is
type arrayName [ arraySize ];

• For example
double balance[10];

44
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0;
} 45
• #include <iostream>
• using namespace std;
• int main()
• {
• int n, i;
• float num[100], sum=0.0, average;
• cout << "Enter the numbers of data: ";
• cin >> n;
• while (n > 100 || n <= 0)
• {
• cout << "Error! number should in range of (1 to 100)." << endl;
• cout << "Enter the number again: ";
• cin >> n;
• }
• for(i = 0; i < n; ++i)
• {
• cout << i + 1 << ". Enter number: ";
• cin >> num[i];
• sum += num[i];
• }
• average = sum / n;
• cout << "Average = " << average;
46
• return 0;
Classes and Objects

• The class is the mechanism that is used to


create objects.
• The syntax of a class declaration is similar to
47
that of a structure. Its general form is
48
• Class class-name{
private function and variables of the class
Public:
public functions and variables of the class
}
Objects-list

• Class myclass {
\\ private to myclass
int a;
public:
void set_a(int num);
int get_a();
}; 49
50
51
52
53
54
55
#include <iostream>
using namespace std;
class test
{
private:
int a;
int b;
public:
void set_data(int x,int y) {
a=x;
b=y;
• }
int big()
{
• if (a>b)
return a;
else
return b;
}
};
int main()
{
test t;
int a,b;
cout<< "enter two number"<<endl;
cin>> a>>b;
t.set_data(a,b);
cout<< "the biggest number is"<<' '<<[Link]()<<endl;
return 0;
} 56
#include <iostream>
using namespace std;
class test
{
private:
int a;
int b;
int c;
public:
void set_data(int x,int y,int z) {
a=x;
b=y;
c=z;
}
int big(){
if ((a>b) && (b>c))
return a;
else if ((b>a) && (a>c))
return b;
else
return c;
}
};
int main()
{
test t;
int a,b,c;
cout<< "enter three number"<<endl;
cin>> a>>b>>c;
t.set_data(a,b,c); 57
cout<< "the biggest number is"<<' '<<[Link]()<<endl;
return 0;
// classes example
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int x, int y);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main ()
{
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << [Link]();
58
return 0;
59
60
Pointer in C++
• A pointer is a variable whose value is the
address of another variable.
• It must be declared before you can work with it.
• Format is
– Type *var-name;
The asterisk is being used to designate a variable as a
pointer

61
• Int *ip // pointer to an integer
• Double *dp // pointer to a double
• Float *fp // pointer to a float
• Char *ch // pointer to a character

62
• int main ( ) {
• int var = 20; // actual variable declaration
• int *ip; // pointer variable
• ip = &var // store address of var in pointer variable
• cout << “Value of var variable: ”;
• cout << var << endl;
• cout << “Address stored in ip variable: ”;
• cout << ip <<endl;
• cout << “Value of *ip variable: ”; // access the value
at the address available in pointer
• cout << *ip << endl;

• return 0;
• } 63
64
65
66
67
Class Constructor

What would happen in the previous example if we called


the member function area before having
called set_values? An undetermined result, since the
members width and eight had never been assigned a
value.

In order to avoid that, a class can include a special


function called its constructor, which is automatically
called whenever a new object of this class is created,
allowing the class to initialize member variables or
allocate storage.

This constructor function is declared just like a regular


member function, but with a name that matches the
class name and without any return type; not even void. 68
• // example: class constructor
• #include <iostream>
• using namespace std;
• class Rectangle {
• int width, height;
• public:
• Rectangle (int,int);
• int area () {return (width*height);}
• };
• Rectangle::Rectangle (int a, int b) {
• width = a;
• height = b;
• }
• int main () {
• Rectangle rect (3,4);
• Rectangle rectb (5,6);
• cout << "rect area: " << [Link]() << endl;
• cout << "rectb area: " << [Link]() << endl;
• return 0; 69
• return a;
• }
• main ()
• {
• myclass ob1, ob2;
• ob1.set_a(10);
• ob2.set_a(99);
• cout << ob1.get_a() << “\n”;
• cout << ob2.get_a() << “\n”;
• return 0;
• } 70
Inheritance and Polymorphism
Polymorphism means having many forms. It
occurs when there is a hierarchy of classes
and they are related by inheritance.

A call to a member function will cause a


different function to be executed depending
on the type of object that involves the
function.
71
Base classes and derived classes
• Inheritance is a fundamental requirement of oriented
programming
• It allows us to create new classes by refining existing
classes
• Essentially a derived class can inherit data members
of a base class
– The behaviour of the derived class can be refined
by redefining base class member functions or
adding new member function
– A key aspect of this is polymorphism where a class
behaviour can be adapted at run-time 72
Base and Derived classes
• We can think of many examples in real life of
how a (base) class can be refined to a set of
(derived) classes

• For example a Polygon class can be refined to


be a Quadrilateral which can be further
refined to be a Rectangle

73
Base classes and derived classes
Base class Derived class
Shape Triangle, Circle,
Rectangle
Bank Account Current, Savings
Student Undergraduate,
Postgaduate
Vehicle Car, Truck, Bus
Filter Low-pass, Band-pass,
High-pass
74
Example – a BankAccount class
• A BankAccount base class models basic
information about a bank account
– Account holder
– Account number
– Current balance
• Basic functionalities
– Withdraw money
– Deposit money
75
public class BankAccount
{
private int accountNumber;
private string accountHolder;
private int balance;

public BankAccount(int n,string name ,int b)


{
accountNumber = n;
accountHolder = name;
balance = b;
}
public int AccountNumber { // accountNumber property}
public string AccountHolder { // accounHolder property}
public int Balance { // balance property}
public void withdraw(int amount)
{
if (balance>amount)
balance-=amount;
}
public void Savings(int amount) { balance+=amount;}
} 76
Example – a BankAccount class
• We can consider refinements to our Account class
– CurrentAccount
• Can have an overdraft facility
• No interest paid
– SavingsAccount
• Pays interest on any balance
• No overdraft facility
77
Example – a BankAccount class
• We will create our refined classes using inheritance
from the BankAccount base class
• Classes CurrentAccount and SavingsAccount inherit the
basic attributes (private members) of account
– accountNumber
– accountHolder
– balance
• Also, new attributes are added
– overdraftFacility
– interestRate 78
Example – a BankAccount class
• In order to implement the derived classes, we need to
consider private/public access between base and derived
classes
– public member functions of the base class become
public member functions of the derived class
– private members of the base class cannot be accessed
from the derived class
• Obvious otherwise encapsulation could be easily
broken by inheriting from the base class
• The question is, how do we initialise derived class
objects?
79
Example – a BankAccount class
• Base class methods and properties are accessed
through the base keyword
– base(.....) refers to the base class constructor
– [Link](.....) refers to a method of the
base class
– [Link] refers to a property of the base
class

80
class CurrentAccount : BankAccount
{
private int overdraftFacility;
public CurrentAccount(int n, string name, int b, int ov) :
base(n, name, b)
{
overdraftFacility = ov;
}
public override void withdraw(int amount)
{
if ([Link] - amount > -overdraftFacility)
[Link] -= amount;
}
}
class SavingsAccount : BankAccount
{
private float interestRate;
public SavingsAccount(int n, string name, int b, float rate) :
base( n, name,b)
{ interestRate = rate; }
float calcInterest()
{
float interest = [Link] * interestRate;
[Link] += (int)(interest);
81
return interest;
}
Two Derived classes
CurrentAccount SavingsAccount

accountNumber accountNumber
accountHolder accountHolder
balance balance
Savings() Savings()
withdraw() withdraw()

overdraftFacility interestRate

withdraw() calcInterest()
82
• We can see that in both derived classes we need to access the
balance instance field
• We can do this directly (without using a public method or
property) by making balance a protected member of the
base class
• A protected class member is one that can be accessed by
public member functions of the class as well as public
member functions of any derived class
– Its half way between private and public
– Encapsulation is then broken for classes in the inheritance
hierarchy and thus must be used where performance
issues are critical
83
Class member Can be accessed from

private public member


functions of same class

protected public member


functions of same class
and derived classes

public Anywhere
84
public class BankAccount
{
private int accountNumber;
private string accountHolder;

protected int balance;

public BankAccount(int n,string name ,int b)


{
accountNumber = n;
accountHolder = name;
balance = b;
}
public int AccountNumber { // accountNumber property}
public string AccountHolder { // accounHolder
property}
public int Balance { // balance property}
public void withdraw(int amount)
{
if (balance>amount)
balance-=amount;
}
public void Savings(int amount) { balance+=amount;} 85
}
class CurrentAccount : BankAccount
{
private int overdraftFacility;
public CurrentAccount(int n, string name, int b, int ov) :
base(n, name, b)
{
overdraftFacility = ov;
}
public override void withdraw(int amount)
{
if (balance - amount > -overdraftFacility) // balance is
protected
balance -= amount;
}
}
class SavingAccount : BankAccount
{
private float interestRate;
public SavingsAccount(int n, string name, int b, float rate) :
base( n, name,b)
{ interestRate = rate; }
float calcInterest() {
float interest = balance * interestRate;
balance += (int)(interest);
return interest;
} 86
}
Polymorphism

Application

animal Move

87
Polymorphism

• Polymorphism is implemented through


references to objects
• We can assign base class object references to
any derived class object

BankAccount acc1 = new CurrentAccount(12345,


"John Smith", 1000, 500);

BankAccount acc2 = new SavingsAccount(54321,


"Bill Jones", 2000, 5.0);
88
Polymorphism
• We can see that in the case of the reference to a
CurrentAccountObject object, method
withdraw() is overidden in the derived class
• The question is, which one is called at
runtime?
public class BankAccountTest
{
static void Main(string[] args)
{
BankAccount acc1 = new CurrentAccount(12345,
"John Smith“,1000, 500);

[Link](250); // Which withdraw()?


}
89
}
CurrentAccount

acc1 accountNumber
accountHolder
balance
Savings()
withdraw()
Which one is
called?
overdraftFacility
withdraw() 90
• Clearly the behaviour of the object to the
‘withdraw’ message is important
– The derived class behaviour takes into account
the overdraft facility
• We must look at the definitions of the withdraw()
method in the base and derived classes
– The base class withdraw() method is overridden
by the derived class method if the base class
method is declared as virtual and the derived
class method is declared as override
91
Polymorphism
public class BankAccount
{
//……

public virtual void withdraw(int amount)


{
if (balance - amount > -overdraftFacility)
balance -= amount;
}
}

public class CurrentAccount : BankAccount


{
private int overdraftFacility;
public CurrentAccount(n, name, b) {…}
public override void withdraw(int amount)
{
if (balance - amount > -overdraftFacility)
balance -= amount;

} 92
}
Polymorphism Conts.
• Because withdraw() in the derived class is declared
as an override function of the virtual function in the
base class, the correct behaviour is obtained

public class BankAccountTest


{
static void Main(string[] args)
{
BankAccount acc1 = new
CurrentAccount(12345, "John Smith“,1000, 500);
[Link](250); // Calls the
CurrentAccount withdraw() method
} 93
}
Polymorphism Conts.
• In Java, polymorphism (overriding the base
class implementation) is the default behaviour
• In C++, the virtual keyword is used but no
override keyword
• C# also has a keyword sealed for a base class
method which can’t be overriden
– Methods can also be declared override and
sealed indicating that they override a base
class method but can’t themselves be
overriden
94
ABSTRACTION
• Data abstraction refers to providing
only essential information to the outside
world and hiding their background
details.
• It relies on the separation of interface
and implementation.

95
ABSTRACTION (Abstract classes)
• In our example classes, the withdraw()
method of our BankAccount was declared
as a virtual function
– We were able to provide a sensible
implementation of this function
– This implementation could be regarded
as default behaviour if the function was
not overridden in derived classes

96
Abstract classes
 If the method called can’t be resolved
in the derived class, it is delegated back
to the default base class method
public class BankAccountTest
{
static void Main(string[] args)
{
BankAccount acc1 = new CurrentAccount(12345,
"John Smith“,1000, 500);
[Link](250); // Calls the
CurrentAccount withdraw() method
BankAccount acc2 = new SavingsAccount(54321,
“Bill Jones“,2000, 5.0);
[Link](100); // Calls the BankAccount
withdraw() method
}
97
}
Abstract classes
• Abstract classes arise when there is no sensible
implementation of the virtual functions in the base
class
– Base class virtual functions are always overridden
by derived class implementations
• In this case, we simply declare the virtual function as
abstract but provide no implementation
– A class containing at least one abstract function
must be declared an abstract class

98
Abstract classes
• As an example, suppose we wanted to design a
hierarchy of shape classes for a computer graphics
application
• Shape is an abstract concept
– There is no sensible way we can implement functions
to draw a shape or compute the area of a shape
– It is natural to make such functions abstract
– We can derive concrete classes from shape and
provide implementations in the override functions

99
Abstract classes
public abstract class Shape
{
private int xpos;
private int ypos;

public abstract void draw();


public abstract double area();

public virtual void move(int x, int y)


{
xpos+=x;
ypos+=y;
}
}
100
Abstract classes
public class Square : Shape
{
private int side;

public Square(int s) {side=s;}

public override void draw() { }

public override double area() { return side*side; }


}

public class Circle : Shape


{
private int radius;

public Circle(int r) { radius = r; }

public override void draw() { }

public override double area() { return


[Link]*radius*radius;} 101
}
Abstract classes
• We can’t create Shape objects but we can
declare Shape references and assign them to
derived class objects
using System;

class ShapeTest
{
static void Main(string[] args)
{
Shape sq = new Square(10);
Shape c = new Circle(5);
[Link]("Area of square= " +
[Link]());
[Link]("Area of circle= " +
[Link]());
} 102
}
Generic programming
• Generic programming refers to performing
operations on different types using a single piece of
code
– Examples include the application of searching and
sorting algorithms to different data types
• In Java, this is done using polymorphism and the fact
that all types are ultimately derived from a
superclass object
• In C++ it is normally done using templates
• C# provides both mechanisms for generic
programming
– We will look at an example of generic searching
using polymorphism
103
Generic programming
• Suppose we want a generic search algorithm to
search for any kind of object in an array
• Class object provides an Equals() method to test
whether one object is equal to another
– Simply checks if the 2 object references point
to the same area of memory
– Not very useful in practice
• We need to provide an Equals() method in the
class of the object we are searching for
– Polymorphism does the rest! 104
Generic Programming
• In the following example we are searching
for a BankAccount object in an array
– The search is based on the account
number
• Class SearchAlg provides a linearSearch
method which carries out the search
• We have provided an implementation of
Equals() in class BankAccount which
overrides the Equals() method in object
105
public class BankAccount
{
private int accountNumber;
private string accountHolder;
private int balance;
public BankAccount(int n,string name ,int b)
{
accountNumber = n;
accountHolder = name;
balance = b;
}
public int AccountNumber { // accountNumber property}
public string AccountHolder { // accounHolder property}
public int Balance { // balance property}
public void withdraw(int amount)
{
if (balance>amount)
balance-=amount;
}
public void Savings(int amount) { balance+=amount;}
public override bool Equals(object obj)
{
BankAccount b = (BankAccount) obj;
return (accountNumber==[Link]);
}
} 106
Generic Programming
using System;

public class SearchAlg


{
public static int linearSearch(object[]
a, object b)
{
int n=[Link];
for (int i=0; i<n; i++)
{
if (a[i].Equals(b))
return i;
}
return -1;
} 107
}
Generic Programming
using System;

public class BankAccountTest


{
static void Main(string[] args)
{
BankAccount[] b = new BankAccount[3];

b[0]=new BankAccount(12345, "John Smith",100);


b[1]=new BankAccount(13579, "Bill Jones",200);
b[2]=new BankAccount(87654, "Paul Brown",300);

BankAccount bt=new BankAccount(13579, "JonesB",


700);
int index=[Link](b,bt);
[Link]("Account found at index " +
index);
}
} 108
Polymorphism
• Polymorphism is a key feature of object oriented
programming
• Complex systems are able to be easily extended
– The extendibility is provided by defining new
classes within an inheritance hierarchy
– Objects of these new classes are accessed through
a base class reference
– These objects add new behaviours to the system
through a common interface to the application
(the base class virtual functions)

109
Polymorphism
• For example we could extend the list of
animals to which we can send ‘move’
messages in our video game application
– Each animal is responsible for its own
movement code which can easily ‘plug-in’
to the main application
– Thus the application is easily extended
with minimal changes to the main
application code
110
Polymorphism and OOP

animal Move

. 111
Summary
• We have looked at how we can extend existing classes
through the idea of inheritance
• We have seen how, by accessing derived classes
through a base class pointer, object behaviour is
determined at run time through polymorphism
• We have looked at abstract classes where there is no
obvious implementation of base class virtual methods
– These methods are always overriden by derived
class methods
• We have looked at the significance of polymorphism
in object orientation
– Object oriented applications are easily extended
with additional code mainly confined to new
112
derived classes

You might also like