Computer Programming II

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 128

Computer

Programming II

M. A. Heman
Stages of Compilation
• Preprocessor copies content of the included header files, generate macrocode, and
replaces symbolic constants with their values
• The expanded source code file (macrocode) is converted into assembly language
for the platform
• The assembler code generated is assembled into object code for the platform
• The object codes are linked together using linker to link to any library used in
generating object to generate the executable file
Compilation In C++
• You could us CodeBlocks or
• NetBeans IDE
Variable
• Variable: a storage location on the RAM
• Types of variables:
 Local variables: a variable declared within a function
 Global variables: variable declared to be used in more than one function in a
program
Arithmetic Operations
• To make addition before multiplication:
dToBePaid = dTotal * (1 + dTaxpacentage)
• Priority rule:
Other Mathematical Functions
Arithmetic Operations Conn’d
Constant
• Is a variable whose value never change throughout a program
• Its cleared in c++ as const. e.g.
const double pi = 3.14;
const double radius = 4.6;
Statement
• Each individual instruction in a program that are executed in the order they appear
or as they are controlled and end with semicolon, “;”.
• Statements include:
 Declarative
 Assignments
 Procedures/methods
 Controls statements
 Select statement
 Loop/iteration
Declarative Statement
• The are used for initializing of declaring variables
E.g. int iNo;
float price;
string whatisYourName;
char yourCGPA;
Assignment Statement
• int grossPrice = 4.15
• Int price = grossPrice * tax * discount
• num = num + 1
• sum -= 1
Control Statement
• If
• If /else
• Nested if
• If/else if
• Flags
• Logical operator
• Conditional
• Switch
IF Statement
Yes
If int A, B;
Print A
A>B cin >> A;
No cin >> B;
if (A > B)
cout << A;

Stop
IF/Else
int A, B;
cin >> A;
If A > B Print A cin >> B;
if (A > B)
{
cout << A;
} else
{
Print B cout << B;
}

Stop
Nested If Statement
• Testing more than one condition

cout << “Are you employed”;


