You are on page 1of 55

Introduction to Programming (C++) J.

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

Advanced Technological Institute 1 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Advanced Technological Institute 2 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Some Commonly Used High-Level Languages:


FORTRAN (Formula translator) was developed by IBM and introduced in 1954. It was the first high-
level language. It is very good at representing complex mathematical formulas.
ALGOL (Algorithmic Language) was the first structured procedural programming language
developed in late 1950s.
COBOL (Common business oriented language) is a verbose (wordy), English-like compiled
programming language developed between 1959 and 1961 and still in widespread use, especially in
business applications typically run on mainframes. It is very good for processing large, complex data
files and for producing well-formatted business reports.
RPG (Report program generator) was developed by IBM in 1965 to allow rapid creation of reports
from data stored in the computer files.
BASIC (Beginners all purpose symbolic instruction code) was originally developed by Dartmouth
College professors John Kemeny and Thomas Kurtz in 1965 to teach programming to their
students.
Pascal was designed between 1967 and 1971 by Niklaus Wirth. It is a compiled, structured
language built upon ALGOL, simplifies syntax while adding data types and structures such as sub
ranges, enumerated data types, files, records, and sets.
C was created in 1972. One of the C’s primary advantages is its portability: There are C compilers
for almost every combination of computer and operating system available today.
C++ is an object-oriented version of C, developed in the early 1980s.
Java is a network-friendly object-oriented programming language derived from C++ that permits a
piece of software to run directly on many different platforms. Java programs are not compiled
directly into machine language, but into an intermediate language called bytecode. This bytecode is
then executed by a universal platform, called the JVM (Java Virtual Machine), which sits atop a
computers regular platform. The JVM interprets (translates) compiled Java code into instructions
that the platform underneath can understand. Java provides high level of security to the user and
the network. Java uses Unicode coding system, which allows displaying all character sets in a
uniform manner. Web pages can include Java mini programs, called applets, which run on a Java
platform included in the user’s Web browser.
Visual Basic (VB) was introduced by Microsoft in 1987 as its first visual development tool. It allows
the programmer to easily create complex user interfaces containing standard Windows features,
such as buttons, dialog boxes, scrollbars, and menus. VB enables the user to control program
execution. This type of program is referred to as being event-driven. The ability to create user-
friendly event-driven programs with attractive Windows-like interfaces quickly has resulted in VB
becoming one of the most popular programming languages. VB can also be thoroughly integrated
with Microsoft Office to customize programs.
Perl (Practical Extraction and Report Language) is an interpreted language, based on C and several
UNIX utilities. Perl has powerful string handling features for extracting information from text files.
Perl can assemble a string and send it to the shell as a command; hence, it is often used for system
administration tasks. A program in Perl is known as a script.

Classification of Currently Available Languages according to The Programming Style:


1. Procedural/Imperative Languages: These consist of explicit instructions that describe the step-by-
step procedure to solve the problem. These are formed from collection of basic commands
(assignments, input, output, etc) and control structures (selection, iteration, etc.). E.g.: C, Pascal,
FORTRAN, Assembly, etc.
2. Nonprocedural languages: These are a programming languages that do not follow the procedural
paradigm (pattern) of executing statements, subroutine calls, and control structures sequentially
but instead describes a set of facts and relationships and then is queried for specific results.

Advanced Technological Institute 3 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Basic Questions when Selecting a Suitable Computer Language:


1. How readable is the language, to humans?
2. How easy is it to write the program in this particular language?
3. How reliable is the language?
4. How much would it cost to develop using a given language?
5. How complicated is the syntax going to be?
6. Does the language have standards for greater readability? For instance Java has standards for
naming, commenting and capitalization.

Stages of Computer Programming:


1. Analyzing and defining the problem:
In some organizations, programmers receive asset of specifications from system analysts. In
others, the programmers meet directly with users to analyze the problem and determine the
user’s needs.
In either case, the task of problem definition involves determining the input and output.
Finally, you produce a written agreement that specifies, in detail, the input data, the required
output, and the processing required converting the input into the output.

