SCS202_OBJECT ORIENTED PROGRAMMING
SCS202_OBJECT ORIENTED PROGRAMMING
PROGRAMMING
SCS202
Lecturer’s Name: Kirema Mutembei
[email protected]
Basic Object Oriented concept
Some Characteristics of Object Oriented Programming
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.
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 user needs to know the external interfaces only to make use of an object
Creating a program
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
// 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;
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
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
+= 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.
Syntax
If (boolean_expression)
{
/* statement(s) will execute if
the boolean expression is true */
}
if - else statement
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;
This chain is evaluated from the top and, if a particular if-conditional is TRUE,
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 */
}
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.
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.
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 */
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
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
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.
}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
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
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 –
Only the class and friend functions can access private members.
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.
When we inherit an existing class, all its methods and fields become
available in the new class, hence code is reused.
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
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.
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.
// 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.
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.
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.
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.
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};
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 –
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;
int number;
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.
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;
free up the memory that it occupies in the free store with the ‘delete’ operator
as follows -
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
return 0;
}
Constructors and destructors
Syntax: class_name(void);
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.
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;