0% found this document useful (0 votes)
2 views

SCS202_OBJECT ORIENTED PROGRAMMING

The document provides an overview of Object-Oriented Programming (OOP) concepts, including characteristics such as encapsulation, inheritance, and polymorphism. It explains the structure of classes and objects, emphasizing data abstraction and message passing. Additionally, it covers the basics of C++ programming, including variable declaration, initialization, and program structure.

Uploaded by

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

SCS202_OBJECT ORIENTED PROGRAMMING

The document provides an overview of Object-Oriented Programming (OOP) concepts, including characteristics such as encapsulation, inheritance, and polymorphism. It explains the structure of classes and objects, emphasizing data abstraction and message passing. Additionally, it covers the basics of C++ programming, including variable declaration, initialization, and program structure.

Uploaded by

obotemiltone4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

OBJECT ORIENTED

PROGRAMMING
SCS202
Lecturer’s Name: Kirema Mutembei

[email protected]
Basic Object Oriented concept
Some Characteristics of Object Oriented Programming

 Emphasis is on data rather than procedure.

 Programs are divided into what are known as objects.

 Data structures are designed such that they characterize the objects.

 Functions that operate on the data of an object are ties together in the data structure.

 Data is hidden and cannot be accessed by external function.

 Objects may communicate with each other through function.

 New data and functions can be easily added whenever necessary.

 Follows bottom up approach in program design.


Principles of object-oriented programming, all OOP
languages, including C++, have the following characteristics

 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing
Objects
 An object is an identifiable entity with specific characteristics and behavior.
 An object is said to be an instance of a class.
 Real world objects have two parts:
 Properties (or state :characteristics that can change),
 Behavior (or abilities :things they can do).

 They may represent a person, a place, a bank account, a table of data or any item that the
program has to handle.
 They may also represent user-defined data such as vectors, time and lists.
 Programming problem is analysed in term of objects and the nature of communication
between them.
 When a program is executed, the objects interact by sending messages to one another.
 For example, if “customer” and “account” are to object in a program, then the customer
object may send a message to the count object requesting for the bank balance.
 Each object contain data, and code to manipulate data.
 Objects can interact without having to know details of each other’s data or code.
 It is sufficient to know the type of message accepted, and the type of response returned
by the objects.
Class
 A class is a user defined data type.
 A class is a collection of objects (or values) and a corresponding set of methods.
 It is a template that defines the form of an object.
 A class is thus a collection of objects of similar types. For examples, guava, mango and
orange are members of the class fruit.
 A class specifies both code and data.
 It is not until an object of that class has been created that a physical representation of
that class exists in memory.
 When you define a class, you declare the data that it contains and the code that
operates on that data.
 Data is contained in instance variables defined by the class known as data members,
and code is contained in functions known as member functions.
 The code and data that constitute a class are called members of the class.
 If fruit has been defines as a class, then the statement
 Fruit Mango; will create an object mango belonging to the class fruit.
Encapsulation and Data Hiding
 Means of data hiding
 Encapsulation is a programming mechanism that binds together code and
the data it manipulates, and that keeps both safe from outside interference
and misuse.
 C++’s basic unit of encapsulation is the class.
 Within a class, code or data or both may be private to that object or public.
 Private code or data is known to and accessible by only another part of the
object.
 That is, private code or data cannot be accessed by a piece of the program
that exists outside the object.
 When code or data is public, other parts of your program can access it
even though it is defined within an object.
 This insulation of the data from direct access by the program is called data
hiding.
 Data can be encapsulated such that it is invisible to the “outside world”.
 Data can only be accessed via methods
Data abstraction
 Abstraction refers to the act of representing essential features without
including the background details or explanation.

 The internal details of the objects are hidden which makes them abstract.

 The technique of hiding internal details in an object is called data


abstraction.

 The user needs to know the external interfaces only to make use of an object

 The data is hidden, so it is safe from accidental alteration.


Inheritance
 Inheritance is the process by which one object can acquire the properties of another object.
 Inheritance is the mechanism by which one class can inherit the properties of another
 The class that is inherited is called the base class/super class the inheriting class is called
the derived class/sub class
 In OOPs, the concept of inheritance provides the idea of reusability.
 In essence, the base class represent the most general description of a set of traits.
 The derived class inherits those general traits and adds properties that are specific to that
class.
 For example, a Hash Avocado is part of the classification Avocado, which in turn is part of the
fruit class, which is under the larger class food.
 That is, the food class possesses certain qualities (edible, nutritious, and so on) which also,
logically, apply to its subclass, fruit.
 In addition to these qualities, the fruit class has specific characteristics (juicy, sweet, and so
on) that distinguish it from other food.
 The Avocado class defines those qualities specific to an Avocado (grows on trees, tropical,
and so on).
 A Hash Avocado would, in turn, inherit all the qualities of all preceding classes and would
define only those qualities that make it unique.
Polymorphism

 Polymorphism (from the Greek, meaning “many forms”) is a feature that


allows one interface to be used for a general class of actions

 Polymorphism: One piece of code works with all shape objects.

 This means that it is possible to design a generic interface to a group of


related activities.

 This helps reduce complexity by allowing the same interface to be used to


specify a general class of action

 In compile time polymorphism, the compiler is able to select the


appropriate function for a particular call at compile time
Dynamic binding
 Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
 Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time.
 Dynamic binding: How polymorphism is implemented
 A function call associated with a polymorphic reference depends
on the dynamic type of that reference.
 Consider the procedure “draw” by inheritance, every object will
have this procedure.
 Its algorithm is, however, unique to each object and so the draw
procedure will be redefined in each class that defines the object.
 At run-time, the code matching the object under current
reference will be called
Message passing

 An object-oriented program consists of a set of objects that


communicate with each other.
 Objects communicate with one another by sending and
receiving information.
 Message for an object is a request for execution of a
procedure, and therefore will invoke a function (procedure) in
the receiving object that generates the desired results.
 Message passing involves specifying the name of object, the
name of the function (message) and the information to be
sent.
Benefits of Object oriented Programming

 Simplicity: Software objects model real world objects, so the


complexity is reduced and the program structure is very clear.
 Modularity: Each object forms a separate entity whose internal
workings are decoupled from other parts of the system.
 Modifiability: It is easy to make minor changes in the data
representation or the procedures in an OO program. Changes
inside a class do not affect any other part of a program, since the
only public interface that the external world has to a class is
through the use of methods.
 Extensibility: adding new features or responding to changing
operating environments can be solved by introducing a few new
objects and modifying some existing ones.
 Maintainability: objects can be maintained separately, making
locating and fixing problems easier.
 Re-usability: objects can be reused in different programs.
Terminologies in OOP
 A message is a request to an object to invoke one of its methods. A message
therefore contains the name of the method and the arguments of the method.

 A method is associated with a class. An object invokes methods as a reaction to