2. Program design or planning the solution:


The next step is to design an algorithm, a detailed, step-by-step solution to the 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.
After completing the algorithm design, the programmer should perform a process, called desk-
checking or dry-run, to verify that it produces the desired result. This involves sitting down with a
pencil and paper and ‘playing computer’ by carrying out each step of the algorithm in the
indicated sequence.

3. Program coding:

Advanced Technological Institute 4 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

4. Program testing and debugging:


The following diagram illustrates the steps in preparing a program for execution. During these
steps computer programs should be checked for program errors.

Program development Source Program Logical errors


[Original Program] Data

Translation Compiler Syntax errors

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.

6. Program maintenance and update:


Program maintenance means to make simple corrective actions in order to run the computer
program to meet data processing requirements of the organization. Generally software
maintenance agreements can be signed or in-house maintenance personnel can be used for
program maintenance.

Advanced Technological Institute 5 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

The Characteristics of a Good Computer Program:


1. Reliability: The program should provide correct results at all times and should be free from errors.
2. Maintainability: The existing program should be able to change or modify to meet new
requirements.
3. Portability: The program should be able to transfer to a different computer system.
4. Readability: The program must be readable and understandable with the help of documentation.
5. Performance: The program should handle the task more quickly and efficiently.
6. Storage saving: The program should be written with the least number of instructions.

Advanced Technological Institute 6 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Input the first number A

L←A
C ←1

Input the next number A

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

Advanced Technological Institute 7 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

The Escape Sequence Characters:


A character constant in a C++ program may also be an escape sequence if preceded by ‘\’.
Although these may appear to contain two characters, they still represent single characters.
Newline \n Carriage return [Home] \r Question mark \? Octal number \ooo
Horizontal tab \t Form feed [Top of next page] \f Single quote \’ Hex number \xhhh
Vertical tab \v Bell \a Double quote \”
Backspace \b Backslash \\ Integer 0 \0
The character ‘Z’ for example can be represented by any of the following:
Decimal: 90
Octal: ‘\132’
Hexadecimal: ‘\x5A’

Declaring Variables in a Program:


Variable is a named memory location to hold a particular type of data and the content of a variable
can be changed during the execution of the program.
Variables are declared in a C++ program by following the type name with the variable name.
E.g.: char ch;
int item_no;
float x;

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.

Advanced Technological Institute 8 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Unary Operator Shorthand:


These convert what would be dyadic expressions (more than one operands) to unary.
E.g.: int counter =1;
counter++; //counter = counter + 1;
counter--; // counter = counter - 1;

Other Expression Shorthand:


We also have shorthand for changing the value of a variable by arithmetic on its existing value.
In general terms variable_name = variable_name ? n can be replaced with variable_name ?= n
where ‘?’ means any one of the five arithmetic operators.
E.g.: counter += 5; //counter = counter + 5;
counter -= 3; //counter = counter - 3;
counter *= 5; //counter = counter * 5;
counter /= 4; //counter = counter / 4;
counter %= 3; //counter = counter % 3

Prefix and Postfix Notation:


Postfix notation: counter++ or counter--
Prefix notation: ++counter or --counter
In prefix notation, the operator will execute before the rest of the expression, but in postfix notation it
will be executed afterwards.
E.g.: int ctr = 1;
int x = ctr++; //x = 1 and ctr = 2
int y = ++x; //y = 2 and y = 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.

Advanced Technological Institute 9 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

The main Function:


All C++ programs start executing at a special function called main.
It frequently looks like,
void main()
{

}

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

Advanced Technological Institute 10 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Advanced Technological Institute 11 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

avg ← total/3 C++ Code:


