KEMBAR78
C++ Object Oriented Progamming | PDF | Class (Computer Programming) | C++
0% found this document useful (0 votes)
49 views78 pages

C++ Object Oriented Progamming

Uploaded by

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

C++ Object Oriented Progamming

Uploaded by

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

PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+

KABARAK UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCE

STUDENT MANUAL

COURSE NAME : COMP 212 (OBJECT ORIENTED PROGAMMING)

(PROGRAMMING WITH C++)

For Lisalitsa 1
1
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

CONTENTS PAGE

Object – Oriented Programming

COMPARISON WITH TRADITIONAL PROGRAMMING TECHNIQUES

OVERVIEW OF OBJECT ORIENTED PROGRAMMING

 Object

 Classes

 Data abstraction and encapsulation

 Inheritance

 Polymorphism

 Dynamic binding

 Message passing

Data abstraction in object-oriented programming

 Tokens

 Operators

 Basic Data Types

 Control Structure

 Functions

 Array

 Classes And Object

 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

Procedure oriented programming

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

Some features exhibited by procedure programming are :

 Emphasis is on doing things(algorithms)

 Large programs are divided into smaller programs known as functions

 Most of the functions share global data

 Data move openly around the system from function to function

 Functions transform data from one form to another

 Employ top – down approach in program design

Object oriented programming paradigm

Def:

For Lisalitsa 3
3
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

Object oriented programming as an approach that provides a way of modularizing programs by


creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand

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

Function1 Function 2 Function3

Local data Local data


Local data

Its features

 Emphasis is on data rater than procedure

 Programs are divided into what is known as objects

 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

 Data are hidden and cannot be accessed by external functions

 Object may communicate with each other through functions

 New data and functions can be easily added whenever necessary

 Follow bottom up approach in program design

For Lisalitsa 4
4
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

Basic concepts of object oriented programming

Include:

1. Object

2. Classes

3. Data abstraction and encapsulation

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

Data name ,dob,marks


functions total , average,display

: 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

// will create an object mango belonging to the class fruit

class classname

instructions
}

Data abstraction and encapsulation

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

Child class 1 Child class 2

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:

1. Creating classes that define objects and their behavior

2. Creating objects from class definitions

3. Establishing communication among objects

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);

Object message information

For Lisalitsa 8
8
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

Benefits of object oriented programming

 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

 It is possible to map objects in the problem domain to those in the program

 Message passing techniques for communication between objects makes the interface
descriptions with external system much simple

Simple programs in c++

#include <iostream.h> // header file

Int main() // start of the program

cout << “ hallo” ; // cout used to display the information(screen output)

Return 0; }

my first program in C++

#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

using namespace std;


All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its functionality we
declare with this expression that we will be using these entities

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;

cout<< “enter two numbers:”;

cin>> number1;

cin>>number2;

sum = number1 + number2;

average = sum/2;

cout << “Sum =” << sum <<”\n”;

cout << “Average =”<< average << “\n”;

return 0;

General structure of a c++ program

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

Identifiers refer to t he names of variables, functions, array, classes created by the


user(programmer) .

they can be defined as the name of the variable and some other program elements using the
combination of the following characters

Alphabets :a ……..z ,A…..Z

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.

Rules for naming a identifiers

1. only alphabetic characters, digits and underscore are permitted

2. the name cannot start by a digit

3. upper case and lower case are distinct

4. a declared keyword cannot be used as variable name

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

String constant: is a sequence of alphanumeric characters enclosed in double quotation marks


whose maximum length is 255 characters

Examples

“result” “ksh 3000” “my program’

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 int x,y;

long int x,y

integer data: int stands for the integer data

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;

the 5 in this piece of code was a literal constant.

Assignment (=)

The assignment operator assigns a value to a variable.


a = 5;

This statement assigns the integer value 5 to the variable

Arithmetic operators ( +, -, *, /, % )

The five arithmetical operations supported by the C++ language are:


+ addition
- subtraction
* multiplication

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.

Logical operators ( !, &&, || )

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:

!(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.

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:

( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).


( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).

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:

condition ? result1 : result2

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.

// 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.

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.

Bitwise Operators ( &, |, ^, ~, <<, >> )

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+
+

>> SHR Shift Right

Explicit type casting operator

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 );

Both ways of type casting are valid in C++.

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

we may doubt if it really means:

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:

Level Operator Description Grouping


Left-to-
1 :: scope
right
() [] . -> ++ -- dynamic_cast static_cast Left-to-
2 postfix
reinterpret_cast const_cast typeid right
++ -- ~ ! sizeof new delete unary (prefix)
indirection and reference Right-to-
3 *&
(pointers) left
+- unary sign operator
Right-to-
4 (type) type casting
left
Left-to-
5 .* ->* pointer-to-member
right
Left-to-
6 */% multiplicative
right
Left-to-
7 +- additive
right
Left-to-
8 << >> shift
right
Left-to-
9 < > <= >= relational
right

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 (\)

BASIC DATA TYPES

Name Description Size* Range*


signed: -128 to 127
char Character or small integer. 1byte
unsigned: 0 to 255
short int signed: -32768 to 32767
Short Integer. 2bytes
(short) unsigned: 0 to 65535
signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
Boolean value. It can take one of two
bool 1byte true or false
values: true or false.
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
double Double precision floating point number. 8bytes 1.7e +/- 308 (15 digits)
Long double precision floating point
long double 8bytes 1.7e +/- 308 (15 digits)
number.

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

 switch case statement

loop statement

 for loop

 While loop

 Do while loop

Breaking control statement

 Break statement

 Continue statement

21 Lisalitsa 21
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

 goto statement

CONDITIONAL STATEMENT

They are used in decision making process

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;

} // the expression is evaluated if it is true

Example

#include <iostream.h>

main(void)

int a=20;

int b =10;

if (a > b )

cout << “ largest value =” << a;

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)

Statement 1 // statement 1 will be executed if it is true

Else // where the else part is optional

Statement2

Example

#include <iostream.h>

void main(void)

float x,y;

cout << “ enter any two numbers \n”;

cin >> x>>y;

if (x > y)

cout << “largest value is “<< x << endl;

else

cout<< “largest value is “ <<y<< endl;

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>

void main (void)

int day;

cout<<”enter any number between 1 to 7 \n”;

cin >> day;

23 Lisalitsa 23
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

if (day == 1)

cout <<”Monday \n”;

else if (day == 2)

cout << “Tuesday \n”;

else if (day ==3)

cout << “Wednesday \n”;

else if(day ==4)

cout << “Thursday \n”;

else if(day ==5)

cout <<” Friday \n”;

else if (day==6)

cout << “Saturday \n”;

else if (day ==7)

cout <<”Sunday \n”;

else

cout << “enter a correct number \n”;

SWITCH STATEMENT

this is a multiple branching statement where,based on a condition, the control is transferred to


one of the many possible points

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

// TO CHECK WHETHER THE CHARACTER ENTERED ID A VOWEL OR NOT

Switch (input_ch) {

case ‘A’:

case ‘a’ :

Cout <<”A”;

break;

case ‘E’ :

case ‘e’ :

cout << ” e”;

break;

25 Lisalitsa 25
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

case ‘I’ :

case ‘i’ :

cout << ”i”;

break;

case ‘O’ :

case ‘o’ :

cout << ” o”;

break;

case ‘U’ :

case ‘u’ :

cout << ” u”;

break;

default :

cout <<” not a vowel \n”;

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>

void main (void)

int day;

cout<<”enter any number between 1 to 7 \n”;

switch(day)

case 1 :

26 Lisalitsa 26
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

cout <<”Monday \n”;

break;

case 2 :

cout << “Tuesday \n”;

break;

case 3 :

cout << “Wednesday \n”;

break;

case 4 :

cout << “Thursday \n”;

break;

case 5 :

cout <<” Friday \n”;

case 6 :

cout << “Saturday \n”;

case 7:

cout <<”Sunday \n”;

LOOP STATEMENT

FOR LOOP

Syntax: for (initialization; condition; increase) statement;

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.

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 { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back to
step 2.
The for is an entry entrolled loop and is used when an action iis to be repeated for predetermined
number of times

Syntax

For(initial value; test; increment/decrement)

Where:

The first expression is used to initialize the index value

Second expression to check whether or not the loop is to continued again

Third to change the index value for further iteration

Example

void main(void) {

for( int i=0; I <=10; ++i)

cout << i << ‘\t’;

} } // will display numbers between one to ten

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)