receipt of a message.

 A statement is a simple or compound expression that can actually produce some


effect
Introduction to C++

Creating a program

 Use a text editor to write a program and save it in a file →


source code

 Compile the source code (compiler is a program that


translates the source code to machine language) → object
code

 Link the object code with additional code (libraries) →


executable code
Structure of a program
#include <iostream>
using namespace std;
int main ()
{
//body
cout << " Hello World ";
return 0 ;
}
Structure of a program
// Sample program that input values for the length and width of a rectangle
// and returns the perimeter and area of the rectangle.
#include <iostream>
using namespace std;
int main ()
{
int length, width;
int perimeter, area; // declarations
cout << "Length = "; // prompt user
cin >> length; // enter length
cout << "Width = "; // prompt user
cin >> width; // input width
perimeter = 2*(length+width); // compute perimeter
area = length*width; // compute area
cout << endl << "Perimeter is " << perimeter;
cout << endl << "Area is " << area<< endl;
return 0 ; // output results
Structure of a program Explained
Comments
 Comments are ignored by the compiler. This is a comment line. Comments and do not have any
effect on the behaviour of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief
description of what our program is.
 Types of comments //…………..line comment and /*…………………*/ block comment
Compiler directive
#include <iostream>
 The #include directive instructs the compiler to include the contents of the file enclosed within
angular brackets into the source file. The header file iostream.h should be included at the
beginning of all programs that use input/output statements.
 Lines beginning with a hash sign (#) are directives for the preprocessor. In this case the
directive #include <iostream> tells the preprocessor to include the iostream standard file. This
specific file (iostream) includes the declarations of the basic standard input-output library in C+
+, and it is included because its functionality is going to be used later in the program.
using namespace std;
 Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a
scope for the identifiers that are used in a program. For using the identifier defined in the
namespace scope we must include the using directive, like Using namespace std;
main function
int main ()
 This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution, independently of its
location within the source code. It does not matter whether there are other functions with
other names defined before or after it – the instructions contained within this function's
definition will always be the first ones to be executed in any C++ program.
The Body
 The body of the main function enclosed in braces ({}). What is contained within these
braces is what the function does when it is executed.
cout << "Length = ";
 cout represents the standard output stream in C++, and the meaning of the entire
statement is to insert a sequence of characters into the standard output stream (which
usually is the screen).
cin >> length; cin represents the standard input stream in C++,
return 0;
 The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program worked as expected without any
errors during its execution. This is the most usual way to end a C++ console program.
Variables and constant
 A variable is a named area in memory used to store values during program execution.
 An identifier is a name assigned to a function, variable, constant or any other user-
defined item
 An identifier or name of variable must:
a) start with a letter
b) consist only of letters, the digits 0 to9, or the underscore symbol _
c) not be a reserved word
d) Uppercase and lowercase are distinct
 Reserved words are valid identifiers that have special significance to C++.
 The syntax rules of C++ define certain symbols to have a unique meaning within a C+
+ program.
 These symbols, the reserved words, must not be used for any other purposes. And
reserved words are in lower-case letters.
 The C++ language is a "case sensitive" language. That means that an
identifier written in capital letters is not equivalent to another one with the same
name but written in jisaduku letters.
Basic fundamental data types

Data type defines size and type of values that a variable can store along with the set of
operations that can be performed on that variable.
Declaration of variables
 All the variables must be declared prior to use in a program
 When a variable is given a value, that value is actually placed in the memory space assigned to
the variable.
 All variables must be declared before they can be used.
 Declaration purposes:
 It associates a type and an identifier (or name) with the variable
 it allows the compiler to decide how much storage space to allocate for storage of the value
associated with the identifier and to assign an address for each depending with type.

 The syntax to declare a new variable is to write the specifier of the desired data type (like int,
bool, float...) followed by a valid variable identifier. For example:
 int x; //declares a variable of type int with the identifier x
 Float myage; // declares a variable of type float with the identifier myage
 Once declared, the variables x and myage can be used within the rest of their scope in the
program.
 To declare more than one variable of the same type, can be declared all of them in a single
statement by separating their identifiers with commas. For example:
 int x, y, z;
Example

// operating with variables }