#include <iostream.h>
void main()
Output avg
{
int a, b, c, total;
Stop float avg;
cout<<"Enter three numbers :";
cin>>a>>b>>c;
total=a+b+c;
avg=total/3;
cout<<"The average is "<<avg<<endl;
}

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

Advanced Technological Institute 12 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Advanced Technological Institute 13 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

True C++ Code:


op=’*’ x← x*y #include <iostream.h>
False void main()
{
True int x,y;
op=’/’ x← x/y
char op;
False cout<<"Enter a simple expression like '5
+ 9' : ";
True cin>>x>>op>>y;
op=’%’ x← x%y
switch (op)
False {
case '*': x *= y; break;
Output “Invalid” case '/': x /= y; break;
case '+': x += y; break;
case '-': x -= y; break;
Output x case '%': x %= y; break;
default : cout<<"Invalid ";
}
Stop
cout<<"Answer: "<<x;
}

6. For Loop: Output the factorial of a given number


Flow Chart: Pseudo Code:
Start
start
read num
fÅ1
Read num
for i=2 to num
fÅf*i
f←1 print f
i←2 stop

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

Advanced Technological Institute 14 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Read the next number n C++ Code


#include <iostream.h>
True void main()
n <>999 {
False int s=0,n=0;
do
Print s
{
s=s+n;
Stop cout<<"Enter a number: ";
cin>>n;
}
while (n !=999)
cout<<"The sum is "<<s;
}

Advanced Technological Institute 15 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Read the next number n

Fals
n=999
True

Print s

Stop

Some Example C++ Programs:


Example:
#include <iostream.h>
void main()
{
int a, b, c;
cout<<"Enter the lengths of the sides of a triangle :";
cin>>a>>b>>c;
if (a<(b+c) && b<(a+c) && c<(a+b))
cout<<"It can be a triangle"<<endl;
else
cout<<"It cannot be a triangle"<<endl;
}

Typical Outputs:
Enter the lengths of the sides of a triangle :3 4 5
It can be a triangle

Enter the lengths of the sides of a triangle :3 4 7


It cannot 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':

Advanced Technological Institute 16 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Advanced Technological Institute 17 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Pass by Value and Pass by Reference:


By default most type of function parameters are passed by value, which means that the function
makes a copy of each parameter which is passed to it, and the original data is unaffected.

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

Advanced Technological Institute 18 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Advanced Technological Institute 19 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Example:
#include <iostream.h>

int sqr(int value_in);

void main()
{
int x=5;
int y=sqr(x);
cout<<"Square of "<<x<<" is "<<y;
}

int sqr(int value_in)


{
int squared=value_in*value_in;
return squared;
}

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

Advanced Technological Institute 20 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Enter a string of characters: 999


Total number of digits in the string: 3
Try another string(y/n)? y

Enter a string of characters: C++


Total number of digits in the string: 0
Try another string(y/n)? n

Advanced Technological Institute 21 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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]

(b) Two-dimension array


float matrix[5][4];
matrix 0 1 2 3
0
1 matrix[1][1]
2 matrix[2][3]
3
4

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.

Arrays and Functions:


Arrays are always implicitly passed by reference to functions, never by value.
They cannot be used as the return type of a function.
Example:
#include <iostream.h>

void setArraySize(int size, int array_in[])


{
array_in[0]=size;
}

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

Advanced Technological Institute 22 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Declaring Multiple Pointers:


When declaring pointers, all the following three statements would have the same effect:
char* t; char *t; char * t;
If you declare more than one variable in the same statement, it might cause confusion.
E.g.: char x, y, z; //three variables of type char
char* x, y, z; //x is char pointer, y and z are variables of type char
char *x, *y, *z; //three char pointers

De-referencing Numeric Pointers:


We can access the data which a pointer is referencing by preceding the pointer name with an
asterisk (*).
If we display a pointer (of a numeric data type) then we will see the memory address, not the data in
that address.
The address of any variable can be obtained by using ‘&’ ( address of operator) before the variable
name.
Example:
#include <iostream.h>
void main()
{
int x=4; int* y=&x;
cout<<"Variable is "<<x<<endl;
cout<<"Pointer is "<<y<<endl;
cout<<"De-referenced pointer is "<<*y<<endl;
}

Advanced Technological Institute 23 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Output:
Variable is 4
Pointer is 0x6317241a
De-referenced pointer is 4

De-referencing Character Pointers:


Pointers of type char (i.e. strings) behave in a rather different manner to numeric types.
Firstly, cout will display the string rather than the address.
Secondly, if you de-reference a char pointer which you are using to represent a string you will get
the single character which the pointer is addressing.
Example:
#include <iostream.h>
void main()
{
char* x="C++";
cout<<"String is "<<x<<endl;
cout<<"De-referenced char pointer is "<<*x<<endl;
x++;
cout<<"String after incrementing is "<<x<<endl;
cout<<"De-referenced char pointer is now "<<*x<<endl;
}

Output:
String is C++
De-referenced char pointer is C
String after incrementing is ++
De-referenced char pointer is now +

Advanced Technological Institute 24 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

An Array of Type char:


An array of 10 characters would be declared as char astring[10];
In fact the maximum string which we could contain in this array would be 9 characters long, since all
strings must be terminated by the escape sequence character ‘\0’.
The following figure shows the contents of astring when it contains the string ‘hello’.
astring h e l l o \0

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;

Advanced Technological Institute 25 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

Using Pointers to Strings:


Arrays are difficult to manipulate and cannot be used as the return type of a function.
A complementary approach is to use a pointer to reference a string of characters.
To declare a pointer to a string it must be of type char.
E.g.: char* str_ptr;
Here, the pointer str_ptr is able to point to the first character of a string of characters.
We can use a char pointer to reference an array of characters quite easily.
Example:
#include <iostream.h>
void main()
{
char str[11]={"char array"};
char* str_ptr=str;
cout<<str_ptr;
}

Output:
char array

It is easy to assign literals at declaration, requiring only “ ”.


E.g.: char* str_ptr=”A string”;
However, this is not a particularly safe way to create strings, since any attempt to assign a longer
string to the same pointer can cause other data to be overwritten.
The assignment operator may be used at any time after declaration to make one char pointer equal
to another.
Example:
#include <iostream.h>
void main()
{
char a[10]={"spring"}; //Step1
char b[10]={"summer"}; // Step2
char* c="autumn"; // Step3
char* d="winter"; // Step4
//a=b; will not compile
//a={"printemps"} will not compile
c=d; // Step5
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
cout<<d<<endl;
d="fall"; // Step6
cout<<c<<endl;
cout<<d<<endl;
}

Output:
spring

Advanced Technological Institute 26 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Advanced Technological Institute 27 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

A Strategy for Strings:


In practice, we can see that although pointers provide a flexible means for string manipulation, they
can lead to ‘unsafe’ practices in some contexts.
Therefore we are better served by using arrays to store strings, but may use pointers to manipulate
them.

Advanced Technological Institute 28 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Defining a Class in C++:


In C++, we model a class by using the class keyword.
The class has two parts: private and public.
The private part of a class contains any elements which are to be hidden from public access.
The public part of the class contains any elements which are to be accessed from outside.
It is normal practice to put attributes into the private part of the class, where they can only be
accessed via methods.
Methods (member functions) themselves appear in the public part of the class so they can be
accessed externally and provide the interface to the class.
Example: The following class Point has the attributes x and y, and the methods setX (to set the
value of x), setY (to set the value of y), getX (to get the value of x) and getY (to get the value of y).
class Point
{
private:
int x;
int y;

public:
void setX(int x_in)
{
x=x_in;
}

void setY(int y_in)


{
y=y_in;
}

Advanced Technological Institute 29 Trincomalee


Introduction to Programming (C++) J.Pratheepan

int getX()
{
return x;
}

int getY()
{
return y;
}
};