if (employed == y)
{
if ( recentGrad == Y) // nested if
{
cout << “you qualifiy for the ”;
cout << “interest rate\n”;
}
}
Nested If Statement cout << “Are you employed”;
• Testing more than one condition if (employed == y)
{
if ( recentGrad == Y) // nested if
{
cout << “you qualifiy for the ”;
cout << “interest rate\n”;
}
else
{
cout << “You must have ”;
cout << “graduated from college”;
cout << “in the past tow years to”;
cout << “qualify. \n”;
}
else
{
cout <<“You must be employed to”;
cout <<“to qualify\n”;
}
If/else if statement

• The if/else if statement tests a series of conditions. It is often simpler


to test a series of conditions with the if/else if statement than with a
set of nested if/else statements.
Flags
• A flag is a Boolean or integer variable that signals when a condition exists.
bool salesQuotaMet = false;
if (sales >= QUOTA_AMOUNT)
salesQuotaMet = true;
else
salesQuotaMet = false;
Integer Flag
• Because c++ also take the value 0 as false none-zero numbers are taken as true
int salesQuotaMet = 0; // 0 means false.
if (sales >= QUOTA_AMOUNT)
salesQuotaMet = 1;
else
salesQuotaMet = 0;
Example of Flag
// This program demonstrates the && logical operator.
#include <iostream>
using namespace std;
int main()
{
char employed, // Currently employed, Y or N
recentGrad; // Recent graduate, Y or N
// Is the user employed and a recent graduate?
cout << "Answer the following questions\n";
cout << "with either Y for Yes or N for No.\n";
cout << "Are you employed? ";
cin >> employed;
cout << "Have you graduated from college "
<< "in the past two years? ";
cin >> recentGrad;
// Determine the user's loan qualifications.
int imployedStaff = false
if (employed == 'Y' && recentGrad == 'Y')
{
employedStaff = true
cout << "You qualify for the special "
<< "interest rate.\n";
}
else
{
employedStaff = false
cout << "You must be employed and have\n"
<< "graduated from college in the\n"
<< "past two years to qualify.\n";
}
return 0;
}
Logic Operators
• && : AND
• || : OR
• ! : NOT
if (employed == 'Y' && recentGrad == 'Y')
{
cout << "You qualify for the special "
<< "interest rate.\n";
}
else
{
cout << "You must be employed and have\n"
<< "graduated from college in the\n"
<< "past two years to qualify.\n";
}
Numerical range with
logical Operator
If (x >= 20 && x <= 40) if x false between 20 – 40
Switch Statement

The switch statement lets the value of a variable or expression determine where the
program will branch
Switch Statement
Conn’d
NB:
• The expression of each case statement in the block must be unique.
• The expression following the word case must be an integer literal or constant. It
cannot be a variable, and it cannot be an expression such as x < 22 or n == 50
Example: Menu
Program
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int choice; // To hold a menu choice
int months; // To hold the number of months
double charges; // To hold the monthly charges

// Constants for membership rates


const double ADULT = 40.0,
CHILD = 20.0,
SENIOR = 30.0;
// Constants for menu choices
const int ADULT_CHOICE = 1,
CHILD_CHOICE = 2,
SENIOR_CHOICE = 3,
QUIT_CHOICE = 4;
// Display the menu and get a choice.
cout << "\t\tHealth Club Membership Menu\n\n"
<< "1. Standard Adult Membership\n"
<< "2. Child Membership\n"
<< "3. Senior Citizen Membership\n"
<< "4. Quit the Program\n\n"
<< "Enter your choice: ";
cin >> choice;
// Set the numeric output formatting.
cout << fixed << showpoint << setprecision(2);

// Respond to the user's menu selection.


switch (choice)
{
case ADULT_CHOICE:
cout << "For how many months? ";
cin >> months;
charges = months * ADULT;
cout << "The total charges are N" << charges << endl;
break;

case CHILD_CHOICE:
cout << "For how many months? ";
cin >> months;
charges = months * CHILD;
cout << "The total charges are N" << charges << endl;
break;
Loop Statement
A loop is a form of iteration such that values are read or written by incrementing or
decrementing process
• ++ and -- are operators that add and subtract 1 from their operands.
• Incrementing/decrementing value by 1
num = num + 1;
num += 1;
num = num - 1;
num -= 1;
Unary operators
++n or n++
--n or n--
Types of loops in C++
• While
• Do while
• for
While loop
• pretest loop
Infinite while loop
Do While loop
• The do-while loop is a posttest loop, which means its expression is tested after
each iteration.
do
{
statement ;
statement ;
// Place as many statements here
// as necessary.
} while ( expression );

NB: It must be terminated with a semicolon, “;”.


For Loop
• The for loop is ideal for performing a known number of iterations.
for ( initialization; test; update )
{
statement;
statement;
// Place as many statements here
// as necessary.
}
for (count = 0; count < 5; count++)
cout << "Hello" << endl;

• For loop is pretest


Nested for loop
cout << fixed << right;
cout.fill('0');
for (int hours = 0; hours < 24; hours++)
{
for (int minutes = 0; minutes < 60; minutes++)
{
for (int seconds = 0; seconds < 60; seconds++)
{
cout << setw(2) << hours << ":";
cout << setw(2) << minutes << ":";
cout << setw(2) << seconds << endl;
}
}
}
Function
• A function collection of statements that perform a specific task. It may or not
return a value or signal
• A function is declared void if it’s not expected to return a value
• It may contain values of parameters
• Mathematical functions
 pow,
 strcmp
Other Mathematical Functions
Function Conn’d
• Each procedure (function, subroutine) maintains a scratchpad of register values –
when another procedure is called (the called), the new procedure takeover the
scratchpad-value may have to be save so we can safely return to the caller.
Parts of function
• Return type: A function can send a value to the part of the program that executed
it. The return type is the data type of the value that is sent from the function.
• Name: You should give each function a descriptive name. In general, the same
rules that apply to variable names also apply to function names
• Parameter list: The program can send data into a function. The parameter list is a
list of variables that hold the values being passed to the function.
• Body: The body of a function is the set of statements that perform the function’s
operation. They are enclosed in a set of braces.
Variable types
• Global variable: any string or character in a program that is meant to assume any
value throughout the life a program irrespective of any function or
procedure/method. It is usually declared outside functions
• Local variable: any variable definition that is made within a function and is
consumed within the function.
Function call
A function call is a statement that causes a function to execute. A function definition
contains the statements that make up the function.
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
int main()
{
cout << "Hello from main.\n";
displayMessage();
cout << "Back in function main again.\n";
return 0;
}
void first();
void second();

int main()
{
cout << "I am starting in function main.\n";
first(); // Call function first
second(); // Call function second
cout << "Back in function main again.\n";
return 0;
}
// Definition of function first. *
// This function displays a message. *
void first()
{
cout << "I am now inside the function first.\n";
}
void second()
{
cout << "I am now inside the function second.\n";
}
Function prototypes
• A function prototype eliminates the need to place a function definition before all
calls to the function.
• In other words prototyping is function declaration
• When an argument is passed into a parameter, only a copy of the argument’s
value is passed. Changes to the parameter do not affect the original argument.
• Argument: is a value that is sent into function
Sending data into function
void changeMe(int);
int main()
{
int number = 12;
// Display the value in number.
cout << "number is " << number << endl;
// Call changeMe, passing the value in number
// as an argument.
changeMe(number);
// Display the value in number again.
cout << "Now back in main again, the value of ";
cout << "number is " << number << endl;
return 0;
}
// Definition of function changeMe. *
// This function changes the value of the parameter myValue. *
//**************************************************************
void changeMe(int myValue)
{
// Change the value of myValue to 0.
myValue = 0;
// Display the value in myValue.
cout << "Now the value is " << myValue << endl;
}
Changing argument variable
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r = a + b;
return r;
}
int main()
{
int x, y, z;
cout << "Enter First Number: ";
cin >> x;
cout << "Enter Second Number: ";
cin >> y;
z = addition (x, y);
cout << "The result =" << z <<endl;
}
Array
• A collection of finite data type stored in consecutive memory locations that could
be declared under one variable
• It can be declared any type
• It has name
• Each element of an array is identified by subscripts 0 - n
• The size of an array could be declared within rectangular brackets
• If an array is defined globally, all of its elements are initialized to zero by default.
Local arrays, however, have no default initialization value.
Array declaration
• const int NUM_DAYS = 6;
int days[NUM_DAYS];
• float temperatures[100]; // Array of 100 floats
• string names[10]; // Array of 10 string objects
• long units[50]; // Array of 50 long integers
• double sizes[1200]; // Array of 1200 doubles
? How many bytes does each declaration occupy of the computer memory
Storing a value in an array
• hours[0] = 20; //hours sub zero is assigned twenty
• Data is input to array memory location one after the other the spite it declared
with one variable
• Thus for loop is must suitable for input data to array
Input/Output array contents
int main()
{
const int NUM_EMPLOYEES = 6;
int hours[NUM_EMPLOYEES];
// Get the hours worked by each employee.
cout << "Enter the hours worked by "
<< NUM_EMPLOYEES << " employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
cin >> hours[4];
cin >> hours[5];
// Display the values in the array.
cout << "The hours you entered are:”;
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
return 0;
}
Using “for” loop to enter and display numbers
int main()
{
const int NUM_EMPLOYEES = 6; // Number of employees
int hours[NUM_EMPLOYEES]; // Each employee's hours
int count; // Loop counter
// Input the hours worked.
for (count = 0; count < NUM_EMPLOYEES; count++)
{
cout << “Enter the hours worked by employee ”
<< (count + 1) << ": "; //it could be count - 1
cin >> hours[count];
}
// Display the contents of the array.
cout << "The hours you entered are:";
for (count = 0; count < NUM_EMPLOYEES; count++)
cout << " " << hours[count];
cout << endl;
return 0;
}
Reading the content of a file to an
array
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int ARRAY_SIZE = 10; // Array size
int numbers[ARRAY_SIZE]; // Array with 10 elements
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
// Open the file.
inputFile.open("TenNumbers.txt");
// Read the numbers from the file into the array.
while (count < ARRAY_SIZE && inputFile >> numbers[count])
count++;
// Close the file.
inputFile.close();
// Display the numbers read:
cout << "The numbers are: ";
for (count = 0; count < ARRAY_SIZE; count++)
cout << numbers[count] << " ";
cout << endl;
return 0;
}
No bounds checking in
c++
• When size of an array is declared c++ doesn’t have way to ensure the attempted
input size equals the declared array size. E.g:
int main()
{
const int SIZE = 3; // Constant for the array size
int values[SIZE]; // An array of 3 integers
int count; // Loop counter variable
// Attempt to store five numbers in the three-element array.
cout << "I will store 5 numbers in a 3-element array!\n";
for (count = 0; count < 5; count++)
values[count] = 100;
// If the program is still running, display the numbers.
cout << "If you see this message, it means the program\n";
cout << "has not crashed! Here are the numbers:\n";
for (count = 0; count < 5; count++)
cout << values[count] << endl;
return 0;
}
Off-by-one Error
const int SIZE = 100;
int numbers[SIZE];
for (int count = 1; count <= SIZE; count++)
numbers[count] = 0;
• The loop starts from memory location 1 instead of 0
• The first element in the array will be skipped
• The program will write data beyond array boundaries (here 100 is an invalid
subscript) since 100 > the highest expected subscript
Array Initialization
• Finite arrays can be initialized as follow
int main()
{
const int MONTHS = 12;
int days[MONTHS] = { 31, 28, 31, 30, //note that MONTH != 12
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < MONTHS; count++)
{ cout << "Month " << (count + 1) << " has ";
cout << days[count] << “ days.\n";
} return 0;
}
The size of the array can be copie from the document type in the like of microsoft word.
Base on the diagramatical rario of the content base on the directly scripture on windows
from the program file in Linux and windows which will take you directly
Implicit Initialization
• Elements are entered to arrays without defining the size of the array
double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};
Range-Base “for” loop
• The range-based for loop is a loop that iterates once for each element in an array.
Each time the loop iterates, it copies an element from the array to a variable
int main()
{
string planets[] = { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus",
"Neptune", "Pluto (a dwarf planet)" };
cout << "Here are the planets:\n";
// Display the values in the array.
for (string val : planets)
cout << val << endl;
return 0;
}
Using “for” loop to sum
elements of an array
• Regular loop:
int total = 0; // Initialize accumulator
for (int count = 0; count < NUM_UNITS; count++)
total += units[count];
• Range loop
int total = 0; // Initialize accumulator
for (int val : units)
total += val;
Two dimensional
arrays
• An array type that hold two dimensional data, the like of Metrix
• Declaration