#include <iostream> Results 4
using namespace std;
int main ()
{
int a, b; // declaring variables:
int result; // declaring variables:
a = 5; // process:
b = 2; // process:
a = a + 1; // process:
result = a - b; // process:
cout << result; // print out the
result:
return 0; // terminate the program:
Scope of variables
 A variable can be either of global or local scope.
 A global variable is a variable declared in the main body of the source code, outside all
functions,
 Local variable is one declared within the body of a function or a block.
Initialization of variables
 Initializing is is giving value to a variable
 Initializing the variable to stores a concrete value at the same moment
that it is declared. There are two ways to do this in C++:
 Done by appending an equal sign followed by the value to which the
variable will be initialized:
 type identifier = initial_value ;
 To declare an int variable called age initialized with a value of 21 , we
could write:
 int age = 21;
 The other way to initialize variables, known as constructor initialization, is
done by enclosing the initial value between parentheses (()):
 type identifier (initial_value) ;
 For example:
 int age (21);
Example
// initialization of variables return 0;
#include <iostream> }
using namespace std; Results 6
int main ()
{
int x =5; // initial value
=5
int y(2); // initial value
=2
int result; // initial value
undetermined
x = x + 3;
result = x - y;
cout << result;
Introduction to strings
 Strings are Variables that can store non-numerical values that are
longer than one single character
 To declare and use objects (variables) of this type we need to
include an additional header file in our source code: <string>
(#include <string> )
 Strings can be initialized with any valid string literal just like
numerical type variables can be initialized to any valid numerical
literal.
 Both initialization formats are valid with strings:
 string mystring = "This is a string";
 string mystring ("This is a string");
 Strings can also perform all the other basic operations that
fundamental data types can, like being declared without an initial
value and being assigned values during execution:
Example

// my first string }
#include <iostream>
#include <string> This is the initial string content
using namespace std; This is a different string content
int main ()
{
string mystring;
mystring = "This is the initial string
content";
cout << mystring << endl;
mystring = "This is a different string
content";
cout << mystring << endl;
return 0;
Constants and the declaration of constants
 Constants are expressions with a fixed value.
 Constants refer to fixed values that the program cannot alter
 The names given to constants must conform to the rules for the
formation of identifiers as defined
 The general form of a constant declaration is:
 const type constant-identifer = value ;
 const int days_in_year = 365;
 const float pie = 3.142;
 type is the type of the constant,
 constant-identifer is the identifier chosen for the constant, which
must be distinct from all identifers for variables,
 value is an expression involving only constant quantities that gives
the constant its value
Example
// Declared constants: calculate circumference
#include <iostream>
using namespace std;
int main ()
{
const int PI = 3.14159; // Declared constants
const char tabulator = '\t'; // Declared constants
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << tabulator;
return 0;
}
31.4159
Literal and Define constants
Literals Constant are used to express particular values within the source code of a
program.
 age= 21; // 21 literal constant.
 Literal constants can be divided in Integer Numerals, Floating-Point Numerals,
Characters, Strings, Boolean Values
 Character and string literals.
'z‘ and 'p'// Character constant literals.
"Hello world“ and "How do you do?“ // string literal constant.
Defined constants (#define)
 defined by own names for constants and used very often without having to resort to
memory consuming variables, by using the #define pre-processor directive. Its format
is:
#define identifier value
For example:
 #define PI 3.14159
 #define NEWLINE '\n'
Example
// defined constants: calculate circumference
#include <iostream>
using namespace std;

#define PI 3.14159 // defined constants PI


#define NEWLINE '\n' // defined constants NEWLINE

int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
31.4159
Operator
 An operator is a symbol that tells the compiler to perform
specific mathematical or logical manipulations
 C++ is rich in built-in operators and are mainly keywords
 Generally, there are six type of operators:
 Arithmetical operators
 Relational operators,
 Logical operators,
 Assignment operators,
 Conditional operators,
 Comma operator.
Arithmetic operators ( +, -, *, /, % )
Arithmetical operators are used to performs an arithmetic
(numeric) operation
Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

Modulus or remainder % is the operation that gives the remainder of a division of two
values. For example, if we write:
a = 11 % 3;
the variable a will contain the value 2, since 2 is the remainder from dividing 11 between
3.
Relational operators

 The relational operators are used to test the relation between


two values.

 All relational operators are binary operators and therefore


require two operands.

 A relational expression returns zero when the relation is false


and a non-zero when it is true.
Relational operators

Operator Meaning Example


Returns TRUE if first value is less than second value otherwise 10 < 5 is
<
returns FALSE FALSE
Returns TRUE if first value is larger than second value otherwise 10 > 5 is
>
returns FALSE TRUE
Returns TRUE if first value is less than or equal to second value 10 <= 5 is
<=
otherwise returns FALSE FALSE
Returns TRUE if first value is larger than or equal to second value 10 >= 5 is
>=
otherwise returns FALSE TRUE
10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE
10 != 5 is
!= Returns TRUE if both values are not equal otherwise returns FALSE
TRUE
Logical operators ( !, &&, || )
 The Operator ! is the C++ operator to perform the Boolean operation NOT,
 It produces false if its operand is true and true if its operand is false.
 Basically, it returns the opposite Boolean value of evaluating its operand

Expression Meaning
!(5 == 5) evaluates to false because the
expression at its right (5 == 5)
is true.
!(6 <= 4) evaluates to true because (6 <=
4) would be false.
!true evaluates to false
!false evaluates to true
Logical operators ( AND i.e &&, || i.e
OR)
 The logical operators && and || are used when evaluating two expressions to obtain a
single relational result.
 The operator && corresponds with Boolean logical operation AND.
 This operation results true if both its two operands are true, and false otherwise
 The operator || corresponds with Boolean logical operation OR.
 This operation results true if either one of its two operands is true, thus being false
only when both operands are false themselves.

A B a && b a b a||b
true true true true true true
true False false true false true
false false false false true true

false false false false false false


Assignment operators
 The assignment operator '=' is used for assigning a variable to a value.
 This operator takes the expression on its right-hand-side and places it into the
variable on its left-hand-side.

Operator Example Equivalent to

+= A+=2 A=A+2

-= A-=2 A=A- 2

%= A % =2 A=A%2

/= A /= 2 A=A/2

*= A *= 2 A=A*2
Increment and Decrement Operators
 incrementing and decrementing the value of a variable by 1
 Increment and decrement operators each have two forms, pre and post
 In Prefix form first variable is first incremented/decremented, then evaluated
 In Postfix form first variable is first evaluated, then incremented /
decremented.

 The syntax of the increment operator is:


 Pre-increment: ++variable
 Post-increment: variable++
 The syntax of the decrement operator is:
 Pre-decrement: ––variable
 Post-decrement: variable––
Conditional operators ( ? )
 The conditional operator ?: is called ternary operator as it requires
three operands.
 The format of the conditional operator is : Conditional_ expression ?
expression1 : expression2; If the value of conditional expression is true
then the expression1 is evaluated, otherwise expression2 is evaluated.
 If condition is true the expression will return result1, if it is not it will
return result2.
 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
 5>3 ? a : b // returns the value of a, since 5 is greater than 3.
 a>b ? a : b // returns whichever is greater, a or b.
Comma operator ( , )
 The comma operator (,) is used to separate two or more
expressions that are included where only one expression is
expected.
 When the set of expressions has to be evaluated for a value,
only the rightmost expression is considered.
 For example, the following code:
a = (b=3, b+2);
 Would first assign the value 3 to b, and then assign b+2 to
variable a. So, at the end, variable a would contain the value 5
while variable b would contain value 3.
Typecasting
 Typecasting is the concept of converting the value of one type into
another type. For example, you might have a float that you need to use
in a function that requires an integer.
Implicit conversion
 The compiler automatically converts one type into another type the
user has no control
Explicit conversion
 The C++ language have ways to give you back control. This can be
done with what is called an explicit conversion.
int i;
float f = 3.14;
i = (int) f;
Control Structures
Control structures allows to control the flow of program’s execution based on certain
conditions C++ supports following basic control structures:
 Conditional structure
 if and if else statements
 Iteration structures (loops)
 The while loop
 The do while loop
 The for loop
 The selective structure
 switch statement
 Jump statements
 The break statement
 The continue statement
 The goto statement
if and if else statements

 An if statement consists of a Boolean expression followed by one or more


statements.
 Where condition is the expression that is being evaluated.
 If this condition is true, statement is executed.
 If it is false, statement is ignored (not executed) and
 the program continues right after this conditional structure.

Syntax
If (boolean_expression)
{
/* statement(s) will execute if
the boolean expression is true */
}
if - else statement

 An if statement can be followed by an optional else statement, which


executes when the Boolean expression is false.
 If the Boolean expression evaluates to true, then the if block will be
executed,
 otherwise, the else block will be executed.

Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}

else
{
/* statement(s) will execute if the boolean expression is false */
}
Example
#include <iostream>
using namespace std;

int main ()
{
/* local variable definition */
int x = 100;
/* check the boolean condition */
if (x == 100)
{
cout << "x is ";
cout << x;
}
return 0;
}
If else // Program to evaluate a wage

#include <iostream>
using namespace std;
cin >> hourly_rate;

int main () // calculate wage


{ if (hours_worked <= limit)
wage = hours_worked * hourly_rate;
const float limit = 40.0,
else
overtime_factor = 1.5; wage = (limit + (hours_worked -
float hourly_rate, // hourly rate of pay limit) * overtime_factor)* hourly_rate;
hours_worked, // hours worked
// Output wage
wage; // final wage cout << "Wage for " <<
hours_worked << " hours at " <<
hourly_rate << " is " << wage <<
// Enter hours worked and hourly rate
endl;
cout << "Enter hours worked: "; return 0;
cin >> hours_worked; }
cout << "Enter hourly_rate: ";
if...else if...else Statement

 This chain is evaluated from the top and, if a particular if-conditional is TRUE,

 then its statement is executed and the chain is terminated.

 On the other hand, if the conditional is FALSE, the next if-conditional is tested.

 If all the conditionals evaluate to FALSE, then the final else statement is
executed as a default.
if...else if...else Statement
Syntax

if(boolean_expression 1)
{ /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{ /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{ /* Executes when the boolean expression 3 is true */
}
else
{ /* executes when the none of the above condition is true */
}

Modify the wage program to include commission


Nested if Statements
 nest if-else statements, which means you can use one if or
else if statement inside another if or else if statement(s).
The syntax for a nested if statement is as follows

if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
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 switch case.

The following rules apply to a switch statement:

 The expression used in a switch statement must have an integral or


enumerated type,

 You can have any number of case statements within a switch.

 Each case is followed by the value to be compared to and a colon.

 The constant-expression for a case must be the same data type as


the variable in the switch, and it must be a constant or a literal.
switch Statement
 When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.

 When a break statement is reached, the switch terminates, and the


flow of control jumps to the next line following the switch statement.

 Not every case needs to contain a break. If no break appears, the flow
of control will fall through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must


appear at the end of the switch.

 The default case can be used for performing a task when none of the cases is
true. No break is needed in the default case.
Syntax
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);
}
Example
// Program to evaluate grade case 'D' :
#include <iostream> cout<< "You passed\n" ;
using namespace std; break;
int main () case 'F' :
{ cout<< "Better try again\n" ;
/* local variable definition */ break;
char grade = 'B'; default :
cout<< "Invalid grade\n" ;
switch(grade) }
{ cout<< "Your grade is \n"<< grade ;
case 'A' :
cout<< "Excellent!\n"; return 0;
break; }
case 'B' :
cout<< "Well done\n" ;
break; Convert the nested if else
case 'C' : commission program to switch
cout<< "good done\n" ; statements
break;
Switch vs if else

switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
cout << "x is 2"; }
break; else {
default: cout << "value of x
cout << "value of x unknown"; unknown" }
}
switch statement

 // custom countdown using while

 #include <iostream>
 using namespace std;

 int main ()
 {
 int n;
 cout << "Enter the starting number > ";
 cin >> n;

 while (n>0) {
 cout << n << ", ";
 --n;
 }

 cout << "FIRE!\n";


 return 0;
 }
Iteration structures (loops)

 Loops have as purpose to repeat a statement a certain number of times


or while a condition is fulfilled.
 A loop statement allows us to execute a statement or group of
statements multiple times.

 The while loop


 The do while loop
 The for loop
The for loop
 A for loop is a repetition control structure that allows
programmer to efficiently write a loop that needs to execute a
specific number of times.

 It works in the following way:

 1. initialization is executed. Generally it is an initial value setting for a


counter variable. This is executed only once.

 2. condition is checked. If it is true the loop continues, otherwise the loop


ends and statement is skipped (not executed).

 3. statement is executed. As usual, it can be either a single statement or a


block enclosed in braces { }.
The for loop
 4. finally, whatever is specified in the increase field is executed and the loop
gets back to step
 The syntax

for ( initialization ; condition; increment )


{
statement(s);
}
Example

// countdown using a for loop


#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
The while loop
 Executes a target statement as long as a given condition is true.
 Functionality is simply to repeat statement while the condition
Set in expression is true.

while(condition)
{
statement(s);
}
Example
// custom countdown using while
1. User assigns a value to n
#include <iostream>
2. The while condition is checked (n>0).
using namespace std; At this point there are two posibilities:
int main () * condition is true: statement is executed
{ (to step 3)
int n;
* condition is false: ignore statement and
continue after it (to step 5)
cout<<"Enter the starting number > ";
3. Execute statement: cout << n << ", ";
cin >> n; --n; (prints the value of n on the screen
while (n>0) { and decreases n by 1)
cout<< n << ", "; 4. End of block. Return automatically to
step 2
--n;
5. Continue the program right after the
} block: print FIRE! and end program.
cout << "FIRE!\n";
return 0;
}
The do-while loop
 Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in checks its condition at the bottom of the loop.
 A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.
 The conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
 If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again.
 This process repeats until the given condition becomes false.

 The syntax of a do...while loop


do
{
statement(s);

}while( condition );
Example
// number echoer
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
Nested Loops loop inside another loop
The syntax for a nested for loop statement }
for ( init; condition; increment ) statement(s);
{ }
for ( init; condition; increment )
{ The syntax for a nested do...while loop
statement
statement(s);
}
do
statement(s);
{
}
statement(s);
do
The syntax for a nested while loop
statement {
while(condition) statement(s);
{ }while( condition );
while(condition)
{statement(s); }while( condition );
C++ CLASSES AND OBJECTS

 A class is used to specify the form of an object and it combines data


representation and methods for manipulating that data into one neat package
 Classes represent real world entities that have both data type properties
(characteristics) and associated operations (behavior).
 The data and functions within a class are called members of the class.
 A class definition starts with the
 keyword class followed by the class name;
 and the class body, enclosed by a pair of curly braces.
 A class definition must be followed either by a semicolon or a list of
declarations.
 The body of the declaration can contain members, that can be
either data or function declarations, and optionally access
specifiers.
C++ Class Definitions
Class name_of _class
{
private ://access specifiers
variable declaration; // data member
Function declaration; // Member Function (Method)
protected:
Variable declaration;
Function declaration;
public :
variable declaration;
Function declaration;
}; // end with a semicolon
C++ CLASS MEMBER FUNCTIONS

 An access specifier is one of the following three keywords: private, public or


protected.

 These specifiers modify the access rights that the members following them
acquire:

 private members of a class are accessible only from within other members
of the same class or from their friends.

 protected members are accessible from members of their same class, from
their friends and members of their derived classes.

 public members are accessible from anywhere where the object is visible.

 All members of a class declared with the class keyword have private access
for all its members.
C++ CLASS MEMBER FUNCTIONS
 Any member that is declared before one other class specifier
automatically has private access

 Member functions can be defined within the class definition or


separately using scope resolution

 a) Inside class definition (inline function)

Defining a member function within the class definition declares the


inline function

 (b) Outside class definition using scope resolution operator (::)

The operator::known as scope resolution operator helps in defining


the member function outside the class
Member functions Definition/ Declaration

 a) Inside class definition (inline function)

class Box {
public:
double length; // Length of a box
double width; // width of a box
double height; // Height of a box
double getVolume(void) //inside class definition
{//body of the member function
return length * breadth * height;
}
};
Member functions Definition/ Declaration
 (b) Outside class definition using scope resolution operator (::)

class Box
{
public:
double length; // Length of a box
double width; // width of a box
double height; // Height of a box
double getVolume(void)
};
//outside class definition
double Box::getVolume(void)
{//body of the member function
return length * breadth * height;
}
Accessing the Data Members
 The public data members of objects of a class can be accessed
using the direct member access operator . (dot operator)
 A member function will be called using a dot operator (.) on a
object where it will manipulate data related to that object only
as follows –

 Box myBox; // Create an object

 myBox.getVolume(); // Call member function for the object


C++ CLASS ACCESS MODIFIERS
Data hiding is one of the important features of Object Oriented
Programming which allows preventing the functions of a program to access
directly the internal representation of a class type.

The public Members

 A public member is accessible from anywhere outside the class but


within a program. You can set and get the value of public variables
without any member function as shown in the following example –
C++ CLASS ACCESS MODIFIERS
#include <iostream> void Line::setLength( double len) {
length = len;
using namespace std; }
class Line { // Main function for the program
int main() {
public: Line line; // Create an object line
double length; // set line length
line.setLength(6.0);
void setLength( double len ); cout << "Length of line : " <<
line.getLength() <<endl;
double getLength( void ); // set line length without member function
}; line.length = 10.0; // OK: because length is
public
// Member functions definitions cout << "Length of line : " << line.length
double Line::getLength(void) { <<endl;
return 0;
return length ; }
}
The private Members

 A private member variable or function cannot be accessed, or


even viewed from outside the class.

 Only the class and friend functions can access private members.

 By default all the members of a class would be private, for


example in the following class width is a private member, which
means until you label a member, it will be assumed a private
member –
The private Members
 Example void Box::setWidth( double wid ) {
width = wid;
#include <iostream>
}
using namespace std;
class Box { // Main function for the program
int main() {
public:
Box box;
double length;
void setWidth( double wid ); // set box length without member function
box.length = 10.0; // OK: because length is public
double getWidth( void );
cout << "Length of box : " << box.length <<endl;
private:
double width; // set box width without member function
};
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
// Member functions definitions cout << "Width of box : " << box.getWidth()
double Box::getWidth(void) { <<endl;
return width ;
return 0;
} }
When the above code is compiled and executed, it produces the following result -
Length of box : 10
Width of box : 10
The protected Members
 A protected member variable or function is very similar to a private
member but it provided one additional benefit that they can be
accessed in child classes which are called derived classes.

 The derived one child class SmallBox from a parent class


Box. Following example is similar to above example and here width
member will be accessible by any member function of its derived
class SmallBox.
The protected Members
#include <iostream> void SmallBox::setSmallWidth( double
using namespace std; wid ) {
width = wid;
class Box {
}
protected:
double width;
}; // Main function for the program
int main() {
class SmallBox:Box { // SmallBox is the derived
class. SmallBox box;
public:
void setSmallWidth( double wid ); // set box width using member function
double getSmallWidth( void );
};
box.setSmallWidth(5.0);
cout << "Width of box : "<<
// Member functions of child class box.getSmallWidth() << endl;
double SmallBox::getSmallWidth(void) {
return width ;
} return 0;
}
When the above code is compiled and executed, it produces the following result -
Width of box : 5
C++ INHERITANCE
 Inheritance is the capability of one class to acquire properties and
characteristics from another class.

 The class whose properties are inherited by other class is called the Parent
or Base or Super class.

 And, the class which inherits properties of other class is called Child or
Derived or Sub class.

 Inheritance makes the code reusable.

 When we inherit an existing class, all its methods and fields become
available in the new class, hence code is reused.

 NOTE : All members of a class except Private, are inherited


C++ INHERITANCE
Basic Syntax of Inheritance
class derived-class: access-specifier base-class
 While defining a subclass like this, the super class/base-class
must be already defined or atleast declared before the
subclass/ derived-class declaration.
 Access Mode is used to specify, the mode in which the
properties of superclass will be inherited into subclass, public,
private or protected.
 Depending on Access modifier used while inheritance, the
availability of class members of Super class in the sub class
changes.
 It can either be private, protected or public.
C++ INHERITANCE
1) Public Inheritance
 This is the most used inheritance mode. In this the protected member of super class
