C++ Object Oriented Progamming
C++ Object Oriented Progamming
KABARAK UNIVERSITY
STUDENT MANUAL
For Lisalitsa 1
1
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
CONTENTS PAGE
Object
Classes
Inheritance
Polymorphism
Dynamic binding
Message passing
Tokens
Operators
Control Structure
Functions
Array
Constructors
Inheritance
Polymorphism
Comparison Of C++ And Java
For Lisalitsa 2
2
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Prepared by
Mr .Masese
In the procedure oriented approach the problem is viewed as a sequence of things to be done
such as reading, calculating and printing, a number of functions are written to accomplish these
tasks. The primary focus is the functions
Procedure oriented programming basically consist of writing a list of instructions (actions) for
the computer to follow, the organizing these instructions into groups known as functions
We use a flowchart to organize these actions and represent the flow of control from one action to
another.
In a multi function program, many important data items are placed as global so that they may be
accessed by all the functions, each function may have its own local data
Main program
Function 1
Def:
For Lisalitsa 3
3
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
The major aim of object oriented programming is to remove some fall backs in the procedure
oriented programming .
Object oriented programming treats data as critical element in the program development, it ties
data more closely to the functions that that operate it, it allows decomposition of a problem into
number of entities called objects and then build data and functions around these objects
Its features
Data structures are designed such that they characterize the objects
Functions that operate on the data of object are tied together in the data structure
For Lisalitsa 4
4
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Include:
1. Object
2. Classes
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
Object
Object are the basic run time entities in an object oriented system,they may represent a
person , place, table of data that the program has to handle
They may also represent user defined data such as vector, time and list, when a program is
executed the objects interact by sending message to one another.
Example
If “customer” and “account” are two object in a program then the customer object may send a
message to the account object requesting for the bank balance,each object contains data and
code to manipulate the data
Object student
: person ………object
Name……………data
Basic pay……….data
Salary……….function()
Tax………….function()
For Lisalitsa 5
5
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Classes
Is a user defined which defines a collection of similar objects ,the entire set of data and code
of an objects can be made a user defined data type with the help of a class.
Objects are variables of the type class, once a class has been defined, we can create any number
of objects belonging to that class.
Each object is associated with the data of type class with which they are created
Syntax
Fruit mango
class classname
instructions
}
The wrapping up of data and functions into single unit is called class is known as
encapsulation. Data encapsulation is the most striking feature of a class.
The data is not accessible to the outside world and only those functions which are wrapped in the
class can access it.
These functions provide the interface between the object and the program, this insulation of the
data from direct access by the program is called data hiding or information hiding.
ABSTRACTION refers to the act of representing essential features without including the
background details, classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost and functions operate on these attributes
The attributes are sometimes called as data members because they hold information; the
functions that operate on these are sometimes called methods or member functions
For Lisalitsa 6
6
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Inheritance
Is the process by which objects acquire the properties of objects of another class, it supports the
concept of hierarchical classification.
In oop , the concept of inheritance provide the idea of reusability, this means that we can add
additional feature to an existing class with out modifying it,
This is possible by deriving a new class from the existing one, the class will have combined
feature of both the classes hence the classes are reusable.
parent
Polymorphism
This is the ability to take more than one form, an operation may exhibit different behaviors in
different instances, and the behavior depends upon the type of data used in the operation.
Polymorphism plays important role in allowing objects having different internal structures to
share the same external interface, this means that a general class of operations may be accessed
in the same manner even through specific actions associated with each operation may differ
For Lisalitsa 7
7
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
shape
circle square
Dynamic binding
Refers to the linking of a procedure call to the node to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure is not known until the
time of the call at run time.
Message passing
An object oriented program consist of a set of objects that communicate with each other, the
process of programming in an object oriented language therefore involves the following basic
steps:
Objects communicate with one another by sending and receiving information much the same
way as people pass message to one another.
Message passing involves specifying the name of the object, the name of the function
(message) and the information to be sent
Example employee.salary(name);
For Lisalitsa 8
8
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Through inheritance we can eliminate redundant code and extend the use of existing
The principle of data hiding helps the programmer to build secure program that cannot be
invaded by code in other parts of the program
Message passing techniques for communication between objects makes the interface
descriptions with external system much simple
Return 0; }
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;}
where
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor
int main ()
For Lisalitsa 9
9
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
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.
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.
Example 2
#include <iostreaam>
Int main()
float number1,number2,sum,average;
cin>> number1;
cin>>number2;
average = sum/2;
return 0;
10 Lisalitsa 10
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Tokens
They are smallest individual units in a program ,they are divided into the following
1. Keywords
2. Identifiers
3. Constants
4. String
5. operators
Identifiers
they can be defined as the name of the variable and some other program elements using the
combination of the following characters
Numerals :0…..9
11 Lisalitsa 11
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Underscore : _
In object oriented programming, upper case and lower case are distinct , a variable should not
begin with a digit.
Keywords
Key words are also identifiers but cannot be user defined since they are used by the
language ,the following words are reserved for use as key words
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do,
double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline,
int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast,
return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try,
typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while
Constants
This are the values which are set and will remain unchanged through out the program
Types of constants
String constant
Numeric constants
Character constant
Examples
Numeric constants: there are four types of numeric constants: integer constant, floating point
constant, hex constant, octal constant
12 Lisalitsa 12
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Declaration
Integer constant integer constant do not contain decimal points, the variable can be declared as
integer in the following ways
int x,y;
short integer : used to declare the short integer data whose maximum size is between -32,768 to
32,767
long integer : used to declare the short integer data whose maximum size is between -
2,147,483,648 to 2,147,483,647
Literals
Literals are used to express particular values within the source code of a program. We have
already used these previously to give concrete values to variables or to express messages we
wanted our programs to print out, for example, when we wrote:
a = 5;
Assignment (=)
Arithmetic operators ( +, -, *, /, % )
13 Lisalitsa 13
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
/ division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with their
respective mathematical operators. The only one that you might not be so used to see may be
modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the
remainder of a division of two values.
The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one
operand, located at its right, and the only thing that it does is to inverse the value of it, producing
false if its operand is true and true if its operand is false. Basically, it returns the opposite
Boolean value of evaluating its operand. For example:
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 following panel
shows the result of operator && evaluating the expression a && b:
&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
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. Here are the possible results of a || b:
14 Lisalitsa 14
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false false
For example:
Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and a
different one if the EXPRESSION is evaluated as false. Its format is:
If condition is true the expression will return result1, if it is not it will return result2.
// conditional operator 7
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
15 Lisalitsa 15
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus
the first value specified after the question mark was discarded in favor of the second value (the
one after the colon) which was b, with a value of 7.
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.
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.
Bitwise operators modify variables considering the bit patterns that represent the values they
store.
operato
asm equivalent description
r
& AND Bitwise AND
| OR Bitwise Inclusive OR
^ XOR Bitwise Exclusive OR
~ NOT Unary complement (bit inversion)
<< SHL Shift Left
16 Lisalitsa 16
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Type casting operators allow you to convert a datum of a given type to another. There are several
ways to do this in C++. The simplest one, which has been inherited from the C language, is to
precede the expression to be converted by the new type enclosed between parentheses (()):
int i;
float f = 3.14;
i = (int) f;
The previous code converts the float number 3.14 to an integer value (3), the remainder is lost.
Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the
functional notation: preceding the expression to be converted by the type and enclosing the
expression between parentheses:
i = int ( f );
sizeof()
This operator accepts one parameter, which can be either a type or a variable itself and returns
the size in bytes of that type or object:
a = sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.
The value returned by sizeof is a constant, so it is always determined before program execution.
Other operators
Later in these tutorials, we will see a few more operators, like the ones referring to pointers or
the specifics for object-oriented programming. Each one is treated in its respective section.
Precedence of operators
When writing complex expressions with several operands, we may have some doubts about
which operand is evaluated first and which later. For example, in this expression:
17 Lisalitsa 17
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
a=5+7%2
a = 5 + (7 % 2) // with a result of 6, or
a = (5 + 7) % 2 // with a result of 0
The correct answer is the first of the two expressions, with a result of 6. There is an established
order with the priority of each operator, and not only the arithmetic ones (those whose preference
come from mathematics) but for all the operators which can appear in C++. From greatest to
lowest priority, the priority order is as follows:
18 Lisalitsa 18
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Left-to-
10 == != equality
right
Left-to-
11 & bitwise AND
right
Left-to-
12 ^ bitwise XOR
right
Left-to-
13 | bitwise OR
right
Left-to-
14 && logical AND
right
Left-to-
15 || logical OR
right
Right-to-
16 ?: conditional
left
Right-to-
17 = *= /= %= += -= >>= <<= &= ^= |= assignment
left
Left-to-
18 , comma
right
Grouping defines the precedence order in which operators are evaluated in the case that there are
several operators of the same level in an expression
Character and string literals have certain peculiarities, like the escape codes. These are special
characters that are difficult or impossible to express otherwise in the source code of a program,
like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of
some of such escape codes
n newline
\r carriage return
\t tab
\v vertical tab
19 Lisalitsa 19
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
20 Lisalitsa 20
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
2 or 4
wchar_t Wide character. 1 wide character
bytes
enumerated data type
is a user defined type which provides a way for attaching names to numbers, thereby increasing
comprehensibity of the code.
The enum keyword automatically enumerates a list of words by assigning them values 0.1.2, and
so on
Example
Enum shape{circle,square,triangle};
Enum color{red,blue,yellow}
Enum position{off,on}
Control structure
They are mainly used to control the flow of the program during execution
Types
Conditional statements
if statement
if else statement
loop statement
for loop
While loop
Do while loop
Break statement
Continue statement
21 Lisalitsa 21
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
goto statement
CONDITIONAL STATEMENT
If statement
Is used to express conditional expressions, if the given condition is true then it will execute the
statement otherwise it will execute the optional statement
The braces { and } are used to group declaration and statement into a compound statement or a
block, this compound statement or block are always considered as single statement
Syntax
If(expressions)
Statement;
Statement;
Example
#include <iostream.h>
main(void)
int a=20;
int b =10;
if (a > b )
IF ELSE STATEMENT
The program will execute the else part after the if part has failed to meet the requirement.
Syntax
22 Lisalitsa 22
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
If(expression)
Statement2
Example
#include <iostream.h>
void main(void)
float x,y;
if (x > y)
else
Example 2
// program to display the name of the day in a week ,depending upon the number which is
entered by the keyboard .
#include <iostream.h>
int day;
23 Lisalitsa 23
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
if (day == 1)
else if (day == 2)
else if (day==6)
else
SWITCH STATEMENT
syntax
switch(expression)
case1:
…….. //statement
24 Lisalitsa 24
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
break
case2:
……// statement
break
….
default
…..// statements
break
example
Switch (input_ch) {
case ‘A’:
case ‘a’ :
Cout <<”A”;
break;
case ‘E’ :
case ‘e’ :
break;
25 Lisalitsa 25
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
case ‘I’ :
case ‘i’ :
break;
case ‘O’ :
case ‘o’ :
break;
case ‘U’ :
case ‘u’ :
break;
default :
break; }
// program to display the name of the day in a week ,depending upon the number which is
entered by the keyboard using switch statement .
#include <iostream.h>
int day;
switch(day)
case 1 :
26 Lisalitsa 26
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
break;
case 2 :
break;
case 3 :
break;
case 4 :
break;
case 5 :
case 6 :
case 7:
LOOP STATEMENT
FOR LOOP
its main function is to repeat statement while condition remains true, like the while loop. But in
addition, the for loop provides specific locations to contain an initialization statement and an
27 Lisalitsa 27
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
increase statement. So this loop is specially designed to perform a repetitive action with a
counter which is initialized and increased on each iteration.
Syntax
Where:
Example
void main(void) {
While loop
Is used when we are not certain that the loop will be executed , after checking the initial
condition is true or false and finding it to be true.
28 Lisalitsa 28
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Syntax
While (condition)
Statement 1;
Statement 2;
Example
void main(void)
sum + =digit;
digit ++;
Do while
Is a repetitive loop can be used as it enters into the loop at least once and then checks whether
the given condition is true or false, as long as condition is true the loop operations is true or false
As long as the case of a while loop operations or statements will be repeated again and again.
Syntax
Expression_1
do{
29 Lisalitsa 29
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
statement _1
statement_2
-----
----
Expression _2
While(expression_3);
Example
void main(void)
int max,sum,digit;
digit =2;
do
Break statement
30 Lisalitsa 30
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Used to terminate the control from the loop statement of the case – switch structure.the break
statement is normally used in the switch case loop and in each case condition.
Continue statement
Used to repeat the same operation once again even if it checks the error.
The continue statement is used for the inverse operations of the break statement
Example
void main(void)
I =0;
while (i<=10)
if (value <=0){
continue;
i++
}}
Go to statement
Go to statement is used to alter the program execution sequence by transferring the control to
some other part of the program.
Example
void main()
31 Lisalitsa 31
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
start:
go to start;
#include<iostream.h>
void main()
int a,b;
if (a>b)
goto output1;
else
goto output2;
output1:
goto stop
output2:
stop;
32 Lisalitsa 32
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
FUNCTIONS
Is a procedure that returns a value , a complex program be decomposed into small or easily
manageable parts that are useful to read, write , debug and modify complex programs
syntax
Body of function
------
Return something
Example
#include <iostream.h>
Void main(void)
33 Lisalitsa 33
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
CALL BY REFERENCE
A function call mechanism that passes argument to a function by passing the address of the
argument
The control is transferred to the current object hence the current value will be reflected in the
memory
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
CALL BY VALUE
A function mechanism that passes argument to a function by passing a copy of the value of the
arguments
The control will be transferred from the main function to the value of the actual argument is
copied to the function.the values altered are not transferred back to the main function.
Example
#include<iostream.h>
void main(void) {
int x,y;
34 Lisalitsa 34
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
x= 100;
y = 20;
int temp;
temp = x;
x= y;
y = temp; }
INLINE FUNCTIONS
Inline function is a function specifier which specifies to the compiler that the function definition
should be substituted in all places where the function is called.
The compiler replaces the function with the corresponding function code
Syntax
Function body
35 Lisalitsa 35
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Example
#include<iostream.h>
return(x * y);
return(p /q);
int main()
float a =12.34;
float b = 19.08;
return 0;
36 Lisalitsa 36
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
ARRAY
Array is a collection of identical data objects which are stored in consecutive memory location
under a common heading or a variable name.
The individual values in an array are called elements, array elements are also variables, array
are set of values of the same type, which have a single name followed by an index.
ARRAY DECLARATION
Declaring the name and type of an array and setting the number of elements in the array is
known as dimensioning the array,
One must define the type of array ( eg integer ,float character type),
example
int mark[300];
char line[30];
array initialization
general format
example
program
# include<iostream.h>
37 Lisalitsa 37
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
void main(void)
int a[100];
int i,n;
cin>>n;
for(i =0;i<=n-1;i++)
cin>>a[i];
}}
POINTERS
Advantages of pointers
Allows to pass variable, array, functions strings and structures as function arguments
It allows to establish links between data elements for complex data structures such as
linked stacks, binary trees and graphs
38 Lisalitsa 38
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Pointer operator
Example
Int *ptr;
Declaration
Data_type *pointer_variable;
Where:
Data_type is a type of pointer variable such as integer, character and floating point number
variable
Pointer_variable is any valid identifier and should be proceeded by the pointer variable.
Example
Float *fpointer;
Char *mpoint1;
Address operator
Pointer expressions
Pointer assignment : a pointer is avariable data type and hence the general rule to assign its
value to the pointer is same as that of any other variable data type
Example
int x,y
prt1 = &x means the memory address of variable x is assigned to the pointer variable ptr1
y = *ptr1 means contents of the pointer variable ptr1 is assigned to the variable y not the memory
address.
39 Lisalitsa 39
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Prt1 = &x;
Example
// a program to assign the pointer variable to another pointer and display the contents of both
the pointer variable
#include<iostream.h>
main(void)
int x;
int *ptr1,ptr2;
x=10;
ptr1 = &x;
ptr2 = ptr1;
40 Lisalitsa 40
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
NOTE
Next you have a summary on how can you read some pointer and class operators (*, &, ., ->, [ ])
that appear in the previous example:
A class is a user defined data type which holds both data and functions, the internal data of a
class is called member data(data member) and the functions are called member functions, the
member functions mostly manipulate the internal data of a class
Structures contain one or more data items(members) which are grouped together as a single unit.
other hand is similar to a structure data type but it consists of only data elements but also
functions which operate on the data.
Secondly structure all the elements are public by default while the class it is private.
Syntax of a class
Class name
Private:
Data_type members
Implementation operations
41 Lisalitsa 41
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Public:
Data_type members
Implementation operations
Protected:
Data_type members
Implementation operations
};
Where:
Private: a member date can only accessed by the member function and friendly functions of
that class
Public: can be accessed by any function in the outside of t he class where it is declared
Protected: can only be accessed by the member functions and friendly of this class, also can be
accessed by the member functions and friendly derived from this class.
class student
private:
char sex;
float height;
public :
42 Lisalitsa 42
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
void disinfo(void);
void process();
};
Note: it is not a must you declare the class private for simple programs because it is private by
default.
A data or function member of a class construct is accessed using the .(period) operator
class_object.data_member
class_object.function_member
#include<iostream.h>
class sample {
private:
int x;
int y;
public :
void getinfo() {
void display() {
43 Lisalitsa 43
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
cout<<”mul=”<<mult()<<endl;
cout<<”div=”<<div()<<endl;
int sum() {
return( x+y);
int diff() {
return( x-y);
int mult() {
return( x*y);
int div() {
return( x /y);
};
void main(void)
sample obj1;
obj1.getinfo();
obj1.display();
obj1.sum();
obj1.diff();
obj1.mult();
obj1.div();
44 Lisalitsa 44
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
An array is a user defined type whose member are homogeneous and stored in contiguous
memory locations, mostly used in designing a large size of data base.
Class name {
Private:
// data
// methods
Public:
// methods
Protected:
// data
};
Where MAX is a user defined size of the array of the class objects
#include<iostream.h>
class student
private :
int age;
char sex;
45 Lisalitsa 45
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
float height;
public :
void getinfo()
cout<<”Age:”;
cin>>age;
cout <<”Sex:”;
cin >>sex;
cout<<”Height:”;
cin>>height;
void disinfo()
cout<< endl;
void main()
int i,n;
46 Lisalitsa 46
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
cin >>n;
int j = i;
cout <<endl;
object[i].getinfo();
object[i].disinfo();
}}
class sample{
private :
int x;
float y;
char s;
public :
void getdata();
void display();
};
sample *ptr;
47 Lisalitsa 47
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
where:
ptr is a pointer variable that holds the address of the address of the class sample and consists of
the three data member such as int x, float y and char s and also holds member functions such as
getdata() and display().
void main()
student *ptr;
------------
……………
(*ptr).data_member;
(*ptr).member_function();
void main()
student *ptr;
------------
……………
ptr->.data_member;
ptr->.member_function();
#include<iostream.h>
class student
48 Lisalitsa 48
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
private :
int age;
char sex;
float height;
public :
void getinfo();
void disinfo(); };
cout<<”Age:”;
cin>>age;
cout <<”Sex:”;
cin >>sex;
cout<<”Height:”;
cin>>height;
void disinfo()
cout<< endl;
49 Lisalitsa 49
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
void main()
ptr->disinfo();
CLASSES PART 2
CONSTRUCTORS
class stu
int m,n;
………..
};
50 Lisalitsa 50
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
m=0; n=0;
It should have public or protected access within the class and only in rare cases it may be
declared as private.
They may make use of new and delete when memory allocation is required.
//program to generate series of Fibonacci numbers using the constructor where the
constructor member function,
#include<iostream.h>
class fibonacci {
public :
fibonacci() { // constructor
f0 =0;
f1=1;
fib = fo +f1;
void increment ()
fo =f1
f1 =1;
fib = f0 +f1;
51 Lisalitsa 51
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
void display () {
void main()
fibonacci number;
number.display();
number.increment();
Copy constructor
They are used when the compiler has to create a temporary object of a class object.
General format
//program to generate series of Fibonacci numbers using the copy constructor where the
constructor member function,
#include<iostream.h>
52 Lisalitsa 52
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
class fibonacci {
public :
fibonacci() { // constructor
f0 =0;
f1=1;
fib = fo +f1;
f0 = ptr.fo;
f1 =ptr.1;
fib = f0 +f1;
Void increment ()
fo =f1
f1 =1;
fib = f0 +f1;
void display () {
void main()
53 Lisalitsa 53
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
int i;
fibonacci number;
number.display();
number.increment();
example 2
class CRectangle {
int width, height;
public:
CRectangle (int,int);
int area () {return (width*height);}
};
int main () {
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
DESTRUCTORS
54 Lisalitsa 54
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
The primary usage of the destructor function is to release space on the heap.
The destructor function name is the same as that of the class it belongs except that
the for character of the name must be a tilde(~0.
Example
class employee
private :
char name[20];
int ecode;
public :
employee();
~employee(); // destructor
void getdata();
void display();
};
New - the operator is used to create a heap memory space for an object of a class
55 Lisalitsa 55
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Delete – used to destroy the variable space which has been created by using the new
operator dynamically, hence to release the memory space.
class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};
CRectangle::~CRectangle () {
delete width;
delete height;
}
int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
56 Lisalitsa 56
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Overloading Constructors
Like any other function, a constructor can also be overloaded with more than one
function that have the same name but different types or number of parameters.
Remember that for overloaded functions the compiler will call the one whose parameters
match the arguments used in the function call.
In the case of constructors, which are automatically called when an object is created, the
one executed is the one that matches the arguments passed on the object declaration:
class CRectangle {
int width, height;
public:
CRectangle ();
CRectangle (int,int);
int area (void) {return (width*height);}
};
CRectangle::CRectangle () {
width = 5;
height = 5;
}
int main () {
CRectangle rect (3,4);
CRectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;}
57 Lisalitsa 57
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
INHERITANCE
58 Lisalitsa 58
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
A key feature of C++ classes is inheritance. Inheritance allows to create classes which are
derived from other classes, so that they automatically include some of its "parent's" members,
plus its own. For example, we are going to suppose that we want to declare a series of classes
that describe polygons like our CRectangle, or like CTriangle. They have certain common
properties, such as both can be described by means of only two sides: height and base.
DEFINATION :
This Is the process by which objects acquire the properties of objects of another class,it supports
the concept of hierarchical classification.
In oop , the concept of inheritance provide the idea of reusability, this means that we can add
additional feature to an existing class with out modifying it,
This is possible by deriving a new class from the existing one, the class will have combined
feature of both the classes hence the classes are reusablecould be represented in the world of
classes with a class CPolygon from which we would derive the two other ones: CRectangle and
CTriangle.
The class CPolygon would contain members that are common for both types of polygon. In our
case: width and height. And CRectangle and CTriangle would be its derived classes, with
specific features that are different from one type of polygon to the other.
Classes that are derived from others inherit all the accessible members of the base class. That
means that if a base class includes a member A and we derive it to another class with another
member called B, the derived class will contain both members A and B.
In order to derive a class from another, we use a colon (:) in the declaration of the derived class
using the following format:
59 Lisalitsa 59
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Where derived_class_name is the name of the derived class and base_class_name is the name of
the class on which it is based. The public access specifier may be replaced by any one of the
other access specifiers protected and private. This access specifier describes the minimum access
level for the members that are inherited from the base class.
// derived classes 2
#include <iostream> 0
using namespace std; 1
0
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
The objects of the classes CRectangle and CTriangle each contain members inherited from
60 Lisalitsa 60
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
SINGLE INHERITANCE
Is the process of creating new classes from an existing base class .the existing class is
known as direct base class and the newly created class is called a singly derived class.
Single inheritance is the ability of a derived class to inherit the member functions and
variables from the existing base class.
The declaration f a singly derived class is as that same of an ordinary class, a derived
class consist of the following components
a single colon
General syntax
private:
// data members
public:
// data members
// methods
protected:
61 Lisalitsa 61
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
data members
};
example
class basic {
private :
char name[20];
char sex;
public:
void getdata();
void display();
private:
float height;
float weight;
public:
void getd();
void disp();
};
Friend functions
In principle, private and protected members of a class cannot be accessed from outside the same
class in which they are declared. However, this rule does not affect friends.
62 Lisalitsa 62
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
If we want to declare an external function as friend of a class, thus allowing this function to have
access to the private and protected members of this class, we do it by declaring a prototype of
this external function within the class, and preceding it with the keyword friend:
// friend functions 2
#include <iostream> 4
using namespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area () {return (width * height);}
friend CRectangle duplicate (CRectangle);
};
int main () {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}
The duplicate function is a friend of CRectangle. From within that function we have been able to
63 Lisalitsa 63
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
access the members width and height of different objects of type CRectangle, which are private
members. Notice that neither in the declaration of duplicate()
summarize the different access types according to who can access them in the following way:
Where "not members" represent any access from outside the class, such as from main(), from
another class or from a function.
In our example, the members inherited by CRectangle and CTriangle have the same access
permissions as they had in their base class CPolygon:
This is because we have used the public keyword to define the inheritance relationship on each
of the derived classes:
This public keyword after the colon (:) denotes the maximum access level for all the members
inherited from the class that follows it (in this case CPolygon). Since public is the most
accessible level, by specifying this keyword the derived class will inherit all the members with
the same levels they had in the base class.
If we specify a more restrictive access level like protected, all public members of the base class
are inherited as protected in the derived class. Whereas if we specify the most restricting of all
access levels: private, all the base class members are inherited as private.
64 Lisalitsa 64
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
For example, if daughter was a class derived from mother that we defined as:
This would set protected as the maximum access level for the members of daughter that it
inherited from mother. That is, all members that were public in mother would become protected
in daughter. Of course, this would not restrict daughter to declare its own public members. That
maximum access level is only set for the members inherited from mother.
If we do not explicitly specify any access level for the inheritance, the compiler assumes private
for classes declared with class keyword and public for those declared with struct.
Although the constructors and destructors of the base class are not inherited themselves, its
default constructor (i.e., its constructor with no parameters) and its destructor are always called
when a new object of a derived class is created or destroyed.
If the base class has no default constructor or you want that an overloaded constructor is called
when a new derived object is created, you can specify it in each constructor definition of the
derived class:
For example:
class mother {
public:
mother ()
{ cout << "mother: no parameters\n"; }
65 Lisalitsa 65
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
mother (int a)
{ cout << "mother: int parameter\n"; }
};
int main () {
daughter cynthia (0);
son daniel(0);
return 0;
}
Notice the difference between which mother's constructor is called when a new daughter object
is created and which when it is a son object. The difference is because the constructor declaration
of daughter and son:
Multiple inheritance
In C++ it is perfectly possible that a class inherits members from more than one class. This is
done by simply separating the different base classes with commas in the derived class
declaration. For example, if we had a specific class to print on screen (COutput) and we wanted
our classes CRectangle and CTriangle to also inherit its members in addition to those of
CPolygon we could write:
class CRectangle: public CPolygon, public COutput;
66 Lisalitsa 66
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
// multiple inheritance
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class COutput {
public:
void output (int i);
};
int main () {
CRectangle rect;
67 Lisalitsa 67
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
rect.output (rect.area());
trgl.output (trgl.area());
return 0;
}
68 Lisalitsa 68
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
POLYMORPHISM
Polymorphism is the process where identically named methods(member functions) that have
different behavior depending on the type of object they refer,
The process of defining a number of objects of different classes into group and call the member
to carry out operation of objects using different function calls.
If any of the following statements seem strange to you, you should review the indicated sections:
Statement: Explained in:
int a::b(c) {}; Classes
a->b Data Structures
class a: public b; Friendship and inheritance
One of the key features of derived classes is that a pointer to a derived class is type-compatible
with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but
powerful and versatile feature, that brings Object Oriented Methodologies to its full potential.
We are going to start by rewriting our program about the rectangle and the triangle of the
previous section taking into consideration this pointer compatibility property:
69 Lisalitsa 69
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
int area ()
{ return (width * height); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
In function main, we create two pointers that point to objects of class CPolygon (ppoly1 and
ppoly2). Then we assign references to rect and trgl to these pointers, and because both are
objects of classes derived from CPolygon, both are valid assignations.
The only limitation in using *ppoly1 and *ppoly2 instead of rect and trgl is that both *ppoly1
and *ppoly2 are of type CPolygon* and therefore we can only use these pointers to refer to the
members that CRectangle and CTriangle inherit from CPolygon. For that reason when we call
the area() members at the end of the program we have had to use directly the objects rect and trgl
instead of the pointers *ppoly1 and *ppoly2.
In order to use area() with the pointers to class CPolygon, this member should also have been
declared in the class CPolygon, and not only in its derived classes, but the problem is that
CRectangle and CTriangle implement different versions of area, therefore we cannot implement
it in the base class. This is when virtual members become handy:
Virtual members
70 Lisalitsa 70
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
A member of a class that can be redefined in its derived classes is known as a virtual member. In
order to declare a member of a class as virtual, we must precede its declaration with the keyword
virtual:
// virtual members 2
#include <iostream> 0
using namespace std; 1
0
class CPolygon { 0
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return (0); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon poly;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
CPolygon * ppoly3 = &poly;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << endl;
71 Lisalitsa 71
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Now the three classes (CPolygon, CRectangle and CTriangle) have all the same members: width,
height, set_values() and area().
The member function area() has been declared as virtual in the base class because it is later
redefined in each derived class. You can verify if you want that if you remove this virtual
keyword from the declaration of area() within CPolygon, and then you run the program the result
will be 0 for the three polygons instead of 20, 10 and 0. That is because instead of calling the
corresponding area() function for each object (CRectangle::area(), CTriangle::area() and
CPolygon::area(), respectively), CPolygon::area() will be called in all cases since the calls are
via a pointer whose type is CPolygon*.
Therefore, what the virtual keyword does is to allow a member of a derived class with the same
name as one in the base class to be appropriately called from a pointer, and more precisely when
the type of the pointer is a pointer to the base class but is pointing to an object of the derived
class, as in the above example.
Note that despite of its virtuality, we have also been able to declare an object of type CPolygon
and to call its own area() function, which always returns 0.
Abstract base classes are something very similar to our CPolygon class of our previous example.
The only difference is that in our previous example we have defined a valid area() function with
a minimal functionality for objects that were of class CPolygon (like the object poly), whereas in
an abstract base classes we could leave that area() member function without implementation at
all. This is done by appending =0 (equal to zero) to the function declaration.
72 Lisalitsa 72
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area () =0;
};
Notice how we appended =0 to virtual int area () instead of specifying an implementation for the
function. This type of function is called a pure virtual function, and all classes that contain at
least one pure virtual function are abstract base classes.
The main difference between an abstract base class and a regular polymorphic class is that
because in abstract base classes at least one of its members lacks implementation we cannot
create instances (objects) of it.
But a class that cannot instantiate objects is not totally useless. We can create pointers to it and
take advantage of all its polymorphic abilities. Therefore a declaration like:
CPolygon poly;
would not be valid for the abstract base class we have just declared, because tries to instantiate
an object. Nevertheless, the following pointers:
CPolygon * ppoly1;
CPolygon * ppoly2;
This is so for as long as CPolygon includes a pure virtual function and therefore it's an abstract
base class. However, pointers to this abstract base class can be used to point to objects of derived
classes.
class CPolygon {
protected:
73 Lisalitsa 73
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << endl;
cout << ppoly2->area() << endl;
return 0;
}
If you review the program you will notice that we refer to objects of different but related classes
using a unique type of pointer (CPolygon*). This can be tremendously useful. For example, now
we can create a function member of the abstract base class CPolygon that is able to print on
screen the result of the area() function even though CPolygon itself has no implementation for
this function:
74 Lisalitsa 74
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
void printarea (void)
{ cout << this->area() << endl; }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly1->printarea();
ppoly2->printarea();
return 0;
}
Virtual members and abstract classes grant C++ the polymorphic characteristics that make
object-oriented programming such a useful instrument in big projects. Of course, we have seen
very simple uses of these features, but these features can be applied to arrays of objects or
75 Lisalitsa 75
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
Let's end with the same example again, but this time with objects that are dynamically allocated:
int main () {
CPolygon * ppoly1 = new CRectangle;
CPolygon * ppoly2 = new CTriangle;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly1->printarea();
ppoly2->printarea();
delete ppoly1;
delete ppoly2;
76 Lisalitsa 76
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
return 0;
}
are declared being of type pointer to CPolygon but the objects dynamically allocated have been
declared having the derived class type directly.
Finalize
The finalize function in Java, roughly corresponds to the destructor in C++. When an object is
collected by the garbage collector, its finalize method is called. This allows objects to clean up
after themselves.
Operator Overloading
It is only possible in in c++ but not in java(calling of different operators at the same time)
Templates
Templates are a wonderful feature of C++. The fact that Java does not support such templates for
tempory holding the information while it is in the memory.
Multiple Inheritance
Memory Management
Java uses garbage collection. Garbage collection is a scheme of memory management that
automatically frees blocks of memory sometime after all references to that memory have been
redirected
77 Lisalitsa 77
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+
References:
Prepared by
Mr .Masese
0727171725 /0737070029
Internationalkid@gmail.com
78 Lisalitsa 78
For For Lisalitsa