int sum, digit;

sum =0; digit = 1;

while(digit <= 100)

sum + =digit;

digit ++;

cout << “1+2+3 …….. 100 = sum << endl;

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;

cout<< “enter a number \n ”;

cin >> max;

do

sum = sum + digit;

digit = digit +2;

while (digit <= max);

cout << “2 + 4+ ….=”<< max << “sum = “;

cout << sum << endl;

Breaking control statement

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)

int value ,I;

I =0;

while (i<=10)

cout <<”enter a number \n”;

cin >> value;

if (value <=0){

cout<< “zero or negative value found \n”;

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:

cout << “my first program \n”;

go to start;

#include<iostream.h>

void main()

int a,b;

cout <<”enter two numbers \n”;

cin >> a>> b;

if (a>b)

goto output1;

else

goto output2;

output1:

cout<<” largest value =”<< a<< endl;

goto stop

output2:

cout<<”largest value =”<< b<< endl;

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

Main advantages of using function

 easy to write a correct small function

 easy to read write and debug a function

 easier to maintain or modify such a function

 it can be called more than once in any part of the program

syntax

functiontype functionname(datatype arg1,datatype arg2…)

Body of function

------

Return something

Example

#include <iostream.h>

Void main(void)

void display(void); // function declaration

display(); // function calling

Void display(void) // function definition

cout<< “my first program .\n”

33 Lisalitsa 33
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

cout<< “demonstrating a function call \n”;

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

passing parameters by reference


#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)


{
a*=2;
b*=2;
c*=2;
}

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+
+

void swap (int, int);

x= 100;

y = 20;

cout <<”values before swap() ”<<endl;

cout << “x =” << x << “ and y =”<< y<<endl;

swap(x,y); // call by value

cout << “values after swap () “<<endl;

cout <<” x = “<< x<<” and y =”<<y<<endl;

void swap(int x, int y)

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

Inline function –header

Function body

35 Lisalitsa 35
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

Example

#include<iostream.h>

inline float mul(float x, float y)

return(x * y);

Inline float div(double p , double q)

return(p /q);

int main()

float a =12.34;

float b = 19.08;

cout << mul(a,b) << “\n”;

cout<< div(a,b) <<”\n”;

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),

 The name of the array,

 Number of subscripts in the array (whether it is one dimensional or two dimensional


array)

 Total number of memory locations to be allocated

example

int mark[300];

char line[30];

array initialization

general format

storage_class data_type array_name[expression]=(element_1,element_2…..element_n)

example

char name [5] ={‘r’,’a’,’v’,’i’,’c’};

int values [7] ={10,23,34,56,78,12,34};

char sex [2] ={‘m’,’f’};

program

// to read n numbers from the keyboard(where n is defined by the user)

# 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;

cout <<”how many numbers do you want in the array ?”<<endl;

cin>>n;

cout<< “enter the elements “<<endl;

for(i =0;i<=n-1;i++)

cin>>a[i];

cout<<”contents of the array ”<<endl;

for(i = 0;i<= n-1; i++)

cout <<a[i] <<’\t’;

}}

POINTERS

A pointer is a variable that holds the memory address of another variable.

Advantages of pointers

 Allows to pass variable, array, functions strings and structures as function arguments

 A pointer allows to return structured variable from functions

 Provides functions which can modify their calling arguments

 It supports dynamic allocation and deallocation of memory segments

 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

A pointer operator can be represented by a combination of *(asterisk) with a variable

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

An address operator can be represented by a combination of &(ampersand) with a pointer


variable

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

int *ptr1, ptr2;

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;

Ptr2 = ptr1 // address of ptr1 is assigned to ptr2

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;