becomes protected members of sub class and public becomes public.
Syntax
class Subclass : public Superclass
2) Private Inheritance
In private mode, the protected and public members of super class become private
members of derived class.
Syntax
class Subclass : Superclass // By default its private inheritance
3) Protected Inheritance
 In protected mode, the public and protected members of Super class becomes
protected members of Sub class.
Syntax
class subclass : protected Superclass
Example of Inheritance
class Animal
{ public:
int legs = 4;
};
class Dog : public Animal//creating derived class Dog
{ public:
int tail = 1;
};

int main()
{
Dog d;// Object of class dog d created
cout << d.legs;
cout << d.tail;
}
Types of Inheritance
 In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
 In this type of inheritance one derived class inherits from only one base class.
 It is the most simplest form of Inheritance.
2. Multiple Inheritance
 a single derived class may inherit from two or more than two base classes
3. Hierarchical Inheritance
 multiple derived classes inherits from a single base class
4. Multilevel Inheritance
 the derived class inherits from a class, which in turn inherits from some other class.
 The Super class for one, is sub class for the other.
5. Hybrid Inheritance (also known as Virtual Inheritance)
 Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance
Example // Derived class
#include <iostream>
class Rectangle: public Shape {
using namespace std;
public:
// Base class
int getArea() {
class Shape {
return (width * height);
public:
void setWidth(int w) { }

width = w; };
} int main(void) {
void setHeight(int h) { Rectangle Rect;
height = h; Rect.setWidth(5);
} Rect.setHeight(7);
protected: // Print the area of the object.
int width; cout << "Total area: " << Rect.getArea() << endl;
int height; return 0;
};
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Multiple Inheritance

