Professional Documents
Culture Documents
Pratheepan
Week 1 & 2
Computer Programming:
Computer programming means to develop or write computer programs to perform different types of
activities in a computer system using computer languages.
Programming can be classified into two types: systems programming and (application)
programming.
System programming is handled by computer engineers or system programmers to develop system
programs such as operating systems, language translators, etc.
(Application) programming is handled by ordinary computer programmers to develop application
software such as payroll system, stock control system, etc.
The possibility of programming a task by a machine is called computability.
Complexity is the measuring term of quantity of resources used for many alternative algorithms.
Knowledge of complexity helps to find the best algorithm. Average cases and worst cases can also
be identified.
A program should produce the required result for all possible inputs; and it is called correctness.
Programming that produces programs with clean flow, clear design, and a degree of modularity or
hierarchical structure is called structured programming. The three basic constructs in structured
programming are sequence (ordered set of statements), selection (conditional branch), and iteration
(repletion). There is no GOTO statement to jump to any place in the program.
An approach to programming in which the program is broken into several independently compiled
modules is called modular programming. It facilitates group programming efforts. Modular
programming is a precursor (ancestor) of object oriented programming.
Object-oriented programming (OOP) is a programming paradigm in which a program is viewed as a
collection of discrete objects that are self contained collection of data structures and routines that
interacts with other objects.
An approach to programming that implements a program in top-down fashion is referred to as top-
down programming. Typically this is done by writing a main body which calls to several major
routines (implemented as stubs). Each routine is then coded, calling other, lower-level routines (also
done initially as stubs). Here, stub is a placeholder for a routine to be written later.
Bottom-up programming is a programming technique in which lower-level functions are developed
and tested first; higher-level functions are then built using the lower-level functions.
Programming Language:
Programming Language is any artificial language that can be used to define a sequence of
instructions that can ultimately be processed and executed by the computer.
A program called, language translator, translates statements written in one programming language
into their machine language.
Levels/Generations of Languages:
Languages are generally divided into five levels/generations: (1) machine language, (2) assembly
language, (3) high-level languages, (4) very high-level languages, and (5) natural languages.
Programs that are written in 0s and 1s are in the actual machine language. Machine code consists
of binary coded instructions and data intermixed. All other languages must be translated into
machine language before execution. Each type of computer has its own unique machine langue.
Machine language is very difficult to write programs and to detect and correct program errors. A
thorough knowledge of computer hardware is required for machine language programming. Here,
programmers cannot concentrate on data processing problems, because more attention should be
paid for the architecture of the computer system. Machine language programs are not portable
among different types of computers. However, machine language programs can be executed much
faster and maximum usage of resources (e.g. memory) can be obtained.
Assembly language is the direct symbolic representation of a machine language. Assembly
languages include IBM, BAL and VAX Macro. Assembly languages use English-like mnemonic
codes to represent the operations: A for add, C for compare, MP for multiply, STO for storing
information in memory, and so on. Assembly language specifies registers with meaningful codes,
such as AX, BX, etc., instead of binary numbers. Furthermore, it permits the use of names –
perhaps RATE or TOTAL – for memory locations, instead of the actual binary memory address. As
with machine language, each type of computer has its own unique assembly language. Therefore,
both machine and assembly languages are considered as machine oriented or low-level computer
languages. Assembly language is easy to write programs and to detect and correct program errors
compared to machine language programs. As source program should be translated into machine
language, more time is required for execution.
The part of the machine language or assembly language instructions that specifies the operation or
function to be carried out is called opcode.
To overcome problems of low-level languages, high-level languages were developed. As standard
words of those languages are closer to human language (English) it is much easier to write
programs and to detect and correct errors. As high-level languages are machine independent,
programs are portable, less hardware knowledge is required, and more attention can be paid for
data processing requirements. Here, a lesser number of instructions are required. Due to the
compilation process more time is needed to execute the program. Here, computer resources cannot
be used fully. FORTRAN (Formula translator), ALGOL (Algorithmic Language), COBOL (Common
business oriented language), RPG (Report program generator), BASIC (Beginners all purpose
symbolic instruction code), Pascal, C, C++, Java, and Visual Basic, are some of the examples for
high-level language. For any given high-level language, there are usually a number of translators
available, each of which translates a program in that language to the machine language for a
specific type of computer.
Very high-level languages are often known as 4GLs (fourth-generation languages). Languages
belonging to the first three generations are procedural languages, consisting of instructions that
describe the step-by-step procedure to solve the problem. 4GLs are nonprocedural languages, in
which the programmer specifies the desired results, and the language develops the solution.
Query languages, such as SQL (Structured query language), are variations on 4GLs and are used
to retrieve information from databases.
The natural language (sometimes considered to be 5GLs) translates human instructions into code
the computer can execute. If it does not understand the user’s request, it politely asks for further
explanation. For example, INTELLECT, a natural language, would use a statement like, “What are
the average exam scores in MIS?”.
E.g.: Comparison among different levels of programming languages.
Machine Assembly High-Level 4GL / Natural Language
Language Language language
1010 11001 LOD Y X=Y+Z SUM THE FOLLOWING
1011 11010 ADD Z NUMBERS
1100 11011 STR X
Language Translators:
All the source programs should be converted into their machine language before the execution
process. Language translators are used for this translation.
There are three types of language translators: Assemblers, Compilers, and Interpreters.
Assembler is a language translator which translates source programs written in assembly language
into their object programs.
Compiler translates/compiles the entire program written in a high-level language into its object
program considering the program as a single unit. After the compilation process the source program
is no more required as the object program is available. A compiler is able to look at the whole of a
program and to work out the best way of translating. This is some times called optimization and is
one of the reasons why a compiler can produce efficient code. Once all errors have been corrected,
the program will run faster. However errors are more difficult to find during compilation because they
are not reported until the end of the process and a single error can generate additional error
messages making it harder to locate the error. When the program is in testing mode, there is no
benefit to having a stored executable program since this will have to be rebuilt each time.
Interpreter is a language translator which converts high-level language statements into equivalent
machine language statements one at a time as the program is executed. It does not generate an
object program as a separate unit. Here, each statement is checked for syntax, then converted into
machine code, and then executed. The presence of the source program is required for the
execution of the program and it should be interpreted each time. Here, in the case of repetition,
some program statements may be translated many times. Executing an interpreted program is
slower than executing a compiled program since each statement has to be converted to binary each
time even if it has been converted previously. With an interpreted language there is always the
danger that a syntax error may exist in a section of code that has not been tested. However, there is
no lengthy compile and link cycle. If the program encounters an error, the interpretations stops and
an error message is displayed so the user can correct it. Therefore, interpreters are comfortable for
beginners because small programs can be written and tested very quickly.
Most current languages come in a comprehensive package called an integrated development
environment (IDE) that includes language aware editor, project build capability (compile and link),
debugger, and other programming tools. Other programming tools include diagramming packages,
code generators, libraries of reusable objects and program code, and prototyping tools.
3. Functional Languages: These are based on lambda-calculus, which concerns the application of
functions to their arguments. Functional Language programs consist of collections of function
definitions and their applications. E.g.: LISP (LISt Processing), etc.
4. Logic Programming Languages: Here, programs consists of collections of statements within a
particular logic, such as predicate logic. E.g.: Prolog (Programming logic), etc.
5. Object Oriented Language: Here, programs consist of objects that interact with each other. E.g.:
SIMULA (SIMUlation Language), Smalltalk, Eiffel, etc.. The object-oriented language that
currently dominates the market is C++. It supports both object-oriented programming and non-
object-oriented programming. Java, the language threatening C++ dominance, is a pure object-
oriented language; that is, it is impossible to write a non-object-oriented program. The latest
version of Java is J2EE (Java2 Enterprise Edition). A relatively new language, C# (“cee-sharp”) is
Microsoft’s answer to Java. It has most of the same advantages over C++ as does Java, but it is
designed to work within Microsoft’s .NET environment. The .NET environment is designed for
building, deploying (organizing), and running Web-based applications. Many people referred to
prior versions of Visual Basic as ‘object-oriented’, because VB programs used ‘objects’ such as
command buttons, scrollbars, and others. However, it wasn’t until the current version, VB.NET,
that Visual Basic supported the concepts of inheritance and polymorphism, thus meeting the
criteria for a true object-oriented language.
6. Declarative Language: These are collections of declarations. Many functional and Logic
languages are also declarative. Here, you describe a pattern to be matched without writing the
code to match the pattern.
7. Scripting Languages: Scripting languages are designed to perform special or limited tasks,
sometimes associated with a particular application or function. E.g.: Perl (Practical extraction
report language), etc.
8. Parallel Languages: These are collections of processes that communicate with each other. E.g.:
C*, Ada, etc.
3. Program coding:
Program coding means conversion of the algorithm into a set of instructions written in a computer
programming language.
This program is keyed into the computer by using a text editor, a program that is similar to a word
processor.
Object Program
[Machine Language Version]
Utility Programs
Linking [System Library] Linkage Editor / Linker Link errors
Executable Program
(Load Module)
Execution Run-time errors
Information
The original program written in a computer programming language is called as source program.
Initially, this source program is translated into its machine language form (called object program)
by the language translator (compiler). If the source program violates the grammatical rules of that
programming language, it cannot be converted into its machine language and these types of
errors can be described as syntax errors, compile time errors, or diagnostic errors.
As data cannot be processed without some utility programs, object programs should be linked
with them to produce an executable program (load module), which can be executed by the
computer. This job is done by another system program called a linkage editor (linker). When
required utility programs are not available or when utility programs cannot be linked with the
object program properly, an executable program cannot be produced. These errors are described
as link errors.
When the executable program cannot be executed, such errors can be described as run-time
errors or execution-time errors.
When an executable program is executed and if it produces undesirable results it is due to some
errors in the program logic or algorithm. Such errors are described as logical errors. Programmers
call these errors bugs, and the process of locating and correcting them is referred to as
debugging the program.
If syntax, link or run-time errors are available computer can detect those errors, but the logical
error should be detected by computer programmers.
During program testing, different types of test data (both valid and invalid) should be used as
input data.
5. Program implementation:
If program testing provides satisfactory results, the executable program can be used to handle
data processing activities of the organization in the real environment. This is called program
implementation.
Program updating means making structured changes to the existing programs or introducing a
new set of programs to meet new data processing requirements of the organization.
7. Program documentation:
Program documentation means to keep or record information related to all the activities of the
computer programming.
Although documentation appears as the last step in the programming process, it is actually
performed throughout the entire process.
Documentation consists of materials generated during each step. E.g.: problem analysis report,
algorithm, program listing, test reports, maintenance and update information, user manuals and
training materials.
Week 3
Algorithm
Algorithm is a detailed step-by-step solution to a problem.
An algorithm must have some characteristics: must be precise (unambiguous); must be effective;
must have a finite number of instructions; execution must always terminate.
There are number of design tools that a programmer can use to develop the algorithm: flowchart,
pseudo code, decision trees, decision tables, structure diagrams etc.
Flowcharts:
Program flowcharts can be described as a pictorial or graphical method to represent an algorithm or
processing logic.
This traditional method uses the following standard symbols:
Predefined
Start / Stop Process Input/Output Decision Direction of flow Connector
Process
This traditional flow chart may lead to very unstructured program code. Structured flow charts are a
development of the original flow chart idea, but recognizing the three constructs of sequence,
selection and iteration.
Example: A flow chart for finding the largest number of ten given numbers.
Start
L←A
C ←1
True
A>L
False L←A
C←C+1
True
C <10
False
Output L
Stop
Pseudo Code:
Pseudo code, sometimes called structured English, is a nonstandard English-like language that lets
you specify your algorithm with more precision than you can in plain English but with less precision
than is required with a formal programming language.
In this method standard words of the natural language English with mathematical notations are used
to illustrate an algorithm.
Example: A pseudo code for finding the largest number of ten given numbers.
Start
Accept the first number A
L←A
C←1
Repeat
Accept the next number A
If A>L then L←A
C←C+1
Until C>=10
Display L
Stop
Week 4 & 5
C++ Programming Language
C++ is case sensitive, and all C++ keywords must be written in lower case.
Every C++ statement ends in a semicolon (;).
Data types:
The following types of data can be stored and handled by C++.
Type Range Bytes Represents
From To
char / short -128 127 1 Characters
unsigned char 0 255 1 Characters
int -32,768 32,767 2 Whole numbers
unsigned int 0 65,535 2 Whole numbers
long -2,147,438,648 2,147,438,648 4 Whole numbers
unsigned long 0 4,294,967,295 4 Whole numbers
float (-) 3.4 x 10-38 (-)3.4 x 1038 4 Fractional numbers
double (-)1.7 x 10-308 (-)1.7 x 10308 8 Fractional numbers
long double (-)3.4 x 10-4932 (-)3.4 x 104932 10 Fractional numbers
There is also a data type called void, which means no data type at all!
You may have noticed that there is no ‘string’ type in C++. This means we have to handle strings in
a rather indirect fashion, as will be explained later.
Assignment:
It just involves the equals (=) sign known as the assignment operator.
E.g: int x;
x = 4;
int y = 10;
y = 5;
Constants:
Constant is a named memory location to hold a particular type of data and the content of a constant
cannot be changed during the execution of the program.
This is done with the keyword const.
E.g.: const float PI = 3.141;
const int CHAR_BUFFER = 80;
It is common practice to write constant names in upper case to differentiate them from variable
names which are typically in lower case.
Arithmetic Operators:
Arithmetic operators are + , - , * , / and %(remainder).
The remainder operator has equal precedence with multiply and divide.
E.g.: int x = 4 + 2 * 3; //10
x = (4 + 2) * 3; //18
x = 5 / 3; //1
int y = 5 % 3; //2
Relational Operators:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Logical Operators:
&& AND
|| OR
! NOT
Functions:
C++ programs are basically just a series of functions which are able to call each other.
The general format of a C++ function is,
return_type function_name(data_type parameter1, data_type parameter2, …)
{
function_body
}
The return type of a function is int by default, so if no return type is declared, the compiler expects
the function to return an integer.
If no data is to be returned from the function, then its type is declared as void.
The parameter list may also be void, when there are no parameters to the function, and the brackets
may be left empty if this is the case.
Any function which is not void must contain a return statement as the last statement in the function.
E.g.: int sqr(int value_in)
{
int squared=value_in*value_in;
return squared;
}
The return statement may return the result of an expression directly instead of via a variable.
E.g.: int sqr(int value_in)
{
return value_in*value_in;
}
Example:
void main()
{
int x;
int y;
int z;
x=4;
y=2;
z=x+y;
}
You could even compile, link and run this program, but we can’t see any output.
Output:
Unfortunately C++ has no I/O syntax.
C++ has its own set of I/O library syntax defined in a header file called iostream.h.
We must include this header file in our program before main, as follows.
#include <iostream.h>
To output data onto the screen, we use the word cout followed by the insertion / put to operator
(<<).
E.g.: cout<<x;
cout<<“This is a string literal”;
cout<<“Value of x is: ”<<x<<“ Value of y is: ”<<y;
cout<<“Value of x is: ”<<x<<endl<<“ Value of y is: ”<<y<<endl; //endl forces a line feed
Example:
#include <iostream.h>
void main()
{
int x;
int y;
int z;
x=4;
y=2;
z=x+y;
cout<<"Value of z is "<<z<<endl;
}
Output:
Value of z is 6
Input:
To input data from the keyboard, we use the word cin followed by the extraction / get from operator
(>>).
E.g.: cin>>x;
cin>>x>>y;
cout<<“Enter a number: ”; cin>>x;
Example:
#include <iostream.h>
void main()
{
int x,y,z;
cout<<"Please enter an integer: ";
cin>>x;
cout<<"Please enter the second integer: ";
cin>>y;
z=x+y;
cout<<"Total is "<<z<<endl;
}
Output:
Please enter an integer: 4
Please enter the second integer: -6
Total is -2
Comments:
There two ways of writing comments in C++.
// This is a single line comment
and
/* This is a
multi line comment */
Week 6 & 7
Structured Programming:
Programming that produces programs with clean flow, clear design, and a degree of modularity or
hierarchical structure is called structured programming. The three basic constructs in structured
programming are sequence (ordered set of statements), selection (conditional branch), and iteration
(repletion / loop). There is no GOTO statement to jump to any place in the program.
Example Problems and Solutions (Flow Chart, Pseudo Code and C++ Code)
1. Sequence: Output the average of three given numbers
Flow Chart: Pseudo Code:
Start start
input a,b,c
totalÅa+b+c
Input a,b,c avgÅtotal/3
output avg
total ← a+b+c stop
2. One-Way Selection (If Then): Output the biggest number of three given numbers
Flow Chart: Pseudo Code:
Start start
input a,b,c
bigÅa
Input a,b,c if big<b then bigÅb
if big<c then bigÅc
big ← a output big
stop
True
big<b
C++ Code:
big ← b #include <iostream.h>
False
void main()
{
True int a, b, c, big;
big<c
cout<<"Enter three numbers :";
big ← c cin>>a>>b>>c;
False
big=a;
if (big<b)
Output big
{
big=b;
};
Stop if (big<c)
{
big=c;
};
cout<<"The big number is "<<big<<endl;
}
3. Two-Way Selection (If Then Else): Output the big number of two given numbers
Flow Chart: Pseudo Code:
Start start
input a,b
if a>b then big=a
Input two numbers a, b else big=b
output big
True stop
a>b
False C++ Code:
big ← b big ← a #include <iostream.h>
void main()
{
Output big int a, b, big;
cout<<"Enter two numbers :";
Stop
cin>>a>>b;
if (a>b)
{
big=a;
}
else
{
big=b;
}
cout<<"The big number is "<<big<<endl;
}
4. Multi-Way Selection (If Then ElseIf ElseIf ………… Else): Output the grade for a given marks
Flow Chart: Pseudo Code:
Start start
input marks
if marks≥75 then gradeÅ’A’
Input marks else if marks≥60 then gradeÅ’B’
else if marks≥40 then gradeÅ’C’
True else gradeÅ’F’
marks≥75 grade ← ‘A’
output grade
False stop
True
marks≥60 grade ← ‘B’ C++ Code:
#include <iostream.h>
False
void main()
True {
marks≥40 grade ← ‘C’
int marks;
False char grade;
cout<<"Enter the marks: ";
grade ← ‘F’ cin>>marks;
if (marks>=75)
grade=’A’;
Output grade else if (marks>=60)
grade=’B’;
Stop
else if (marks>=40)
grade=’C’;
else
grade=’F’;
cout<<"The grade is "<<grade<<endl;
}
5. Multi-Way Selection (Case): Output the answer of a given simple expression like '5 + 9'.
Flow Chart: Pseudo Code:
Start
start
input x, op, y
case op of
Input x, op, y '+': x = x+y
'-': x = x-y
True '*': x = x*y
op=’+’ x ← x+y
'/': x = x/y
False '%': x = x%y
else : output “Invalid”
True output x
op=’-‘ x ← x-y
stop
False
C++ Code:
False
i≤num #include <iostream.h>
True void main()
{
f←f*i int num,fact,i;
i←i+1 cout<<"Enter a number: ";
cin>>num;
fact=1;
Print f for (i=2; i<=num; i++)
fact=fact*i;
Stop cout<<"The factorial of "<<num<<
" is "<<fact<<endl;
}
7. While Loop: Accept numbers until the user enters a 999 and output the sum of the given
numbers
Flow Chart: Pseudo Code:
Start
Start
s←0
Read the first number n
s←0 while n<>999
s←s+n
Read the first number n Read the next number n
end while
Print s
False Stop
n <>999
True C++ Code:
#include <iostream.h>
s←s+n void main()
{
int s=0,n;
Read the next number n cout<<"Enter the first number: ";
cin>>n;
while (n !=999)
Print s {
s=s+n;
cout<<"Enter the next number: ";
Stop
cin>>n;
}
cout<<"The sum is "<<s;
}
8. Do While Loop: Accept numbers until the user enters a 999 and output the sum of the given
numbers
Flow Chart: Pseudo Code:
Start
Start nÅ 0
sÅ0
n←0 do
s←0 sÅs+n
Read the next number n
while n<>999
s←s+n Print s
Stop
9. Until Loop: Accept numbers until the user enters a 999 and output the average of the given
numbers
Flow Chart: Pseudo Code:
Start Start
nÅ 0
sÅ0
n←0
repeat
s←0
sÅs+n
Read the next number n
until n=999
s←s+n Print s
Stop
Fals
n=999
True
Print s
Stop
Typical Outputs:
Enter the lengths of the sides of a triangle :3 4 5
It can be a triangle
Example:
#include <iostream.h>
void main()
{
char c;
cout<<"Enter a character :";
cin>>c;
switch (c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': cout<<"It's a vowel"; break;
default: cout<<"It's not a vowel";
}
}
Typical Outputs:
Enter a character :i
It's a vowel
Enter a character :f
It's not a vowel
Example:
#include <iostream.h>
void main()
{
int i;
for (i=1; i<10; i++)
cout<<"The square of "<<i<<" is "<<i*i<<endl;
}
Output:
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
Example:
#include <iostream.h>
void main()
{
int i,j;
for (i=1; i<=5; i++)
{
for (j=1; j<=i; j++)
cout<<i;
cout<<endl;
}
}
Output:
1
22
333
4444
55555
Exercise:
Draw a flow chart, write a pseudo code and write a C++ program to output the number of even
numbers among the numbers entered by the user.
Week 8
Calling Functions
Functions are called (made to execute) by their names, followed by the appropriate parameter
arguments.
Example:
#include <iostream.h>
void sqr(int value_in)
{
cout<<value_in*value_in<<endl;
}
void main()
{
int x=5;
sqr(x);
cout<<x;
}
Output:
25
5
If a function gives a return value, then it should be called so that the return value is used.
Example:
#include <iostream.h>
int sqr(int value_in)
{
int squared=value_in*value_in;
return squared;
}
void main()
{
int x=5;
int y=sqr(x); //The returned value is assigned to a variable
cout<<"Square of "<<y<<" is "<<sqr(y); //The returned value is printed on the output screen
}
Output:
Square of 25 is 625
Example:
#include <iostream.h>
void sqr(int value_in)
{
value_in=value_in*value_in;
cout<<value_in<<endl;
}
void main()
{
int x=5;
sqr(x);
cout<<x;
}
Output:
25
5
C++ also has a simple pass by reference syntax, which allows the actual variable rather than a copy
to be passed to a function.
The syntax for a pass by reference parameter is to add the ampersand character (&) to the end of
the data type.
Example:
#include <iostream.h>
void sqr(int& value_in)
{
value_in=value_in*value_in;
cout<<value_in<<endl;
}
void main()
{
int x=5;
sqr(x);
cout<<x;
}
Output:
25
25
Example:
#include <iostream.h>
void swap(int& first, int& second)
{
int temp;
temp=first;
first=second;
second=temp;
}
void main()
{
int x=5;
int y=10;
cout<<"x = "<<x<<" y = "<<y<<endl;
swap(x,y);
cout<<"x = "<<x<<" y = "<<y;
}
Output:
x = 5 y = 10
x = 10 y = 5
Prototyping Functions:
The prototype is simply the declaration of the function’s name and data types so that the compiler
can ensure that any calls to the functions are made with appropriate values.
E.g.: int sqr(int value_in) //Prototype
…
void main() //or some other function
{
…
int a=sqr(10); //Function call
…
}
int sqr(int value_in) //Declarator
{
return value_in*value_in;
}
Example:
#include <iostream.h>
void main()
{
int x=5;
int y=sqr(x);
cout<<"Square of "<<x<<" is "<<y;
}
Output:
Square of 5 is 25
Note that the prototype does not have to name the parameter(s); and indeed may even use a
different identifier to that used in the declarator.
Our prototype above might equally have appeared as int sqr(int) or int sqr(int a_value).
However, to aid readability, it is good practice to use a consistent identifier in both the prototype and
the declarator.
Example:
#include <iostream.h>
int isADigit(char)
void main()
{
char buffer[80];
int digit_count;
char answer;
do
{
digit_count=0;
cout<<"Enter a string of characters: ";
cin>>buffer;
for (int i=0; buffer[i]!='\0'; i++)
{
if (isADigit(buffer[i]))
{
digit_count++;
}
}
cout<<"Total number of digits in the string: "<<digit_count<<endl;
cout<<"Try another string(y/n)? ";
cin>>answer;
cout<<endl;
}
while (answer!='n' && answer!='N');
}
int isADigit(char c)
{
if (c>=48 && c<=57)
{
return 1;
}
else
{
return 0;
}
}
Output:
Enter a string of characters: ab2cd56%@*34
Total number of digits in the string: 5
Try another string(y/n)? y
Week 9
Arrays
Array declaration:
In C++, arrays are declared and accessed by the use of square brackets.
E.g.:
(a) One-dimension array
int num[10];
0 1 2 3 4 5 6 7 8 9
num
num[3] num[8]
C++ has no bounds checking, so the compiler will let you refer to array elements even if they are
outside the declared range.
For example, we could refer to num[20].
The moral is, be very careful never to use an array element which has not been explicitly declared
as part of the allowed range.
Initializing Array:
We may put values into any individual element of an array using the assignment operator.
E.g.: int num[10]; num[4]=99;
int num[10]={3,99,2,-4,6,29,84,4,-7,25};
int num[]={3,99,2,-4,6,29,84,4,-7,25}; //The compiler can automatically size the array
If we try to display a numeric array using cout (i.e. cout<<num;) then we will see that what is
displayed is the address of the first element of the array.
void main()
{
const int ARRAY_SIZE=15;
int an_array[ARRAY_SIZE];
setArraySize(ARRAY_SIZE,an_array);
cout<<"The first element is "<<an_array[0]<<endl;
}
Output:
The first element is 15
Week 10
Pointers
A pointer points to a memory location which contains data of a particular type.
Therefore, the content of a pointer is not data but the address of some data.
A pointer is declared by the use of an ‘*’ after the data type.
E.g.: int* ip; //ip is a pointer to an integer
ip 0x46cd46f1
435
ip
0x46cd46ef
0x46cd46f0
0x46cd46f1
435
0x46cd46f2
0x46cd46f3
0x46cd46f4
0x46cd46f5
This typing of data is important since a pointer is a variable which can undergo certain arithmetic
operations such as ‘++’ which moves a pointer to the next item of data.
Since different data types occupy different sizes of memory block, the data type of the pointer
defines how many bytes the pointer must be incremented.
Unlike arrays, pointers may be used as the return type of a function.
One very common application of both arrays and pointers is the representation of strings of
characters.
Output:
Variable is 4
Pointer is 0x6317241a
De-referenced pointer is 4
Output:
String is C++
De-referenced char pointer is C
String after incrementing is ++
De-referenced char pointer is now +
Strings
Unlike some other languages, there is no ‘string’ data type in C++.
We can only represent strings of characters in two rather indirect ways:
1. As arrays of type char
2. By pointers of type char
If astring was to contain the string ‘characters’ then the terminating ‘\0’ would be lost.
astring c h a r a c t e r s
Any attempt to display or copy this string would cause problems since the string has an undefined
length, and the program would simply display or copy the contents of all memory locations after the
string until a ‘\0’ was encountered.
To initialize a character array with a string literal, we can use the assignment operator (=) and {}.
E.g.: char astring[]={“hello”};
We cannot assign a string literal to a character array after it has been declared - this can only be
done one character at a time.
Example:
#include <iostream.h>
void main()
{
char astring[4]={"abc"};
char bstring[4];
//bstring={"xyz"} will not compile
bstring[0]='x';
bstring[1]='y';
bstring[2]='z';
bstring[3]='\0';
cout<<astring<<endl;
cout<<bstring<<endl;
}
Output:
abc
xyz
Likewise, if we want to make one array of characters equal to another, then unfortunately the
assignment operator cannot be used.
E.g.: bstring = astring is not allowed
So, to copy the contents of astring into bstring, we can use strcpy(destination, source) and
strncpy(destination, source, num_chars) of the header file string.h
E.g.: strcpy(bstring,astring);
strncpy(bstring,astring,9);
Example:
#include <iostream.h>
#include <string.h>
void main()
{
char astring[20];
char bstring[10];
cout<<"Enter a string (upto 19 characters): ";
cin>>astring;
cout<<astring<<endl;
strncpy(bstring,astring,9);
bstring[9]='\0'; //This is important
cout<<bstring<<endl;
}
Output:
Enter a string (upto 19 characters): Superconductivity
Superconductivity
Supercond
Output:
char array
Output:
spring
summer
winter
winter
winter
fall
The following figure shows what happens when we execute the above program.
s
p
Step1
r
a i
n
b g
\0
Step2
s
u
m
m
e
r
\0
a
Step3 u
c t
u
Step5 m
n
d \0
Step4 w
i
n
Step6 t
e
r
\0
f
a
l
l
\0
Using the assignment operator with char pointers should only be used for short term process.
For safe storage of strings arrays are more reliable.
It is possible to use strcpy or strncpy with character pointers to copy data rather than address.
However, this is not a recommended approach since we may overwrite data in subsequent memory
locations.
It will happen if we declare a char pointer to point to a string of one length and then copy a longer
string to it.
Since char pointer only points to the address of one character, what may be in the subsequent
memory locations is unpredictable.
Example:
#include <iostream.h>
#include <string.h>
void main()
{
char* a="fall";
char* b="winter";
char* c="summer";
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl<<endl;
strcpy(b,a);
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl<<endl;
strcpy(a,c);
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl<<endl;
}
Output:
fall
winter
summer
fall
fall
summer
summer
r
summer
Week 11 & 12
Object-Oriented Programming (OOP):
In a programming environment, an object is a self-contained unit that contains both data and related
functions – the instructions to act on the data. An object can be some physical/tangible/visible thing
in the real world, event, etc. An object is never a value (e.g. name), a process (e.g.: sort), or time
(e.g.: 5 minutes).
Information hiding is a design practice in which implementation details for both data structures and
algorithms within a module are hidden from routines using that module, so as to ensure that those
routines do not depend on some particular detail of the implementation.
The word used to describe an object’s self-containment is encapsulation. An object encapsulates
both data and its related functions.
Abstraction is the process of reducing an object to its essence so that only the necessary elements
are represented. Abstraction defines an object in terms of its properties (attributes), behaviors
(methods-functionalities), and interface (message -means of communicating with other objects).
In an object, the facts that describe the object are called attributes, and the functions that tell the
object to do something are called methods or operations.
A class is a generalized category that describes a group of similar objects. You can think of a class
as a set of plans to create objects.
An object is called an instance or occurrence of a class. E.g.: your pet kitty Pussy is an instance of
the class Cat.
In most cases, methods are activated by an outside stimulus, called a message, which results in the
change of the state of an object. E.g.: a ‘move’ message would cause a boat object to activate its
‘move’ method, which would change the value of its ‘location’ attribute.
An object in a subclass automatically posses all the attributes of the class from which it was derived;
this property is called inheritance.
When a message is sent, the property of polymorphism allows an individual object to know how,
using its own methods, to process the message in the appropriate way for that particular object.
E.g.: when the message ‘move’ is received, an object of the class ‘SailBoat’ knows that it is
supposed to move under sail power, and a ‘PowerBoat’ knows that it moves by use of an engine.
public:
void setX(int x_in)
{
x=x_in;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
public:
void setX(int x_in);
void setY(int y_in);
int getX();
int getY();
};
int Point::getX()
{
return x;
}
int Point::getY()
{
return y;
}
Note that the method definitions, unlike the class definition, do not end in a semicolon (;).
Instantiating Objects:
An object is instantiated in C++ by declaring its type, followed by its name, like other data types.
E.g.: int x; //x is a variable of type int
public:
void setX(int x_in);
void setY(int y_in);
int getX();
int getY();
};
int Point::getX()
{
return x;
}
int Point::getY()
{
return y;
}
void main()
{
Point p1,p2,p3;
p1.setX(10); p1.setY(10);
p2.setX(15); p2.setY(25);
p3.setX(15); p3.setY(30);
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
}
Output:
The coordinate of the point 'p1': (10,10).
We can put the class definition in a separate header file [e.g.: points.h] and this user-defined header
file can be included in any program [e.g.: #include “points.h”].
Example:
#include <iostream.h>
#include "points.h"
void main()
{
Point p1,p2,p3;
p1.setX(10); p1.setY(10);
p2.setX(15); p2.setY(25);
p3.setX(15); p3.setY(30);
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
}
Constructor:
Whenever an object is instantiated, a method known as the constructor is called to reserve memory
for that object.
A default constructor is called if no user-defined constructor is provided in the class definition, but it
has limited application since it only allocates memory for the object being instantiated.
An object constructor in C++ has three important aspects.
1. It takes the same name as the class.
2. It may take arguments.
3. It cannot return a value [including void].
Example:
#include <iostream.h>
class Point
{
private:
int x;
int y;
public:
Point();
void setX(int x_in);
…
};
Point::Point()
{
x=0;
y=0;
}
void main()
{
Point p1,p2,p3;
p1.setX(10); p1.setY(10);
p2.setX(15); p2.setY(25);
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
}
Output:
The coordinate of the point 'p1': (10,10).
The coordinate of the point 'p2': (15,25).
The coordinate of the point 'p3': (0,0).
Parameterized Constructers:
It is also possible to pass parameter arguments to a user-defined constructor.
This gives us the opportunity to create objects with different initial states.
Example:
#include <iostream.h>
class Point
{
private:
int x;
int y;
public:
Point(int x_in, int y_in);
void setX(int x_in);
…
};
void main()
{
Point p1(10,10),p2(100,100),p3(20,25);
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
}
Output:
The coordinate of the point 'p1': (10,10).
The coordinate of the point 'p2': (100,100).
The coordinate of the point 'p3': (20,25).
class Point
{
private:
int x;
int y;
public:
Point(int x_in, int y_in);
void setX(int x_in);
…
};
void main()
{
Point p1(10,10),p2(100,100),p3;
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
}
Output:
The coordinate of the point 'p1': (10,10).
The coordinate of the point 'p2': (100,100).
The coordinate of the point 'p3': (0,0).
In a method with more than one parameters, no parameters with default values are followed by
others without defaults.
E.g.: aFunction(int, int y=10) is okay, but aFunction(int x=10, int y) is not.
Copy Constructor:
To use the default copy constructor, all we need to express is that one new instantiated object
equals another object of the same class.
Example:
#include <iostream.h>
class Point
{
private:
int x;
int y;
public:
Point(int x_in, int y_in);
void setX(int x_in);
…
};
void main()
{
Point p1(10,10),p2(100,100),p3;
Point p4=p2;
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p4': ("<<p4.getX()<<","<<p4.getY()<<")."<<endl;
}
Output:
The coordinate of the point 'p1': (10,10).
The coordinate of the point 'p2': (100,100).
The coordinate of the point 'p3': (0,0).
The coordinate of the point 'p4': (100,100).
class Point
{
private:
int x;
int y;
public:
Point(Point& copied_point); //prototype for copy constructor
Point(int x_in, int y_in); //prototype for ordinary constructor
void setX(int x_in);
…
};
void main()
{
Point p1(10,10),p2(100,100),p3;
Point p4(p2);
cout<<"The coordinate of the point 'p1': ("<<p1.getX()<<","<<p1.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p2': ("<<p2.getX()<<","<<p2.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p3': ("<<p3.getX()<<","<<p3.getY()<<")."<<endl;
cout<<"The coordinate of the point 'p4': ("<<p4.getX()<<","<<p4.getY()<<")."<<endl;
}
Output:
The coordinate of the point 'p1': (10,10).
The coordinate of the point 'p2': (100,100).
The coordinate of the point 'p3': (0,0).
The coordinate of the point 'p4': (100,100).
Example:
#include <string.h>
#include <iostream.h>
class BankAccount
{
private:
int acc_num;
char acc_holder[20];
float curr_balance;
public:
BankAccount(float srart_balance);
void setAccNum(int num_in);
void setAccHolder(char* holder_in);
void deposit(float amount);
void withdraw(float amount);
int getAccNum();
char* getAccHolder();
float getCurrBalance();
};
BankAccount::BankAccount(float start_balance=0.00)
{
curr_balance=start_balance;
}
int BankAccount::getAccNum()
{
return acc_num;
}
char* BankAccount::getAccHolder()
{
return acc_holder;
}
float BankAccount::getCurrBalance()
{
return curr_balance;
}
void main()
{
BankAccount acc1,acc2(100);
acc1.setAccNum(10001);
acc1.setAccHolder("Mr. H. Simson");
acc2.setAccNum(10002);
acc2.setAccHolder("Ms. K.Green");
acc1.deposit(1500.00);
acc2.deposit(2250.00);
acc2.deposit(2000.00);
acc1.withdraw(1000.00);
acc1.deposit(400.00);
acc2.withdraw(3000.00);
cout<<"Acc.Number\tName\t\tBalance\n";
cout<<"---------------------------------------\n";
cout<<acc1.getAccNum()<<"\t\t"<<acc1.getAccHolder()<<"\t"<<acc1.getCurrBalance()<<endl;
cout<<acc2.getAccNum()<<"\t\t"<<acc2.getAccHolder()<<"\t"<<acc2.getCurrBalance()<<endl;
}
Output:
Acc.Number Name Balance
----------------------------------------------------
10001 Mr. H. Simson 900
10002 Ms. K.Green 1350
Exercise:
Create a C++ class to represent a person with attributes of name, year of birth, and height in
meters.
Define methods to get and set the values of these three attributes.
Add a method which will return a person’s approximate age when given a year as a parameter.
Add another method which will return the height in centimeters.
In the main method, use this class.
Week 13
The Lifetime of Named Objects:
1. Automatic Objects:
Automatic objects are instantiated inside the local scope of a function or other structure withits body
defined by braces.
E.g.: void main()
{
BankAccount acc1;
…
}
These will be visible anywhere inside the block.
They only exist while they are in scope.
The automatic object will be created and destroyed each time it falls in and out of scope.
2. External objects:
An external object is declared out side any function body.
E.g.: BankAccount acc1;
void main()
{
…
}
These are visible in any block in the same system.
These exist for the lifetime of the program.
3. Static Object:
A static object is declared, like an automatic object, within a local scope.
E.g.: void main()
{
static BankAccount acc1;
…
}
The static object will be initialized only once when the first time the function executes.
It can only be visible within the block but persist until the end of the program.
Example:
#include <iostream.h>
class Object
{
private:
int value;
public:
Object();
void addValue(int value_in);
int getValue();
};
Object::Object()
{
value=0;
}
int Object::getValue()
{
return value;
}
Object external_object;
void main()
{
external_object.addValue(5);
for (int i=0; i<2; i++)
{
Object auto_object;
auto_object.addValue(10);
static Object static_object;
static_object.addValue(15);
external_object.addValue(20);
cout<<"The automatic object has the value "<<auto_object.getValue()<<endl;
cout<<"The static object has the value "<<static_object.getValue()<<endl;
cout<<"The external object has the value "<<external_object.getValue()<<endl;
}
cout<<"The external object has the value "<<external_object.getValue()<<endl;
}
Output:
The automatic object has the value 10
The static object has the value 15
The external object has the value 25
The automatic object has the value 10
The static object has the value 30
The external object has the value 45
The external object has the value 45
Dynamic Objects:
External and static objects persist as long as the program in which they are declared and are
destroyed when it terminates.
An automatic object is destroyed when it passes out of scope.
We have no other control over the lifetimes of these objects.
If we are to exercise more control over the lifetime of objects, we need to be able to destroy objects
at will, as well as create them.
In other words we need to be able to call the destructor method as well as the constructor.
To handle the dynamic memory allocation of data, including objects, C++ includes the operators
new and delete.
These operators are used to dynamically call object constructors and destructors respectively via
the use of pointers.
It is important to note that Dynamic objects instantiated using new do not have name – they simply
occupy a memory space which may be referenced by a pointer.
Therefore it is called as unnamed object.
Example:
#include <string.h>
#include <iostream.h>
class BankAccount
{
private:
int acc_num;
char acc_holder[20];
float curr_balance;
public:
BankAccount(float srart_balance);
void setAccNum(int num_in);
void setAccHolder(char* holder_in);
void deposit(float amount);
void withdraw(float amount);
int getAccNum();
char* getAccHolder();
float getCurrBalance();
};
BankAccount::BankAccount(float start_balance=0.00)
{
curr_balance=start_balance;
}
void main()
{
BankAccount* acc_ptr1;
BankAccount* acc_ptr2;
acc_ptr1=new BankAccount;
acc_ptr1->setAccNum(20);
acc_ptr2=acc_ptr1;
acc_ptr1=new BankAccount;
acc_ptr1->setAccNum(30);
cout<<"Account number referenced by pointer1 is "<<acc_ptr1->getAccNum()<<endl;
cout<<"Account number referenced by pointer2 is "<<acc_ptr2->getAccNum()<<endl;
}
Output:
Account number referenced by pointer1 is 30
Account number referenced by pointer2 is 20
C++ includes the delete operator to destroy objects which have been instantiated dynamically using
new.
delete explicitly calls the destructor, which destroys the object currently referenced by the pointer.
E.g.: delete acc_ptr;
Note that this destroys the object (by freeing its memory), not the pointer.
Losing Objects:
If a pointer to an object created with the new operator is allowed to pass out of scope without the
delete operator being used, then the destructor will not be called.
The object will still exist but be lost – since it has no pointer to reference it, it will be unreachable.
In a large program, garbage objects such as this may eventually cause memory management
problems.
Destructor:
Destructor makes free the memory previously allocated to the deleted object.
Like the constructor, the destructor has certain characteristics:
1. It takes the same name as the class, preceded by the tilde character (~).
2. It cannot take arguments.
3. It cannot return a value.
Unlike constructors, there can only ever be one destructor per class.
Example:
#include <iostream.h>
#include <string.h>
class Object
{
private:
char name[20];
public:
Object(char* name_in);
~Object();
};
Object::Object(char* name_in)
{
strncpy(name,name_in,19);
name[19]='\0';
cout<<"Constructor called for "<<name<<endl;
}
Object::~Object()
{
cout<<"Destructor called for "<<name<<endl;
}
void main()
{
cout<<"Begining of main"<<endl;
{
Object auto_object("Atomatic Object");
static Object static_object("Static Object");
}
Object* obj_ptr=new Object("Dynamic Object");
delete obj_ptr;
cout<<"End of main"<<endl;
}
Output:
Constructor called for External Object
Begining of main
Constructor called for Atomatic Object
Constructor called for Static Object
Destructor called for Atomatic Object
Constructor called for Dynamic Object
Destructor called for Dynamic Object
End of main
Destructor called for Static Object
Destructor called for External Object
Example:
#include <iostream.h>
#include <string.h>
class Car
{
private:
char color[10];
public:
Car(char* color_in);
char* getColor();
};
char* Car::getColor()
{
return color;
}
void main()
{
Car* garage=NULL;
int menu_choice=0;
char temp_color[10];
while (menu_choice != 3)
{
Output:
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter color of car: Blue
Blue car is parked
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 2
Blue car is removed
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter color of car: Red
Red car is parked
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 3
Example:
#include <iostream.h>
#include <string.h>
class Car
{
private:
char color[10];
public:
Car(char* color_in);
char* getColor();
};
char* Car::getColor()
{
return color;
}
void main()
{
Car* garage[3]={NULL,NULL,NULL};
int menu_choice=0;
char temp_color[10];
int i,room_num;
while (menu_choice != 3)
{
cout<<"Enter 1 to put car in garage, 2 to remove it, 3 to quit: ";
cin>>menu_choice;
if (menu_choice ==1)
{
i=0;
while (garage[i]!=NULL && i<3)
{
i++;
}
if (i<3)
{
cout<<"Enter color of car: ";
cin>>temp_color;
garage[i]=new Car(temp_color);
cout<<garage[i]->getColor()<<" car is parked in "<<(i+1)<<" th room"<<endl;
}
}
if (menu_choice==2)
{
cout<<"Enter the room number to remove the car: ";
cin>>room_num;
if (garage[room_num-1]!=NULL)
{
cout<<garage[room_num-1]->getColor();
delete garage[room_num-1];
garage[room_num-1]=NULL;
cout<<" car is removed from "<<room_num<<" th room"<<endl;
}
}
}
cout<<"\nRoom No.\tColor\n";
for (i=0; i<3; i++)
{
cout<<(i+1)<<"\t\t";
if (garage[i]==NULL)
cout<<"No car\n";
else
cout<<garage[i]->getColor()<<endl;
}
Output:
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter color of car: Blue
Blue car is parked in 1 th room
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter color of car: Red
Red car is parked in 2 th room
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter color of car: Green
Green car is parked in 3 th room
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 2
Enter the room number to remove the car: 2
Red car is removed from 2 th room
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 1
Enter color of car: Black
Black car is parked in 2 th room
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 2
Enter the room number to remove the car: 1
Blue car is removed from 1 th room
Enter 1 to put car in garage, 2 to remove it, 3 to quit: 3
Exercise:
Declare an array which is able to act as a container for up to 20 BankAccount object pointers.
Using your array, create a program which allows the dynamic creation and destruction of bank
accounts.
Accounts should be opened and closed at will while the program is running.
Week 14 & 15
Inheritance:
Inheritance is the derivation of one class from another so that the attributes and methods of one
class are part of the definition of another class. Derived(Child) classes are always ‘a kind of’ their
base(parent) class.
We will begin with a very simple class which represents a single integer.
class BaseClass
{
private:
int x;
public:
void setX(int x_in)
{
x=x_in;
}
int getX()
{
return x;
}
};
In order for DerivedClass to inherit from BaseClass, the colon operator follows the class name, and
then the derivation type and the name of the class from which it inherits.
class DerivedClassName:public/private BaseClassName
public derivation is the more usual type.
It allows objects of a derived class access to the public part (usually the methods) of the base class
as well as its own class.
private derivation is less common, and means that a derived class object may only use the methods
defined in the derived class, not those inherited from the base class.
However, derived class methods may utilize base class methods to implement their own behavior.
class DerivedClass:public BaseClass
{
private:
int y;
public:
void setY(int y_in)
{
y=y_in;
}
int getY()
{
return y;
}
};
Objects of the BaseClass will have the attributes and methods of the BaseClass only, but
DerivedClass objects will have both these and the attributes and methods defined in the
DerivedClass.
#include <iostream.h>
void main()
{
BaseClass base_object;
DerivedClass derived_object;
base_object.setX(7);
//base_object.setY(5); will not be compiled
derived_object.setX(12);
derived_object.setY(1);
cout<<"base x = "<<base_object.getX()<<endl;
cout<<"derived x = "<<derived_object.getX()<<endl;
cout<<"derived y = "<<derived_object.getY()<<endl;
}
The output from the program looks like:
base x = 7
derived x = 12
derived y = 1
The previous program demonstrated that an object of a derived class can use the public methods of
a class from which it inherits.
It cannot, however, access the private attributes of the base class, and neither can its methods.
The protected keyword allows derived class access to attributes inherited from a base class, without
making them public.
Example:
class BaseClass
{
protected:
int x;
public:
void setX(int x_in)
{
x=x_in;
}
int getX()
{
return x;
}
};
#include <iostream.h>
void main()
{
BaseClass base_object;
DerivedClass derived_object;
base_object.setX(7);
//base_object.setY(5); will not be compiled
derived_object.setX(12);
derived_object.setY(1);
cout<<"base x = "<<base_object.getX()<<endl;
cout<<"derived x = "<<derived_object.getX()<<endl;
cout<<"derived y = "<<derived_object.getY()<<endl;
derived_object.xEqualsY();
cout<<"derived x = "<<derived_object.getX()<<endl;
}
Output:
base x = 7
derived x = 12
derived y = 1
derived x = 1
Inheriting Constructors:
A derived class will always inherit the constructor of the base class, as well as having its own.
Here the constructor of the base class is called first, and then the constructor of the derived class is
called.
Example:
#include <iostream.h>
#include <string.h>
class Customer
{
private:
char name[30];
public:
Customer();
char* getName();
};
Customer::Customer()
{
cout<<"Enter the name of the customer: ";
cin>>name;
}
char* Customer::getName()
{
return name;
}
AccountCustomer::AccountCustomer()
{
cout<<"Enter the account number: ";
cin>>account_no;
}
int AccountCustomer::getAccNo()
{
return account_no;
}
void main()
{
Customer c;
AccountCustomer ac;
cout<<c.getName()<<endl;
cout<<ac.getName()<<" "<<ac.getAccNo()<<endl;
}
Output:
Enter the name of the customer: Ravi
Enter the name of the customer: Rathi
Enter the account number: 10001
Ravi
Rathi 10001
If the base class constructor takes no parameters, then this inheritance of the constructor is implicit,
but if it does take parameters, then these must be stated explicitly in each derived class.
Example:
#include <iostream.h>
#include <string.h>
class Customer
{
private:
char name[30];
public:
Customer(char* name_in);
char* getName();
};
Customer::Customer(char* name_in)
{
strncpy(name,name_in,29);
name[29]='\0';
}
char* Customer::getName()
{
return name;
}
int AccountCustomer::getAccNo()
{
return account_no;
}
void main()
{
Customer c("Ravi");
AccountCustomer ac("Rathi",10001);
cout<<c.getName()<<endl;
cout<<ac.getName()<<" "<<ac.getAccNo()<<endl;
}
Output:
Ravi
Rathi 10001
Example:
#include <iostream.h>
class Employee
{
protected:
static int emp_count;
int personal_id;
char name[30];
public:
Employee();
int getPersonalId();
char* getName();
};
int Employee::emp_count;
char factory_section;
float hourly_rate;
public:
HourlyPaid();
char getFactorySection();
float getHourlyRate();
void changeFactorySection(char new_section);
void changeHourlyRate(float new_rate);
};
Employee::Employee()
{
emp_count++;
personal_id=emp_count;
cout<<"Enter employee name: ";
cin>>name;
}
int Employee::getPersonalId()
{
return personal_id;
}
char* Employee::getName()
{
return name;
}
Director::Director()
{
cout<<"Enter shareholding for "<<name<<": ";
cin>>shareholding;
}
int Director::getShareholding()
{
return shareholding;
}
SalariedWorker::SalariedWorker()
{
cout<<"Enter annual salary for "<<name<<": ";
cin>>annual_salary;
}
float SalariedWorker::getAnnualSalary()
{
return annual_salary;
}
int SalariedWorker::getDepartmentNo()
{
return department_no;
HourlyPaid::HourlyPaid()
{
cout<<"Enter hourly rate for "<<name<<": ";
cin>>hourly_rate;
}
char HourlyPaid::getFactorySection()
{
return factory_section;
}
float HourlyPaid::getHourlyRate()
{
return hourly_rate;
}
void main()
{
const int DIRECTORS=2;
const int SALARIED=2;
const int MANUAL=4;
Director directors[DIRECTORS];
SalariedWorker salaried[SALARIED];
HourlyPaid hourly[MANUAL];
int i=0;
Output:
Enter employee name: Black
Enter shareholding for Black: 500
Enter employee name: White
Enter shareholding for White: 150
Enter employee name: Brown
Enter annual salary for Brown: 20000
Enter employee name: Green
Enter annual salary for Green: 15000
Enter employee name: Scarlet
Enter hourly rate for Scarlet: 5
Enter employee name: Magenta
Enter hourly rate for Magenta: 7
Enter employee name: Mysteron
Enter hourly rate for Mysteron: 3
Enter employee name: Indestuctible
Enter hourly rate for Indestuctible: 4
Inheriting Destructors:
Derived classes also inherit the destructors of the base classes.
Here the destructor of the derived class is called first, and then the destructor of the base class is
called.
Exercise:
The followings are the two class definitions (attributes only).
class TextBook
{
private:
char titile[30];
char auther[30];
char publisher[30];
char isbn[20];
};
class Magazine
{
private:
char title[30];
char editor[30];
char publisher[30];
};
Define a base class Book from which TextBook and Magazine can be derived.
With appropriate methods complete the class definitions.