cout << “value of x =”<< x<< endl;

cout << “value of ptr1 = “ <<ptr1<< endl;

cout << “value of ptr2 =”<< ptr2 <<endl;

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:

expression can be read as


*x pointed by x
&x address of x
x.y member y of object x
x->y member y of object pointed by x
(*x).y member y of object pointed by x (equivalent to the previous one)
x[0] first object pointed by x
x[1] second object pointed by x
x[n] (n+1)th object pointed by x
CLASSES AND OBJECT

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 and classes

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+
+

List of friendly functions

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.

A simple class example

class student

long int rollno;

private:

int age; // variable declaration

char sex;

float height;

public :

void getdata( ); // functions declaration

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.

ACCESSING A MEMBER OF CLASS

A data or function member of a class construct is accessed using the .(period) operator

The general syntax for accessing a member of class is

class_object.data_member

class_object.function_member

// program to perform arithmetic operations using the member functions

#include<iostream.h>

class sample {

private:

int x;

int y;

public :

void getinfo() {

cout <<” enter any two numbers ?”<<endl;

cin >> x >> y;

void display() {

cout << “ x =” << x << endl;

cout << “y=” << y<< endl;

cout <<”sum =” <<sum() <<endl;

43 Lisalitsa 43
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

cout <<”dif =” <<diff() <<endl;

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+
+

ARRAY OF CLASS OBJECTS

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.

The general structure

Class name {

Private:

// data

// methods

Public:

// methods

Protected:

// data

};

Class user_defined_name object[max];

Where MAX is a user defined size of the array of the class objects

// program to demonstrate array of class objects

#include<iostream.h>

const int MAX =100;

class student

private :

long int rollno;

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 << “Roll no:”;

cin >> rollno;

cout<<”Age:”;

cin>>age;

cout <<”Sex:”;

cin >>sex;

cout<<”Height:”;

cin>>height;

void disinfo()

cout<< endl;

count << “Roll no =” <<rollno<<endl;

count << “Age =” <<age<<endl;

count << “Sex =” <<sex<<endl;

count << “Height =” <<height<<endl;

} }; // end of class definition

void main()

student object[max]; // array of objects

int i,n;

46 Lisalitsa 46
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

cout <<”how many students ? \n”<<endl;

cin >>n;

cout <<”enter the following information…. \n”<<endl;

for(i=0 ; i<=n-1; ++1) {

int j = i;

cout <<endl;

cout <<”record =” << j+1 <<endl;

object[i].getinfo();

cout << “contents of class \n”;

for(i =0; i<= n-1; ++i) {

object[i].disinfo();

}}

POINTER AND CLASSES

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().

The pointer can be accessed and processed in the following ways…

(*object name).member name = variable;

void main()

student *ptr;

------------

……………

(*ptr).data_member;

(*ptr).member_function();

object name -> member name = variable;

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 :

long int rollno;

int age;

char sex;

float height;

public :

void getinfo();

void disinfo(); };

void student :: getinfo ()

cout << “Roll no:”;

cin >> rollno;

cout<<”Age:”;

cin>>age;

cout <<”Sex:”;

cin >>sex;

cout<<”Height:”;

cin>>height;

void disinfo()

cout<< endl;

count << “Roll no =” <<rollno<<endl;

count << “Age =” <<age<<endl;

49 Lisalitsa 49
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

count << “Sex =” <<sex<<endl;

count << “Height =” <<height<<endl;

} }; // end of class definition

void main()

student *ptr; // pointer

cout <<”enter the following information…. \n”<<endl;

ptr -> getinfo();

cout << “ \n contents of class ”<<endl;

ptr->disinfo();

CLASSES PART 2

CONSTRUCTORS

a constructor is a special member function for automatic initialization of an object whenever an


object is created , it will be executed automatically, it has same name as that of the class.

A constructor can be declared in the following way:

class stu

int m,n;

public stu(void) // constructor declared

………..

};

stu :: stu(void) // constructor defined

50 Lisalitsa 50
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

m=0; n=0;