 A C++ class can inherit members from more than one class and here is
the extended syntax –

 Syntax

class derived-class: access baseA, access baseB....

 Where access is one of public, protected, or private and would be given for
every base class and they will be separated by comma as shown above.
Example: Multiple Inheritance
#include <iostream> // Base class PaintCost int main(void) {
using namespace std; class PaintCost { Rectangle Rect;
// Base class Shape public:
int getCost(int area) { int area;
class Shape {
return area * 70; Rect.setWidth(5);
public:
}
void setWidth(int w) { }; Rect.setHeight(7);
width = w; // Derived class area = Rect.getArea();
} class Rectangle: public Shape,
public PaintCost { // Print the area of the object.
void setHeight(int h) {
public: cout << "Total area: " <<
height = h;
int getArea() {
} return (width * height); Rect.getArea() << endl;
protected: } // Print the total cost of painting
int width;
};
cout << "Total paint cost: $" <<
int height;
Rect.getCost(area) << endl;
};
return 0;
}
Total area: 35, Total paint cost: $2450
POLYMORPHISM IN C++
 The word polymorphism means having many forms.

 Polymorphism is generally having different classes with a function of the same


name, and even the same parameters, but with different implementations.

 Typically, polymorphism occurs when there is a hierarchy of classes and they


are related by inheritance.

 C++ polymorphism means that a call to a member function will cause a