• Assigning elements in row 2 column 1


scores[2][1] = 92.25;
• Displaying elements of row 1 column 2
cout << scores[0][2];
Summing Contents of 2
dimensional arrays
3D Array
• It is possible to create arrays with multiple dimensions, to model data that occur in
multiple sets

• 3D array declaration
double seats[3][5][8];
Example of Array Manipulation at the
Hardware level
.data
x: .word 1,2,3,4,5,6,7,8,9,10 #55
iterator: .word 0
size: .word 9
prompt: .asciiz "The total sum of the array is: "
.text
main:
la $s0, prompt
la $s0, x
lw $t1, iterator
lw $t2, size
begin_loop:
bgt $t1, $t2 exit_loop
sll $t3, $t1, 2 #4.i
addu $t3, $t3, $t0 #x[i]
lw $t6, 0($t3)
addu $t7, $t7, $t6
addi $t1, $t1, 1
j begin_loop
exit_loop:
li $v0 4
la $a0, ($s7)
syscall
li $v0, 1
la $a0, ($s7)
syscall
Searching and Sorting Arrays

• A search algorithm is a method of locating a specific item in a larger


collection of data
• Types of search
 Linear Search and
 Binary Search
Recursion
• A recursive function is one that calls itself
void message()
{
cout << "This is a recursive function.\n";
message(); // an infinite loop
}
• System stores temporary data to stack each time a function is called
• The stack will be used up causing overflow
Message update
void message(int times)
{
if (times > 0) //assume value for times and assign it
{
cout << "This is a recursive function.\n";
message(times - 1);
}
}
Example of a recursive
function
void message(int);
int main()
{
message(5);
return 0;
}
void message(int times)
{
if (times > 0)
{
cout << "This is a recursive function.\n";
message(times - 1);
}
}
Example 2: Factorial of a
number
int factorial(int);
int main()
{
int number;
cout << "Enter an integer value and I will display\n";
cout << "its factorial: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
return 0;
}
int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive case
}
Using Recursion to Count Occurrence of a
Specific Character in a String
int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive case
}
else if (str[subscript] == search)
{
// Recursive case: A matching character was found.
// Return 1 plus the number of times the search
// character appears in the rest of the string.
return 1 + numChars(search, str, subscript+1);
}
else
{
// Recursive case: A character that does not match the
// search character was found. Return the number of times
// the search character appears in the rest of the string.
return numChars(search, str, subscript+1);
}
}