RULES FOR WRITING THE CONSTRUCTOR FUNCTIONS

The constructor name must be same as that of the class

 It may not be static

 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.

 It is invoked automatically when the object are created.

 It is declared with no return type(not even void)

//program to generate series of Fibonacci numbers using the constructor where the
constructor member function,

#include<iostream.h>

class fibonacci {

private : unsigned long int f0,f1,fib;

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 () {

cout << fib <<’\t’;

}; //end of class constructor

void main()

fibonacci number;

for (int i =0 ;i <=15; ++i)

number.display();

number.increment();

Copy constructor

They are used when the compiler has to create a temporary object of a class object.

It is used in the following situations:

 The initialization of an object by another object of the same class

 Return of object as a function value

 Stating the object by value parameter of a function.

General format

class_name :: class_name(class_name &ptr)

//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 {

private : unsigned long int f0,f1,fib;

public :

fibonacci() { // constructor

f0 =0;

f1=1;

fib = fo +f1;

fibonacci( fibonacci &ptr)

f0 = ptr.fo;

f1 =ptr.1;

fib = f0 +f1;

Void increment ()

fo =f1

f1 =1;

fib = f0 +f1;

void display () {

cout << fib <<’\t’;

}; //end of class constructor

void main()

53 Lisalitsa 53
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

int i;

fibonacci number;

for (int i =0 ;i<=15; ++i)

number.display();

number.increment();

example 2

// example: class constructor


#include <iostream>
using namespace std;

class CRectangle {
int width, height;
public:
CRectangle (int,int);
int area () {return (width*height);}
};

CRectangle::CRectangle (int a, int b) {


width = a;
height = b;
}

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+
+

Destructor is a function that automatically executes when an object is destroyed , a destructor


function gets executed whenever an instance of the class to which it belongs goes out of
existence.

The primary usage of the destructor function is to release space on the heap.

Rules for setting the constructor

 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.

 It is declared with no return type(not even void)

 It can not be declared as static

 No arguments and therefore can be overloaded

 It should have public access in the class declaration

Example

class employee

private :

char name[20];

int ecode;

public :

employee();

~employee(); // destructor

void getdata();

void display();

};

Dynamic memory allocation

New - the operator is used to create a heap memory space for an object of a class

syntax new int

55 Lisalitsa 55
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

An allocation expression must call out the following:

 Find storage for the object to be created

 Initialize that object

 Return a suitable pointer type to the object

Delete – used to destroy the variable space which has been created by using the new
operator dynamically, hence to release the memory space.

syntax delete pointer;

// example on constructors and destructors


#include <iostream>
using namespace std;

class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {


width = new int;
height = new int;
*width = a;
*height = b;
}

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:

// overloading class constructors


#include <iostream>
using namespace std;

class CRectangle {
int width, height;
public:
CRectangle ();
CRectangle (int,int);
int area (void) {return (width*height);}
};

CRectangle::CRectangle () {
width = 5;
height = 5;
}

CRectangle::CRectangle (int a, int b) {


width = a;
height = b;
}

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

Inheritance between classes

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:

class derived_class_name: public base_class_name


{ /*...*/ };

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;}
};

class CRectangle: public CPolygon {


public:
int area ()
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area ()
{ return (width * height / 2); }
};

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+
+

CPolygon. These are: width, height and set_values().

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.

Defining the derived class

The declaration f a singly derived class is as that same of an ordinary class, a derived
class consist of the following components

 The key word class

 name of the derived class

 a single colon

 the type of derivation(private, public or protected)

 name of the base or parent class

General syntax

Class derived_class_name:provate/public/protected base_class_name {

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];

long int rollno;

char sex;

public:

void getdata();

void display();

} // end of class definition

class physical_fit :public basic_info

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+
+

Friends are functions or classes declared as such.

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);
};

void CRectangle::set_values (int a, int b) {


width = a;
height = b;
}

CRectangle duplicate (CRectangle rectparam)


{
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}

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:

Access public protected private


members of the same class yes yes yes
members of derived
yes yes no
classes
not members yes no no

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:

CPolygon::width // protected access