different function to be executed depending on the type of object that invokes
the function.

 In inheritance, polymorphism is done, by method overriding, when both super


and sub class have member function with same declaration but different
definition.
POLYMORPHISM IN C++
 If we inherit a class into the derived class and provide a definition for one of
the base class's function again inside the derived class, then that function is
said to be overridden, and this mechanism is called Function Overriding

 A virtual function is a function in a base class that is declared using the


keyword virtual.

 Defining in a base class a virtual function, with another version in a derived


class, signals to the compiler that we don't want static linkage for this
function

 What we do want is the selection of the function to be called at any given


point in the program to be based on the kind of object for which it is called.

 This sort of operation is referred to as dynamic linkage, or late binding.


Example of Function Overriding
class Base
{
public:
void show() NB function show() is overridden in
the derived class. Now let us study
{
how these overridden functions are
cout << "Base class"; called in main() function.
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
Example of polymorphism
#include <iostream> public: // Main function for the program
using namespace std; Rectangle( int a = 0, int b = int main() {
0):Shape(a, b) { }
class Shape { Shape *shape;
int area () {
protected: Rectangle rec(10,7); Triangle
cout << "Rectangle class area :" tri(10,5);
int width, height; <<endl;
// store the address of Rectangle
public: return (width * height);
shape = &rec;
Shape( int a = 0, int b = 0) { }
// call rectangle area.
width = a; };
shape->area();
height = b; class Triangle: public Shape {
// store the address of Triangle
} public:
shape = &tri;
virtual int area() { Triangle( int a = 0, int b =
0):Shape(a, b) { } // call triangle area.
cout << "Parent class area :"
<<endl; int area () { shape->area();
return 0; cout << "Triangle class area :" return 0;
} <<endl; }
};
return (width * height / 2);

class Rectangle: public Shape { }};


C++ FRIEND FUNCTIONS

 A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class.
 Even though the prototypes for friend functions appear in the class definition, friends
are not member functions.
 A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
 To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows –
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
void printWidth( Box box ) {
Example
/* Because printWidth() is a friend of Box, it can
#include <iostream>
directly access any member of this class */
using namespace std;
cout << "Width of box : " << box.width <<endl;
class Box {
}
double width;
// Main function for the program
public:
int main() {
friend void printWidth( Box box );
Box box;
void setWidth( double wid );
// set box width without member function
};
box.setWidth(10.0);
// Member function definition
void Box::setWidth( double wid ) {
// Use friend function to print the wdith.
width = wid;
printWidth( box );
}
return 0;
// Note: printWidth() is not a member function of any
class. }
C++ FUNCTIONS

 A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main function.

 A function is known with various names like a method or a sub-routine or a procedure


etc.

 Functions are used to provide modularity to a program. Creating an application using


function makes it easier to understand, edit, check errors etc.

Syntax of Function/Defining a Function

return-type function-name (parameters)

// function-body

}
C++ FUNCTIONS

 return-type : suggests what the function will return. It can be int, char, some pointer or
even a class object.

 There can be functions which does not return anything, they are mentioned with void.

 Function Name : is the name of the function, using the function name it is called.

 Parameters : are variables to hold values of arguments passed while function is called.
When a function is invoked, you pass a value to the parameter. This value is referred to
as actual parameter or argument.

 A function may or may not contain parameter list.

 Function body : is the part where the code statements are written.
Declaring, Defining and Calling Function
 Function declaration, is done to tell the compiler about the existence of the function.
 Function's return type, its name & parameter list is mentioned. Function body is
written in its definition.

#include <iostream>
using namespace std;
int sum (int x, int y); //declaring function or function prototype
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
} int sum (int x, int y) //defining function
{
return (X + y);
Function to add two numbers
 // program to add two numbers using a function
 #include <iostream>
 using namespace std;
 // declaring a function
 int add(int a, int b) {
 return (a + b);
 }
 int main() {
 int sum; In the above program, the add() function is used to find
the sum of two numbers.
 // calling the function and storing
 // the returned value in sum We pass two int literals 100 and 78 while calling the
 function.
sum = add(100, 78);// function call
 cout << "100 + 78 = " << sum << endl; We store the returned value of the function in the
 return 0; variable sum, and then we print it.
 }
Notice that sum is a variable of int type. This is because
the return value of add() is of int type.
Function Types
 Two types:
 Library Functions
 User Defined functions

Library Functions
 Programmers can use library functions by invoking the functions directly; they don't need to write the functions
themselves.
 Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
 In order to use library functions, we usually need to include the header file in which these library functions are
defined.
 //C++ Program to Find the Square Root of a Number
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file
#include <iostream>
cmath.
#include <cmath>
using namespace std;
int main() {
In this program, the sqrt() library function is used
double number, squareRoot; to calculate the square root of a number.
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
The function declaration of sqrt() is defined in the
cout << "Square root of " << number << " = " << cmath header file. That's why we need to use the
squareRoot; code #include <cmath> to use the sqrt()
return 0;
}
function.

Output:
Square root of 25 = 5
Calling Function
 To use a function, it must be called or invoked.

 When a program calls a function, program control is transferred to the called


function

 A called function performs defined task and when it’s return statement is
executed or when its function-ending closing brace is reached, it returns
program control back to the main function

 To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned
value.

 Functions are called by their names.


Calling Function

 But for functions with arguments, we have two ways to call them,

 1. Call by Value

This method copies the actual value of an argument into the formal parameter
of the function. In this case, changes made to the parameter inside the function
have no effect on the argument.

 2. Call by Reference

 This method copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual argument used
in the call.

 This means that changes made to the parameter affect the argument.
Call by Value
 The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function.
 In this case, changes made to the parameter inside the function have no effect on
the argument.
 Hence, the original values are unchanged only the parameters inside function
changes.
 This means that when calling a function with parameters, what we have passed to
the function were copies of their values but never the variables themselves.

 For example, suppose that we called our first function addition using the following
code:
int x=5, y=3, z;
z = addition ( x , y );
Call by Value
 What we did in this case was to call to function addition passing the values of x and
y, i.e. 5 and 3 respectively, but not the variables x and y themselves.
 This way, when the function addition is called, the value of its local variables a and
b become 5 and 3 respectively,
 but any modification to either a or b within the function addition will not have any
effect in the values of x and y
 outside it, because variables x and y were not themselves passed to the function,
but only copies of their values at
 the moment the function was called.
 By default, C++ programming uses call by value to pass arguments.

 This means that when the function is called a copy of the value of the
actual parameter used in the call is passed across to the memory space of
the function. Anything that happens inside the function to this copy
of the value of the parameter cannot affect the original actual
parameter
Call by Value
 But we can change this program to modify the original x, by making the function
calc() return a value, and storing that value in x.

int calc(int x);


int main()
{
int x = 10;
x = calc(x);
cout<< x;
}
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20
Call by reference
 The declaration of the duplicate type of each
// passing parameters by reference
parameter was followed by an ampersand sign (&).
#include <iostream>
using namespace std;  This ampersand is what specifies that their
void duplicate (int& a, int& b, int& c)
corresponding arguments are to be passed by
reference instead of by value.
{
a*=2; b*=2; c*=2;  When a variable is passed by reference we are not
} passing a copy of its value, but we are passing the
int main ()
variable itself to the function and
{  Any modification that we do to the local variables
int x=1, y=3, z=7; will have an effect in their counterpart variables
duplicate (x, y, z); passed as arguments in the call to the function.
cout << "x=" << x << ", y=" << y << ",
z=" << z <<endl;  In this we pass the address of the variable as
return 0; arguments.
}  In this case the formal parameter can be taken as a
Output x=2, y=6, z=14 reference or a pointer, in both the case they will
change the values of the original variable.
Call by reference
 To explain it in another way, we associate a, b and c with the arguments
passed on the function call (x, y and z) and

 Any change that we do on a within the function will affect the value of x
outside it. Any change that we do on b will affect y, and the same with c
and z.
return 0;
Example
}
#include <iostream>
// function returning the max between two
using namespace std;
numbers
int max(int num1, int num2) {
// function declaration
// local variable declaration
int max(int num1, int num2);
int result;

int main () {
if (num1 > num2)
// local variable declaration:
result = num1;
int a = 100;
else
int b = 200;
result = num2;
int ret;

return result;
// calling a function to get max value.
}
ret = max(a, b);
cout << "Max value is : " << ret <<
endl;
Functions Overloading.
 In C++ two different functions can have the same name and their parameter
types or number are different.
 That means that you can give the same name to more than one function and have
either a different number of parameters or different types in their parameters.

For example:
// overloaded function int main ()
#include <iostream> {
using namespace std; int x=5,y=2;
int compute (int a, int b) float n=5.0,m=2.0;
{ cout << compute (x,y);
return (a*b); cout << "\n";
} cout << compute (n,m);
float compute (float a, float cout << "\n";
b) return 0;
{ }
return (a/b);
}
Functions Overloading.

 Definition of two functions with the same name, Compute, but one of