• search : The character to be searched for and counted


• str : a string object containing the string to be searched
• subscript : The starting subscript for the search
Indirect Recursion
• When a function calls another function such that the initial function is called again
the recursion is said to be indirect
void showMe(int arg);
int main()
{
int num = 0;
showMe(num);
return 0;
}
void showMe(int arg)
{
if (arg < 10)
showMe(++arg);
else
cout << arg << endl;
}
Possibilities in examination
of character
• The end of the string has been reached. This is the base case because there are no
more characters to search.
• A character that matches the search character is found. This is a recursive case
because we still have to search the rest of the string.
• A character that does not match the search character is found. This is also a
recursive case because we still have to search the rest of the string.
OOP Features
• An object is a software entity that contains both data and procedures
• The data that are contained in an object are known as the object’s attributes
• The procedures that an object performs are called member functions
Why OOP
• What happens if the format of the data is altered?
 program’s specifications change, resulting in redesigned data structures and this
generates bugs consequently
• Data protection from corruption – liken to automobile and the driver
 It ensures that the class you create operate the way you intend it
• Object reusability
What is it?
It is a programming paradigm that extensively uses objects to create program
What is a class
• A class is code that specifies the attributes and member functions that a particular
type of object may have or a description of an object
• Each object that is created from a class is called an instance of the class
Instance of a class
Instance of a class
cont’d
• Definition of class object is called an instance of the class
Class Blueprint
Member Functions