CRectangle::width // protected access

CPolygon::set_values() // public access


CRectangle::set_values() // public access

This is because we have used the public keyword to define the inheritance relationship on each
of the derived classes:

class CRectangle: public CPolygon { ... }

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:

class daughter: protected mother;

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.

What is inherited from the base class?

In principle, a derived class inherits every member of a base class except:

 its constructor and its destructor


 its operator=() members
 its friends

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:

derived_constructor_name (parameters) : base_constructor_name (parameters) {...}

For example:

// constructors and derived classes


#include <iostream>
using namespace std;

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"; }
};

class daughter : public mother {


public:
daughter (int a)
{ cout << "daughter: int parameter\n\n"; }
};

class son : public mother {


public:
son (int a) : mother (a)
{ cout << "son: int parameter\n\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:

daughter (int a) // nothing specified: call default


son (int a) : mother (a) // constructor specified: call this

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+
+

class CTriangle: public CPolygon, public COutput;

here is the complete example:

// 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);
};

void COutput::output (int i) {


cout << i << endl;
}

class CRectangle: public CPolygon, public COutput {


public:
int area ()
{ return (width * height); }
};

class CTriangle: public CPolygon, public COutput {


public:
int area ()
{ return (width * height / 2); }
};

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

Pointers to base class

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:

// pointers to base class 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; }
};

class CRectangle: public CPolygon {


public:

69 Lisalitsa 69
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

int area ()
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area ()
{ return (width * height / 2); }
};

int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
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); }
};

class CRectangle: public CPolygon {


public:
int area ()
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area ()
{ return (width * height / 2); }
};

int main () {
CRectangle rect;
CTriangle trgl;
CPolygon poly;
CPolygon * ppoly1 = &rect;
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+
+

cout << ppoly2->area() << endl;


cout << ppoly3->area() << endl;
return 0;
}

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.

A class that declares or inherits a virtual function is called a polymorphic class.

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

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.

An abstract base CPolygon class could look like this:

// abstract class CPolygon


class CPolygon {
protected:
int width, height;

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;

would be perfectly valid.

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.

Here you have the complete example:

// abstract base class


#include <iostream>
using namespace std;

class CPolygon {
protected:

73 Lisalitsa 73
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

int width, height;


public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
};

class CRectangle: public CPolygon {


public:
int area (void)
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area (void)
{ return (width * height / 2); }
};

int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
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:

// pure virtual members can be called 2


// from the abstract base class 0
#include <iostream> 1

74 Lisalitsa 74
For For Lisalitsa
PROGAMMING USING C++ PROGAMMING USING C++ PROGAMMING USING C+
+

using namespace std; 0

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; }
};

class CRectangle: public CPolygon {


public:
int area (void)
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area (void)
{ return (width * height / 2); }
};

int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
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+
+

dynamically allocated objects.

Let's end with the same example again, but this time with objects that are dynamically allocated:

// dynamic allocation and polymorphism 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; }
virtual int area (void) =0;
void printarea (void)
{ cout << this->area() << endl; }
};

class CRectangle: public CPolygon {


public:
int area (void)
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area (void)
{ return (width * height / 2); }
};

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;
}

Notice that the ppoly pointers:

CPolygon * ppoly1 = new CRectangle;


CPolygon * ppoly2 = new CTriangle;

are declared being of type pointer to CPolygon but the objects dynamically allocated have been
declared having the derived class type directly.

COMPARISON OF C++ AND JAVA

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

The designers of Java avoided multiple inheritance. Replacing it is multiple conformance to


interfaces . In Java, there is a structure called an "Interface". A Java interface is almost identical
to a C++ class that has nothing but pure virtual functions.

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:

1.PROGRAMMING WITH C++ BY D. RAVICHARAN TATA MCGRAW HILL

2.PROGRAMMING WITH C++ BY BALUSAMY TATA MCGRAW HILL

3. WEB SITE : http://www.cplusplus.com

Prepared by
Mr .Masese
0727171725 /0737070029

Internationalkid@gmail.com

78 Lisalitsa 78
For For Lisalitsa

You might also like