them accepts two parameters of type int and the other one accepts them
of type float.

 First prototype is called of type int; This function returns the result of
multiplying both parameters.

 While the second call passes two arguments of type float, so the function
with the second prototype is called.
Arrays in C++
 An array is a data structure which allows a collective name to be given to a
group of elements which all have the same type.
 An individual element of an array is identified by its own unique index (or
subscript).
 C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.
 An array can be thought of as a collection of numbered boxes each containing
one data item.
 The number associated with the box is the index of the item.
 The index must be an integer and indicates the position of the element in the
array.
 Thus the elements of an array are ordered by the index.
Declaration of Arrays
 To declare an array in C++, the programmer specifies the type of the elements
and the number of elements required by an array as follows -
Type arrayName [ arraySize ];
 This is called a single-dimension array.
 The arraySize must be an integer constant greater than zero and type can be
any valid C++ data type.
 For example data on the average temperature over the year in Britain for each
of the last 100 years could be stored in an array declared as follows:
float annual_temp[100];
 This declaration will cause the compiler to allocate space for 100 consecutive
float variables in memory.
 The number of elements in an array must be fixed at compile time.
 It is best to make the array size a constant and then, if required, the program
can be changed to handle a different size of array by changing the value of the
constant,
Initialisation of arrays
 An array can be initialised in a similar manner as variables.
 The initial values are given as a list enclosed in curly brackets.
 For example initialising an array to hold the first few prime numbers could be
written as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

int primes[] = {1, 2, 3, 5, 7, 11, 13};


 Note that the array has not been given a size, the compiler will make it large
enough to hold the number of elements in the list.
 In this case primes would be allocated space for seven elements.
 If the array is given a size then this size must be greater than or equal to the
number of elements in the initialisation list. For example:
int primes[10] = {1, 2, 3, 5, 7};
 The compiler would reserve space for a ten element array but would only initialise
the first five elements.
Accessing Array Elements
 Given the declaration float annual_temp[100]; of a 100 element array the compiler
reserves space for 100 consecutive floating point values and accesses these values using
an index/subscript that takes values from 0 to 99.
 The first element in an array in C++ always has the index 0, and if the array has n
elements the last element will have the index n-1.
 An array element is accessed by writing the identifier of the array followed by the
subscript/index in square brackets.
 Thus to set the 15th element of the array above to 1.5 the following assignment is used:
annual_temp[14] = 1.5;
 An element is accessed by indexing the array name.
 This is done by placing the index of the element within square brackets after the name of
the array.
 For example -
double salary = balance[9];
 The above statement will take 10th element from the array and assign the value to salary
variable.
Example of Declaration, assignment and accessing
arrays -
#include <iostream> cout << "Element" << setw( 13 ) << "Value"
<< endl;
using namespace std;

// output each array element's value


#include <iomanip>
using std::setw;
for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ]
int main () { << endl;
}
int n[ 10 ]; // n is an array of 10 integers
return 0;
// 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
}
C++ MULTI-DIMENSIONAL ARRAYS; Two-Dimensional Arrays

 The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows -
type arrayName [ x ][ y ];
 two-dimensional array can be think as a table, which will have x number of rows and y
number of columns.
 A 2-dimensional array a, which contains three rows and four columns can be shown as
below –

 Thus, every element in array a is identified by an element name of the form a[ i ][ j ],


where a is the name of the array, and i and j are the subscripts that uniquely identify
each element in a.
Initializing & Accessing Two-Dimensional
Arrays
Initializing Two-Dimensional Arrays
 Multidimensional arrays may be initialized by specifying bracketed values for each row.
 Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
 The nested braces, which indicate the intended row, are optional. The following initialization
is equivalent to previous example -
 int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
 An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the
 array. For example - int val = a[2][3];
 The above statement will take 4th element from the 3rd row of the array. You can verify it in
