C++ Object-Oriented Programming Guide
C++ Object-Oriented Programming Guide
with C++
CSC 204
By
DR. O. R. VINCENT
• 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.
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 :)
#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>
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
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
int main() {
myFunction(); // call the function
return 0;
}
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;
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
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
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;
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
• 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
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;
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
public Anywhere
84
public class BankAccount
{
private int accountNumber;
private string accountHolder;
Application
animal Move
87
Polymorphism
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
{
//……
} 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
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;
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;
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