A class definition is terminated with a semicolon (;), unlike a function definition.


The members of a class are private by default, so the keyword private could be omitted.
The integer variables x and y are private and therefore inaccessible from outside the class, except
indirectly via the setX, setY, getX and getY methods.
The member functions setX, setY, getX and getY are defined inline (inside the class definition) in
this case.
In most cases, methods must be prototyped (declared) inside the class, with their definitions given
outside the class using :: (scope resolution operator).
Example:
class Point
{
private:
int x;
int y;

public:
void setX(int x_in);
void setY(int y_in);
int getX();
int getY();
};

void Point::setX(int x_in)


{
x=x_in;
}

void Point::setY(int y_in)


{
y=y_in;
}

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

Advanced Technological Institute 30 Trincomalee


Introduction to Programming (C++) J.Pratheepan

char y, z; //y and z are variables of type char


Point p; //p is an object of class Point
Point p1, p2, p3; //p1, p2 and p3 are objects of class Point;

Sending Messages by Using Methods:


When an object is identified by a unique name, anything in the public part of the class (usually
methods) can be called by putting a period (.) between the name of the object and the method.
E.g.: p.setX(100);
Calling a method of an object is known as sending a message.
In the above example, the message ‘set x to 100’ is sent to the object p.
Example:
#include <iostream.h>
class Point
{
private:
int x;
int y;

public:
void setX(int x_in);
void setY(int y_in);
int getX();
int getY();
};

void Point::setX(int x_in)


{
x=x_in;
}

void Point::setY(int y_in)


{
y=y_in;
}

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

Advanced Technological Institute 31 Trincomalee


Introduction to Programming (C++) J.Pratheepan

The coordinate of the point 'p2': (15,25).


The coordinate of the point 'p3': (15,30).

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 Point::setX(int x_in)


{
x=x_in;
}

void main()

Advanced Technological Institute 32 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

};

Point::Point(int x_in, int y_in)


{
x=x_in;
y=y_in;
}

void Point::setX(int x_in)


{
x=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).

Advanced Technological Institute 33 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Default Parameter Values:


What if we want to be able to instantiate objects with parameters some of the time, but not always?
Any single parameter to a method can be given a default value in C++ as in the following example.
Example:
#include <iostream.h>

class Point
{
private:
int x;
int y;

public:
Point(int x_in, int y_in);
void setX(int x_in);

};

Point::Point(int x_in=0, int y_in=0)


{
x=x_in;
y=y_in;
}

void Point::setX(int x_in)


{
x=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;

Advanced Technological Institute 34 Trincomalee


Introduction to Programming (C++) J.Pratheepan

int y;

public:
Point(int x_in, int y_in);
void setX(int x_in);

};

Point::Point(int x_in=0, int y_in=0)


{
x=x_in;
y=y_in;
}

void Point::setX(int x_in)


{
x=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).

User Defined Copy Constructor:


It is also possible to create your own copy constructor.
If we declare a copy constructor, then we must also declare an ordinary constructor, since the
compiler will no longer automatically use the default version.
In fact, a user-defined copy constructor overrides the default constructor.
Example:
#include <iostream.h>

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

};

Advanced Technological Institute 35 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Point::Point(Point& copied_point) //copy constructor


{
x=copied_point.x;
y=copied_point.y;
}

Point::Point(int x_in=0, int y_in=0) //ordinary costructor


{
x=x_in;
y=y_in;
}

void Point::setX(int x_in)


{
x=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)
{

Advanced Technological Institute 36 Trincomalee


Introduction to Programming (C++) J.Pratheepan

curr_balance=start_balance;
}

void BankAccount::setAccNum(int num_in)


{
acc_num=num_in;
}

void BankAccount::setAccHolder(char* holder_in)


{
strncpy(acc_holder, holder_in,19);
acc_holder[19]='\0';
}