Procedures

Storing data from


setWidth() and setLength()
Accessing Private variables in
different class
Accessing Private member
variable can also be like this:

No alteration can be done


anymore to stored data
Access declaration can also be
done like this:
Defining Member Functions
• When Rectangle:: appears before the name of a function in a function header, it
identifies the function as a member of the class say, rectangle class
• In general, member class function is declared:
ReturnType ClassName :: functionName ( ParameterList )
• Example:
Accessor and Mutator
• A member function that gets a value from a class’s member variable but does not change it is
known as an accessor
• A member function that stores a value in member variable or changes the value of member
variable in some other way is known as a mutator
Using const with
Accessors
• When you mark a member function as const , the const key word must appear in
both the declaration and the function header:
double Rectangle::getWidth() const
double Rectangle::getLength() const
double Rectangle::getArea() const
Accessing Object
Members
• Use the dot operator to call class member function:
box.setLength(4.8); // Set box's length to 4.8.
x = box.getWidth(); // Assign box's width to x.
cout << box.getLength(); // Display box's length.
cout << box.getArea(); // Display box's area.
Class demonstration
It is demonstrated in netbean:
Rectangle class with three instances
Stale Data
• The area of rectangle is not stored in an member function variable because if that
happen a change in length/width wont correspondingly result to change in area,
making area a stale data
Pointer Objects
Rectangle myRectangle; // A Rectangle object
Rectangle *rectPtr = nullptr; // A Rectangle pointer: initialization
rectPtr = &myRectangle; // rectPtr now points to myRectangle

rectPtr = new Rectangle //Dynamically allocate Rectangle object to rectPtr


rectPtr->setWidth(12.5); //calling rectangle’s member function
rectPtr->setLength(4.8); //since the pointer had successfully located rectangle
delete rectPtr; // deletes object from the memory
rectPtr = nullptr; // stores zero in rectPtr
Inline Member
Function
• When the body of a member function is written inside a class declaration, it is
declared inline. Example:
public:
void setWidth(double);
void setLength(double);
double getWidth() const
{ return width; }
double getLength() const
{ return length; }
double getArea() const
{ return width * length; }
Constructor
• A constructor is a member function that is automatically called when a class object
is created. It is denoted:
• ClassName :: ClassName ( ParameterList )
• A constructor’s purpose is to initialize an object’s attributes to avoid returning
garbage
• A default constructor is a constructor that takes no arguments:
Rectangle::Rectangle()
{}
Default Constructors and
Dynamically Allocated Objects
Rectangle *rectPtr = nullptr;
rectPtr = new Rectangle;
Passing Arguments to
Constructors
• A constructor can have parameters and can accept arguments when an object is
created
Distructors
• A destructor is a member function that is automatically called when an object is
destroyed.
• Primary aim is to free memory that is dynamically allocated
• Just like constructors, baring the name of a class, they are however prefixed with
“~” say, ~Rectangle()
Example:
class Demo
{
public:
Demo(); // Constructor
~Demo(); // Destructor
};
Demo::Demo()
{
cout << "Welcome to the constructor!\n";
}
Demo::~Demo()
{
cout << "The destructor is now running.\n";
}
int main()
{
Demo demoObject; // Define a demo object;
cout << "This program demonstrates an object\n";
cout << "with a constructor and destructor.\n";
return 0;
}
Inheritance
• Inheritance allows a new class to be based on an existing class. The new class
inherits all the member variables and functions (except the constructors and
destructor) of the class it is based on
• Inheritance emphasizes:
 Based class; and
 Derived class