the above diagram.
Example
#include <iostream>
using namespace std; When the above code is compiled and executed,
it produces the following result -
int main () {
a[0][0]: 0
// an array with 5 rows and 2 columns.
a[0][1]: 0
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},
{4,8}}; a[1][0]: 1
// output each array element's value a[1][1]: 2
a[2][0]: 2
for ( int i = 0; i < 5; i++ )
a[2][1]: 4
for ( int j = 0; j < 2; j++ ) {
a[3][0]: 3
a[3][1]: 6
cout << "a[" << i << "][" << j << "]: ";
a[4][0]: 4
cout << a[i][j]<< endl;
a[4][1]: 8
}
As explained above, you can have arrays with
return 0; any number of dimensions, although it is likely
that most of the arrays you create will be of one
}
or two dimensions.
Character Sequences
 The C++ Standard Library implements a powerful string class, which is very useful to
handle and manipulate strings of characters.
 Strings are in fact sequences of characters, we can represent them also as plain arrays
of char elements.
 For example, the following array:
 char jenny [20];
 Is an array that can store up to 20 elements of type char. It can be represented as:
Character Sequences
 The array of characters can store shorter sequences than its total length, a special
character is used to signal the end of the valid sequence: the null character, whose
literal constant can be written as '\0' (backslash, zero).

 null character ('\0') has been included in order to indicate the end of the sequence.

 The panels in gray color represent char elements with undetermined values.
Initialization of null-terminated character sequences
 Declaration of an array of 6 elements of type char initialized with the characters
that form the word "Hello" plus a null character '\0' at the end.
char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
using string literals.
 Double quoted strings (") are literal constants whose type is in fact a null-
terminated array of characters.
 So string literals enclosed between double quotes always have a null character ('\
0') automatically appended at the end.
 Therefore we can initialize the array of char elements called myword with a null-
terminated sequence of characters by either one of these two methods:
 char myword [] = { 'H', 'e', 'l', 'l', 'o', '\0' };
 char myword [] = "Hello";
Initialization of null-terminated character sequences
 Example
 // null-terminated sequences of characters
#include <iostream>
using namespace std;
int main ()
{//initialization with string literal constants
//implicitly defined by the length of the literal constant
char question[] = "Please, enter your first name: ";
char greeting[] = "Hello,? ";
//explicitly defined by the size 80
char yourname [80];
cout << question;
cin >> yourname;
cout << greeting << yourname << "!";
return 0;
}
Pointer
 Pointer is the variable that stores the reference to another variable.
 The address that locates a variable within memory is what we call a
reference to that variable.
 This reference to a variable can be obtained by preceding the identifier of
a variable with an ampersand sign (&), known as reference operator, and
which can be literally translated as "address of".
For example:
 atieno = &musembi;
 This assigns to atieno the address of variable musembi, since when
 The name of the variable musembi is preceded with the reference
operator (&)
 Thus we are no longer talking about the content of the variable itself, but
about its reference (i.e.,its address in memory).
 Pointers are said to "point to" the variable whose reference they store.
Pointer
 A pointer we can directly access the value stored in the variable which it
points to.
 To do this, we simply have to precede the pointer's identifier with an asterisk
(*),
 which acts as dereference operator and that can be literally translated to
"value pointed by".
 Therefore, following Examples read:
 atieno = * musembi;
 Its read as: " atieno equal to value pointed by musembi “
 atieno = musembi;// atieno equal to musembi
 atieno = * musembi; // atieno equal to value pointed by musembi
NB the difference between the reference and dereference operators:
 & is the reference operator and can be read as "address of"
 * is the dereference operator and can be read as "value pointed by"
Declaring variables of pointer
types
 The declaration of pointers follows this format:

type * name;

 where type is the data type of the value that the pointer is intended to
point to.

 This type is not the type of the pointer itself! but the type of the data the
pointer points to. For example:

 int * number;

 char * character;

 float * greatnumber;
Declaring variables of pointer
types
Example
// more pointers
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue


p2 = &secondvalue; // p2 = address of secondvalue
cout << "firstvalue memory address is " << &firstvalue << endl;
cout << "secondvalue memory address is " << &secondvalue << endl;
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
Pointer initialization
 When declaring pointers we may want to explicitly specify which variable we want
them to point to:

 int number;

 int *tommy = &number;

 The behavior of this code is equivalent to:

 int number;

 int *tommy;

 tommy = &number;

 When a pointer initialization takes place we are always assigning the reference value to
where the pointer points (tommy),

 declaring a pointer, the asterisk (*) indicates only that it is a pointer, it is not the
dereference operator (although both use the same sign: *).
Dynamic memory allocation
 Dynamic memory allocation is allocation of memory during runtime.

 Memory in your C++ program is divided into two parts -

 The stack - All variables declared inside the function will take up memory from the
stack.

 The heap - This is unused memory of the program and can be used to allocate the
memory dynamically when program runs.

 Dynamic memory allocation allows us to assign memory during the execution of the
program (runtime) using any variable or constant value as its size.

 Memory is allocated at run time within the heap for the variable of a given type
using a special operator in C++ which returns the address of the space allocated.
Dynamic memory allocation
 This operator is called new operator.

 If you are not in need of dynamically allocated memory anymore, you can use
delete operator, which de- allocates memory that was previously allocated by
new operator.

 syntax to use new operator to allocate memory dynamically for any data-type.

 new data-type;

 pvalue = new double; // Request memory for the variable

 free up the memory that it occupies in the free store with the ‘delete’ operator
as follows -

 delete pvalue; // Release memory pointed to by pvalue


New and delete operator
#include <iostream>
using namespace std;

int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}
Constructors and destructors

 A constructor is a special member function whose task is to initialize the


objects of its class.

 It is special because its name is same as the class name.

 Syntax: class_name(void);

 The constructor is invoked whenever an object of its associated class is


created.

 It is called constructor because it construct the value data members of the


class.

 A constructor without parameters is referred to as a default constructor.


Constructors and destructors

 The constructor functions have some special characteristics.

 They should be declared in the public section.

 They are invoked automatically when the objects are created.

 They do not have return types, not even void and therefore, they cannot return values.

 They cannot be inherited, though a derived class can call the base class constructor.

 Objects that were created by a constructor must also be cleaned up in an orderly


manner.

 Objects are cleaned up by a special method called a destructor, whose name is


made up of the class name preceded by ~ (tilde).

 Syntax: ∼class_name(void);
Example
// example on constructors and destructors *height = b;
#include <iostream> }
using namespace std;
CRectangle::~CRectangle ()
class CRectangle {
{ delete width;
int *width, *height; delete height;
public: }
CRectangle (int,int); //constructors
~CRectangle (); // destructors int main ()
int area () {
{return (*width * *height);} CRectangle rect (3,4), rectb (5,6);
}; cout << "rect area: " << rect.area() <<
endl;
CRectangle::CRectangle (int a, int b)
cout << "rectb area: " << rectb.area() <<
{
endl;
width = new int;
return 0;
height = new int;
}
*width = a;

You might also like