void BankAccount::deposit(float amount)


{
curr_balance += amount;
}

void BankAccount::withdraw(float amount)


{
curr_balance -= amount;
}

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

Advanced Technological Institute 37 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Advanced Technological Institute 38 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

void Object::addValue(int value_in)


{
value +=value_in;
}

int Object::getValue()

Advanced Technological Institute 39 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

The effect of new is to call the constructor to allocate memory.


E.g.: BankAccount* acc_ptr; // creates a pointer able to reference objects of class BankAccount.
acc_ptr = new BankAccount; //a BankAccount object is created and acc_ptr points to it.
The creation of the pointer and the constructor call can be put into a single line.
E.g.: BankAccount* acc_ptr = new BankAccount;

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.

To call a method of a dynamic object use the de-referencing arrow ( -> ).


E.g.: acc_ptr->deposit(100.00);

Advanced Technological Institute 40 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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 BankAccount::setAccNum(int num_in)


{
acc_num=num_in;
}

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.

Advanced Technological Institute 41 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Directing Pointers to NULL:


We can direct any pointers which is not currently referencing objects to NULL, which is equivalent to
the base memory address (0).
Before referring to NULL, we must include iostream.h.
Pointers of any type can be directed to NULL.
E.g.: int* x = NULL;
char* txt = NULL;
BankAccount* acc_ptr = NULL;
We can use NULL in conditional statements.
E.g.: if (acc_ptr = = NULL)
{
cout<< “No object referenced”;
}
else
{
cout<<acc_ptr -> getAccHolder();
}
It is good practice always to initialize pointers to NULL when they are declared.

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

Advanced Technological Institute 42 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Object external_object("External Object");

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

Car:: Car(char* color_in)


{
strncpy(color,color_in,9);
color[9]='\0';
}

char* Car::getColor()
{
return color;
}

void main()
{
Car* garage=NULL;
int menu_choice=0;
char temp_color[10];

while (menu_choice != 3)
{

Advanced Technological Institute 43 Trincomalee


Introduction to Programming (C++) J.Pratheepan

cout<<"Enter 1 to put car in garage, 2 to remove it, 3 to quit: ";


cin>>menu_choice;
if (menu_choice ==1 && garage==NULL)
{
cout<<"Enter color of car: ";
cin>>temp_color;
garage=new Car(temp_color);
cout<<garage->getColor()<<" car is parked"<<endl;
}
if (menu_choice==2 && garage != NULL)
{
cout<<garage->getColor();
delete garage;
garage=NULL;
cout<<" car is removed"<<endl;
}
}
if (garage != NULL)
{
delete garage;
}
}

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

We can declare arrays of object pointers also.


E.g.: void main()
{
Car* cars[10];

cars[0]=new Car(“Red”);

cout<<cars[0]->getColor();

delete cars[0];
cars[0]=NULL;

}

Example:
#include <iostream.h>
#include <string.h>

class Car
{
private:
char color[10];
public:

Advanced Technological Institute 44 Trincomalee


Introduction to Programming (C++) J.Pratheepan

Car(char* color_in);
char* getColor();
};

Car:: Car(char* color_in)


{
strncpy(color,color_in,9);
color[9]='\0';
}

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

Advanced Technological Institute 45 Trincomalee


Introduction to Programming (C++) J.Pratheepan

cout<<(i+1)<<"\t\t";
if (garage[i]==NULL)
cout<<"No car\n";
else
cout<<garage[i]->getColor()<<endl;
}

for (i=0; i<3; i++)


{
if (garage[i] != NULL)
{
delete garage;
}
}
}

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

Room No. Color


1 No car
2 Black
3 Green

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.

Advanced Technological Institute 46 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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;

Advanced Technological Institute 47 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

class DerivedClass:public BaseClass