Example of a Base Class
#ifndef GRADEDACTIVITY_H
#define GRADEDACTIVITY_H
// GradedActivity class declaration
class GradedActivity
{
private:
double score; // To hold the numeric score
public:
// Default constructor
GradedActivity()
{ score = 0.0; }
// Constructor
GradedActivity(double s)
{ score = s; }
// Mutator function
void setScore(double s)
{ score = s; }
// Accessor functions
double getScore() const
{ return score; }
char getLetterGrade() const;
};
#endif
Derived Class
Private Members:
int numQuestions Declared in the FinalExam class
double pointsEach Declared in the FinalExam class
int numMissed Declared in the FinalExam class
Public Members:
FinalExam() Defined in the FinalExam class
FinalExam(int, int) Defined in the FinalExam class
set(int, int) Defined in the FinalExam class
getNumQuestions() Defined in the FinalExam class
getPointsEach() Defined in the FinalExam class
getNumMissed() Defined in the FinalExam class
setScore(double) Inherited from GradedActivity
getScore() Inherited from GradedActivity
getLetterGrade() Inherited from GradedActivity
Protected Members and Class
Access
• Protected members of a base class are like private members, but they may be accessed by derived
classes. The base class access specification determines how private, public, and protected base class
members are accessed when they are inherited by the derived classes
Example:
#ifndef GRADEDACTIVITY_H
#define GRADEDACTIVITY_H
// GradedActivity class declaration
class GradedActivity
{
protected:
double score; // To hold the numeric score
10 public:
// Default constructor
GradedActivity()
{ score = 0.0; }
// Constructor
GradedActivity(double s)
{ score = s; }
// Mutator function
void setScore(double s)
{ score = s; }
// Accessor functions
double getScore() const
{ return score; }
char getLetterGrade() const;
};
#endif
Constructors and Distructors
in Base and Derived Class
• The base class’s constructor is called before the derived class’s constructor. The destructors are
called in reverse order, with the derived class’s destructor being called first
Polymorphism
• The term polymorphism means the ability to take many forms
• Polymorphism allows an object reference variable or an object pointer to reference
objects of different types and to call the correct member functions, depending
upon the type of object being referenced
• It passes object by reference, not value
Polymorphism Conn’d
• The process of matching a function call with a function at compile time is called
static binding
• A virtual function is a member function that is dynamically bound to function calls
• Virtual functions are defined in a baseclass function: virtual char getLetterGrade()
const;
• Base class pointers and references know only about base class members
• When a class redefines a virtual function, it is said that the class overrides the
function
Polymorphism Conn’d
• When the constructor of a base class is dynamically assigned to a derived class it
will be destroyed when the constructor of the derived class is destroyed
• Use the override key word in the derived class’s function prototype to override
member function from a base class
• To prevent a member function of a base class from being overridden in a derived
class, the function has to be decleared: virtual void message() const final;
and Pure Virtual
Function
• An abstract base class cannot be instantiated, but other classes are
derived from it (objects can't be created directly from the class)
• A pure virtual function is a virtual member function of a base class
that must be overridden
• When a class contains a pure virtual function as a member, that class
becomes an abstract base class
An Abstract Base Class and
Pure Virtual Function
• Declaration of pure virtual member function is decleared: virtual void showInfo()
= 0; (this prevents instantiation)
• What is the difference between redefining and overriding a function?
Multiple Inheritance
• Multiple inheritance is when a derived class has two or more base classes
• General format for declaring a multiple base class:
class DerivedClassName : AccessSpecification BaseClassName ,
AccessSpecification BaseClassName [, ...]
• General format of derived class inheritance constructor:
DerivedClassName ( ParameterList ) : BaseClassName ( ArgumentList ),
BaseClassName ( ArgumentList )[, ...]
Example:
DateTime::DateTime(int dy, int mon, int yr, int hr, int mt, int sc) :
Date(dy, mon, yr), Time(hr, mt, sc)
Multiple Inheritance
Conn’d

• It is advisable to use scope resolution “::” in situation where derived class used
multiple base classes having member variables of functions with the same name
(no function overload)
Exceptions, Templates and
Standard Template Libraries
(STL)
• Exceptions are used to signal errors or unexpected events that occur while a
program is running
Example of Exception
OO Exception
Multiple Exception
• Where multiple exception is required, each exception should have its own class
Typical Example of Multiple Exception

You might also like