{
private:
int y;
public:
void setY(int y_in)
{
y=y_in;
}
int getY()
{
return y;
}
void xEqualsY()
{
x=y;
}
};

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

Advanced Technological Institute 48 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

class AccountCustomer:public Customer


{
private:
int account_no;
public:
AccountCustomer();
int getAccNo();
};

AccountCustomer::AccountCustomer()
{
cout<<"Enter the account number: ";
cin>>account_no;
}

int AccountCustomer::getAccNo()
{
return account_no;
}

Advanced Technological Institute 49 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

class AccountCustomer:public Customer


{
private:
int account_no;
public:
AccountCustomer(char* name_in, int acc_no_in); //Any constructors of derived classes must
also take the parameter
int getAccNo();
};

AccountCustomer::AccountCustomer(char* name_in, int acc_no_in):Customer(name_in)


{
account_no=acc_no_in;
}

int AccountCustomer::getAccNo()
{

Advanced Technological Institute 50 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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;

class Director:public Employee


{
private:
int shareholding;
public:
Director();
int getShareholding();
void changeShareholding(int share_change);
};

class SalariedWorker:public Employee


{
private:
int department_no;
float annual_salary;
public:
SalariedWorker();
int getDepartmentNo();
float getAnnualSalary();
void changeDepartmentNo(int new_dept);
void changeAnnualSalary(float new_salary);
};

class HourlyPaid:public Employee


{
private:

Advanced Technological Institute 51 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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

void Director::changeShareholding(int share_change)


{
shareholding += share_change;
}

SalariedWorker::SalariedWorker()
{
cout<<"Enter annual salary for "<<name<<": ";
cin>>annual_salary;
}

float SalariedWorker::getAnnualSalary()
{
return annual_salary;
}

int SalariedWorker::getDepartmentNo()
{
return department_no;

Advanced Technological Institute 52 Trincomalee


Introduction to Programming (C++) J.Pratheepan

void SalariedWorker::changeAnnualSalary(float new_salary)


{
annual_salary=new_salary;
}

void SalariedWorker::changeDepartmentNo(int new_dept)


{
department_no=new_dept;
}

HourlyPaid::HourlyPaid()
{
cout<<"Enter hourly rate for "<<name<<": ";
cin>>hourly_rate;
}

char HourlyPaid::getFactorySection()
{
return factory_section;
}

float HourlyPaid::getHourlyRate()
{
return hourly_rate;
}

void HourlyPaid::changeFactorySection(char new_section)


{
factory_section=new_section;
}

void HourlyPaid::changeHourlyRate(float new_rate)


{
hourly_rate=new_rate;
}

void main()
{
const int DIRECTORS=2;
const int SALARIED=2;
const int MANUAL=4;

const float DIV_PER_SHARE=3.50;


const int HOURS_IN_YEAR=40*52;

Director directors[DIRECTORS];
SalariedWorker salaried[SALARIED];
HourlyPaid hourly[MANUAL];

int i=0;

float total_dividend=0, total_salary=0, total_wages=0;

for (i=0; i<DIRECTORS; i++)


{
total_dividend += (directors[i].getShareholding()*DIV_PER_SHARE);

Advanced Technological Institute 53 Trincomalee


Introduction to Programming (C++) J.Pratheepan

for (i=0; i<SALARIED; i++)


{
total_salary += salaried[i].getAnnualSalary();
}

for (i=0; i<MANUAL; i++)


{
total_wages += (hourly[i].getHourlyRate()*HOURS_IN_YEAR);
}

cout<<endl<<"Total dividends: "<<total_dividend<<endl;


cout<<"Total salaries: "<<total_salary<<endl;
cout<<"Total wages: "<<total_wages<<endl;
}

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

Total dividends: 2275


Total salaries: 35000
Total wages: 39520

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:

Advanced Technological Institute 54 Trincomalee


Introduction to Programming (C++) J.Pratheepan

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.

Advanced Technological Institute 55 Trincomalee

You might also like