SlideShare a Scribd company logo
1 of 176
Instructor
Mr. S.Christalin Nelson
AP(SG)/SoCSE
PROGRAMMING in C++
At a Glance (1/3)
• Generation of Programming Languages
• Programming Language Paradigms
• From C to C++
• Programming Basics
– Program Structure and Environment
– Statement & Terminator, Block, Identifier, Keyword, Tri-graphs
– Variable & Data Types
• Modifiers, sizeof(), Scope (Local/Global/Environment), Type
Qualifier (const/volatile), Casting
– Constant & Literals, Operators
• Storage Class Specifiers
• Looping & Decision Making
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
2 of 176
At a Glance (2/3)
• Functions
– Basics, Function Callss, Inline Functions, Friend Functions,
Virtual Functions
• Access Modifiers
• Arrays & Strings
• Pointers & References
• OOP Concepts
– Encapsulation & Abstraction
– Constructors & Destructors
– Static Members
– Inheritance
– Polymorphism
– Interfaces & Abstract Classes28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
3 of 176
At a Glance (3/3)
• Dynamic Memory Allocation
• Templates
• Namespaces
• Exception Handling
• Preprocessors
• File Handling
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
4 of 176
Generations
• Generation -1: Machine Level Programming Languages (late
1940s)
• Generation -2: Assembly Languages (early 1950s)
• Generation -3: High-Level Languages (mid 1950s to present)
• Generation -4: Specification/Query Language, Report
Generators (1970s to present)
• Generation -5: Artificial Intelligence
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
6 of 176
Features of Languages (1/2)
• Machine Level Language
– Fast and efficient, executed directly on the CPU
– Consists only of 0s and 1s
– Difficult for humans to read, write, and debug
• Assembly Language
– Also included Interpreting Routines & early Compilers
– Simple mnemonic instructions <opcode> <operands>
– Assembler translates into machine code
– Hand coding in assembly only for low-level needs
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
7 of 176
Features of Languages (2/2)
• High Level Languages
– Easier for humans to read, write, debug
– Compiler translates into machine code before running
– Interpreter translates into machine code at runtime
– Examples: FORTRAN, LISP, COBOL, ALGOL (Ada, Basic, C, C++,
Java, Pascal, Smalltalk, …)
• Fourth Generation
– Examples: Maple, Mathematica, Postscript, SPSS, SQL
• Fifth Generation
– Examples: Prolog
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
8 of 176
Family Tree of Languages
28-Mar-17
Fortran
BASIC
Cobol
LISP
Scheme
ML
Prolog
PL/1
Algol 60
Algol 68
Pascal
Modula 3
Ada
C
C++
Simula
Smalltalk
Java
Dylan
Ruby
Perl
PythonC#
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
9 of 176
Procedural Paradigm
• Procedures, sequential execution of code are basic building
blocks of program
• Examples
– FORTRAN (FORmula TRANslating; John Backus, IBM, 1950s)
– ALGOL (ALGOrithmic Language, 1958)
– COBOL (COmmon Business Oriented Language, 1960)
– BASIC (Beginner's All-purpose Symbolic Instruction Code, John
Kemeny and Thomas Kurtz, Dartmouth, 1963)
– Pascal (Niklaus Wirth, 1970)
– C (Dennis Ritchie, Bell Labs, 1972)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
K. Thompson and D. Ritchie
11 of 176
Object Oriented Paradigm
• Program is designed around the objects required to solve the
problem
• Examples
– Smalltalk (Alan Kay, Xerox PARC, 1971)
– Ada (US Dept of Defense, 1975)
– C++ (Bjarne Stroustrup, Bell Labs, 1983)
– Java (James Gosling, Sun Microsystems, 1995)
– C# (Microsoft, 2000)
28-Mar-17
Alan Kay
B. Stroustrup J. Gosling
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
12 of 176
Functional Paradigm
• Program is designed around the evaluation of functions,
rather than modifying state
• Examples
– LISP (John McCarthy, MIT, 1958)
– Common Lisp
– Dylan
– Logo
– Scheme
– ML (Robin Milner et al, Edinburgh, 1970s)
– Haskell (purely functional language, 1990)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
13 of 176
Logic & Scripting Paradigms
• Logic
– Program is declarative, based on mathematical logic
– Example: Prolog (1972)
• Scripting
– Used for text processing, shells, HTML, CGI
– Examples
• awk (Aho, Weinberger, Kerningham, Bell labs, 1978)
• Perl (Larry Wall, NASA, 1987)
• Tcl/Tk (John Ousterhout, 1988)
• Python (Guido van Rossum, CWI, 1991)
• PHP (Rasmus Lerdorf, 1995)
• Ruby (Yukihiro Matsumoto, 1996)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
14 of 176
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
15
C Language (1/4)
• Salient Features
– Powerful and Efficient
– Frequently used for small/medium sized programs
– Compact obj. codes (after compilation)
– Large presence (OS: Linux & Windows, DB: Oracle, TCP/IP)
– Procedural / Structured Programming
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
17 of 176
C Language (2/4)
• Limitations
– Inability to express large program as an abstraction (group
together related data & functions) of smaller individual units
• Programs Global view (single concept) is lost
– Soln.: Modular programming support
– Eg. Mark-sheet print prog., MS Word, VB prog., Car driving
– Unsuited for very large scale programming (Modules are not
totally independent)
– No Mechanism for information reuse with little modification
• Team Contribution & Correction due to error is difficult
• Eg. Use of Employee Info. to HR & Payroll program
– Can only identify Errors & cannot handle Exceptions
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
18 of 176
C Language (3/4)
• Limitations (contd.)
– Features like Data Hiding, Polymorphism, Inheritance are not
available
– Top-down approach as opposed with Bottom-Top approach of
C++
– NAMESPACE feature (which avoid name collision) is absent
– Does not allow use of reference variables (two variable names
point to the same memory location)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
19 of 176
C Language (4/4)
• Limitations (contd.)
– C is not a Multi-paradigm language like C++. Hence C++ is:
• Generic
– Generalize concepts as templates & reuse them
• Imperative
– Work with a sequence of commands to change the state of program
(Procedural / Structural)
– Organize code in form of blocks of codes (functions, structure, etc.)
that are executed to achieve expected output
– Focus is on the process (Function driven)
• Object-Oriented
– Use classes which are blueprints of objects that share common
behavior & properties
– Focus is on the data & instructions
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
20 of 176
C++ Language (1/3)
• C++ is regarded as a middle-level language [Combination of
both high-level and low-level language features]
• C++ is superset of C
• C++ does not impose Object Orientation to offer flexibility
– Object-based Programming (OBP) offers more flexibility and
more efficiency (Execution speed) than Object-Oriented
Programming (OOP)
• ANSI Standard
– Ensures that C++ is portable
• i.e. Code you write for Microsoft's compiler will compile without
errors using a compiler on a Mac, UNIX, etc.
– All the major C++ compiler manufacturers support the ANSI
standard
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
21 of 176
C++ Language (2/3)
• Standard Libraries - three important parts
– Core language
• Gives all building blocks including variables, data types and
literals, etc.
– C++ Standard Library
• Gives a set of functions for manipulating files, strings, etc.
– Standard Template Library (STL)
• Gives a set of methods for manipulating data structures like
Queue, etc.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
22 of 176
C++ Language (3/3)
• C++ fully supports object-oriented programming including
the four pillars of object-oriented development
– Encapsulation
– Data hiding
– Inheritance
– Polymorphism
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
23 of 176
C++ program (1/4)
• C++ Program can be considered as a collection of objects
that communicate via invoking each other's methods
• Definitions
– Object - Objects have states and behaviors. An object is an
instance of a class.
– Class - A class can be defined as a template/blueprint that
describes the behaviors/states that object of its type support.
– Methods - A method is basically a behavior. A class can contain
many methods. It is in methods where the logics are written,
data is manipulated and all the actions are executed.
– Instance Variables - Each object has its unique set of instance
variables. An object's state is created by the values assigned to
these instance variables.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
25 of 176
C++ program (2/4)
• Defining Classes and Objects
• Class vs. Object
• Classes vs. C Structures
– Contains Attributes & Functions
– Controlled access to Attributes
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Class Object
Abstract Data Type Variable of ADT
Abstraction of what an object should
have & should do, does nothing
Instance of class that does the actions
(method or function)
Sketch from where actual objects are
derived
Objects can operate only on the
functions owned by them
26 of 176
C++ program (3/4)
• Defining Member Functions
– It is a function that has its definition or its prototype within
the class definition like any other data member.
• Defining a member function within the class definition declares
the function inline, even if inline specifier is not used.
• It can be defined outside the class definition using scope
resolution operator (::).
– It operates on any object of the class of which it is a member,
and has access to all the members of a class for that object.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
27 of 176
C++ program (4/4)
• Accessing Data Members & Member Functions using a dot
operator (.) on a object.
• Memory Allocation
– For Member function @Class Definition
– For Member Data @Object definition
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
28 of 176
Discussion (1/5)
• Case: C++ program to maintain roll call of a class
– Roll Call Procedure?
– Entities & Types
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Roll Call System Entities
Mapped from Real World
Student Teacher Subject
Designed for Program
Roll Call
29 of 176
Discussion (2/5)
• Discussion [contd.]
– Attributes & Types
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Attributes of Entity (Teacher)
Data Attributes
Name
Subject
Name
Time
Table
Function Attributes
Enroll
Associate
to subject
Printing
details
30 of 176
Discussion (3/5)
• Discussion [contd.]
– Usefulness of Attributes –
Experience & Intuition
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Attributes of Entity (Student)
Useful Attributes
• Data Attributes
• Name
• Address
• Roll Number
• Course Name
• Function Attributes
• Enrolment
• Getting Mark Sheet
• Exam Registration
Attributes – not useful
• Data Attributes
• Name of Parents
• List of Friends
• Hobbies
• Function Attributes
• Add a Friend
• Scrap
• Upload Photo
31 of 176
Discussion (4/5)
• Discussion [contd.]
– Designing Classes
• Decide other Entities & Attributes of the Entire System (At larger
scope)
– A College Admin. System with 4 programs and their entities
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Roll Call Management
Roll Call Teacher Student
Mark sheet Printing
Student Mark sheet Subject
Subject maintenance
Teacher Student Subject
Teacher’s Information Management
Teacher Student Subject
32 of 176
Discussion (5/5)
• Discussion [contd.]
– Entities identified
• Roll Call, Teacher, Student, Mark sheet, Subject
– Associate Entities with programs
– Find relations between Different Entities
• How are Entities associated with each other?
– E.g. Association of Teacher with Roll Call?
– The method to generate the answer must be provided to the
receiving entity – i.e. “Identify Methods inside Entity”
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
33 of 176
Program Structure (1/2)
• Sample Program
#include <iostream> //Header file
using namespace std; //Namespace
class Student
{ //Class definition
public: //Member Access Modifier
int sap; //Data Member
void printf() { cout<<sap; } //Member fn. definition
};
int main()
{ // program execution begins
Student obj1; // Creating object
cin>>obj1.sap; // Member data access
obj1.printf(); // Member function access
return 0;
}28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
34 of 176
Program Structure (2/2)
• # include <iostream.h> C++ language defines several
headers, which contain information that is either necessary
or useful to program.
• using namespace std; tells the compiler to use the “std”
namespace. Namespaces is a recent addition to C++.
• // is a single-line comment available in C++
• int main() is the main function where program execution
begins.
• cout << "This is my first C++ program."; causes the message
"This is my first C++ program" to be displayed on the screen.
• return 0; terminates main( )function and causes it to return
the value 0 to the calling process.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
35 of 176
Compile & Execute
• Open a editor to create a file
– vi filename.cpp (or) notepad
• Add the necessary code.
• Save the file with .cpp extension.
• Open a command prompt and go to the directory where you
saved the file. Press ESC key followed with :wq (save & quit)
• Type 'g++ hello.cpp' and press enter to compile your code. If
there are no errors in your code the command prompt will
take you to the next line and would generate “a.out”
executable file.
• Type ./a.out to run your program.
• You will be able to see the desired output on the window.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
36 of 176
Statement Terminator - Block - Identifier
• Statement Terminator
– Each individual statement must be ended with a semicolon. It
indicates the end of one logical entity.
• Block
– Set of logically connected statements that are surrounded by
opening and closing braces.
• Identifier
– It is a name used to identify a variable, function, class, module,
or any other user-defined item.
– Identifier starts with a letter A-Z or a-z or underscore (_)
followed by zero or more letters, underscores, and digits (0-9).
Special characters are not allowed within identifiers.
– C++ is a case-sensitive programming language.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
37 of 176
Keywords
• Keywords are reserved words that may not be used as
constant or variable or any other identifier names.
– Alternative tokens28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
and, and_eq,
bitand, bitor, compl,
not, not_eq, or,
or_eq, xor, xor_eq
const Export mutable signed typedef
const_cast Extern namespace sizeof typeid
continue false new static typename
asm default float operator static_cast union
auto delete for private struct unsigned
bool do friend protected switch using
break double goto public template virtual
case dynamic_cast if register this void
catch else inline reinterpret_cast throw volatile
char Enum int return true wchar_t
class Explicit long short try while
38 of 176
Digraphs
• Two-letter alternative tokens that represents a single
character and are expanded anywhere they appear
• Example
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Primary Alternative
{ <%
} %>
[ <:
] :>
# %:
## %:%:
39 of 176
Trigraphs
• Trigraph is a three-character sequence that
represents a single character and are
expanded anywhere they appear, including
within string literals and character literals,
in comments, and in preprocessor
directives.
• Note:
– All the compilers do not support trigraphs
and they are not advised to be used
because of their confusing nature.
– For compilation of a program with trigraph
• $g++ -trigraphs sample.cpp
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Primary Trigraph
{ ??<
} ??>
[ ??(
] ??)
# ??=
 ??/
^ ??'
| ??!
~ ??-
40 of 176
Variables (1/4)
• Variables are reserved memory locations to store values.
This means that some space in memory is created when a
variable is created.
• A variable provides a named storage that programs can
manipulate.
• Each variable in C++ has a specific type, which determines
the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
41 of 176
Variables (2/4)
• Variable Definition
– Compiler is informed of where and how much storage is to be
created for the variable.
– Syntax: type variable_list;
• Variable Initialization
– Variables can be assigned an initial value in their definition.
The initializer consists of equal sign followed by constant
expression
– Syntax: type variable_name = value;
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
42 of 176
Variables (3/4)
• Variable Declaration
– Provides assurance to compiler that there is one variable
existing with the given type and name so that compiler
proceed for further compilation without needing complete
detail.
– Has its meaning at the time of compilation only, compiler
needs actual variable definition at the time of linking of the
program.
• While using multiple files, we define our variable in one of the
files which will be available at the time of linking of the program.
– A variable can be declared multiple times in a C++ program,
but it can be defined only once in a file, a function or a block of
code.
– Use extern keyword to declare a variable at any place.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
43 of 176
Variables (4/4)
• There are two kinds of expressions in C++
– lvalue Expression
• Refer to a memory location
• An lvalue may appear as either the left-hand or right-hand side
of an assignment.
– Rvalue
• Refers to a data value that is stored at some address in memory.
• An rvalue may appear on the right- but not left-hand side of an
assignment.
– Note:
• Variables are lvalues and so may appear on the left-hand side of
an assignment.
• Numeric literals are rvalues and so may not be assigned and can
not appear on the left-hand side.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
44 of 176
Data Types (1/9)
• Primitive Data types
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Type Keyword Description
Boolean bool Stores either value true or false.
Character char Typically a single octet(one byte). This is an integer type.
Integer int The most natural size of integer for the machine.
Floating point float A single-precision floating point value.
Double floating
point
double A double-precision floating point value.
Value-less void Represents the absence of type.
Wide character wchar_t A wide character type.
45 of 176
Data Types (2/9)
• User-defined Data types
– typedef types
– Enumerated types
• Typedef types
– Creation of a new name for an existing type
– Syntax:
typedef type newname;
– Example:
typedef int feet;
feet distance;
• The above tells the compiler that ‘feet’ is another name for int
and creates an integer variable called distance.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
46 of 176
Data Types (3/9)
• Enumerated Types
– This type declares an optional type name and a set of zero or
more identifiers that can be used as values of the type. Each
enumerator is a constant whose type is the enumeration.
– Syntax:
enum enum-name { list of names } var-list;
– Example:
enum color { red, green, blue } c;
c = blue;
• The above tells the compiler that variable c (of enum type color)
is assigned the value "blue“ = 2.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
47 of 176
Data Types (4/9)
• Derived Types
– These types are derived from the primitive types.
– Example: Pointer, Array, Reference, Data structures, Classes.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
48 of 176
Data Types (5/9)
• Modifiers
– Basic types can be modified using one or more of these type
• signed, unsigned, short, long
– Modifiers signed, unsigned, long, and short can be applied to
integer base types.
– Modifiers signed and unsigned can also be applied to char, and
long can also be applied to double.
– The modifiers signed and unsigned can also be used as prefix
to long or short modifiers.
• Example: unsigned long int
– C++ allows a shorthand notation for declaring unsigned, short,
or long integers by simply using the word unsigned, short, or
long, without the int. The int is implied.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
49 of 176
Data Types (6/9)
• sizeof() operator
– To get size of various data types
• Note: The sizes of variables might be different depending on the
compiler and the computer being used.
– Syntax:
• sizeof()
• sizeof expression
– Example
# include <iostream>
using namespace std;
main() {
int a;
cout << sizeof(int) << sizeof a << endl;
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
50 of 176
Data Types (7/9)
• Scope of Variables
– A scope is a region of the program where variables can be
declared
• Local variable: Defined inside a function definition or a block.
• Formal variable/parameter: Defined as a function’s parameter or
argument.
• Global variable: Defined outside all functions in a program.
• Environment variable: Available for all applications/programs.
They can be accessed anywhere in a program without declaring
and initializing in an application or program.
– Note:
• A program can have same name for local and global variables but
value of local variable inside a function will take preference.
• Reference Variable is an alias to the actual variable created.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
51 of 176
Data Types (8/9)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Initializing Local/Global Variables
– When a local variable is defined, it is not initialized by the
system, the programmer should initialize it instead.
– Global variables are initialized automatically by the system
according to the definition as follows:
Data Type Initializer
int 0
char '0'
float 0
double 0
pointer NULL
52 of 176
Data Types (9/9)
• Type Qualifiers in C++
– They provide additional information about the variables they
precede.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Qualifier Meaning
const
Objects of type const cannot be changed by your program
during execution
volatile
The modifier volatile tells the compiler that a variable's value
may be changed in ways not explicitly specified by the program.
53 of 176
Casting (1/2)
• Implicit Cast
– Support to Lossless Conversion (i.e. promotion) and Lossy
Conversions (E.g. Mixed Mode Expressions)
– Lossy conversions could be handled explicitly
• Traditional C-style
– Example
» double a = 3.14; int b = (int) a;
• Functional-style casting
– Example
» double a = 3.14; int b = int (a);
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
54 of 176
Casting (2/2)
• Implicit conversion with Classes
– Implicit conversions can be controlled by means of 3 member
functions
• Single-argument Constructors: allow implicit conversion from a
particular type to initialize an object.
• Assignment Operator: allow implicit conversion from a particular
type on assignments.
• Type-cast Operator: allow implicit conversion to a particular type.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
55 of 176
Constants/Literals (1/7)
• Constants refer to fixed values that the program may not
alter and they are called literals.
• Constants can be of any of the basic data types
– Integer Numerals
– Floating-Point Numerals
– Characters
– Strings
– Boolean Values
• Constants are treated just like regular variables except that
their values cannot be modified after their definition.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
56 of 176
Constants/Literals (2/7)
• Prefix and Suffix in Integer Literal
– A prefix sometimes specifies the base or radix
• 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
– A suffix is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can
be in any order.
– Examples
• 0213 // octal
• 0x4b // hexadecimal
• 30 // int
• 30u // unsigned int
• 30l // long
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
57 of 176
Constants/Literals (3/7)
• Floating-point Literal
– Has an integer part, a decimal point, a fractional part, and an
exponent part.
– Can be represented either in decimal form or exponential
form.
• While representing using decimal form, decimal point, the
exponent, or both must be included.
• While representing using exponential form, the integer part, the
fractional part, or both must be included. The signed exponent is
introduced by e or E.
– Examples
• 3.14159 // Legal
• 314159E-5L // Legal
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
58 of 176
Constants/Literals (4/7)
• Boolean Literal
– There are two Boolean literals and they are part of standard
C++ keywords
• A value of true representing true.
• A value of false representing false.
– Neither the value of true or false should be considered equal
to 1 or 0.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
59 of 176
Constants/Literals (5/7)
• Character Literal
– They are enclosed in single quotes.
• If the literal begins with L (uppercase only), it is a wide character
literal (e.g., L'x') and should be stored in wchar_t type of
variable. Otherwise, it is a narrow character literal (e.g., 'x') and
can be stored in a simple variable of char type.
– A character literal can be a plain character (e.g., 'x'), an escape
sequence (e.g., 't'), or a universal character (e.g., 'u02C0').
– Escape sequences
• There are certain characters in C++ when they are preceded by a
backslash they will have special meaning.
• Example: newline (n), tab space (t)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
60 of 176
Constants/Literals (6/7)
• String Literal
– They are enclosed in double quotes.
– String contains characters that are similar to character literals.
• E.g. Plain characters, escape sequences, and universal characters.
– Note: A long line can be broken into multiple lines using string
literals and separate them using whitespaces.
– Examples (Are the following same?)
• "hello, dear"
• "hello, 
dear"
• "hello, " "d" "ear"
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
61 of 176
Constants/Literals (7/7)
• Defining Constants
– There are two simple ways in C++ to define:
• Using #define preprocessor. [Symbolic Constants]
– Syntax: #define identifier value
• Using const keyword.
– Syntax: const type variable = value;
• Note: An enumerator can be used to define a group of symbolic
constants.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
62 of 176
Operators (1/10)
• An operator is a symbol that tells the compiler to perform
specific manipulations.
• Types of built-in operators
– Arithmetic Operators
– Relational Operators
– Logical Operators
– Bitwise Operators
– Assignment Operators
– Miscellaneous Operators
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
63 of 176
Operators (2/10)
• Arithmetic Operators
– Assume variable A holds 10 and variable B holds 20.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by denominator and provide quotient B / A will give 2
% Divides numerator by denominator and provide remainder B % A will give 0
++ Increment Operator increases integer value by one A++ will give 11
-- Decrement Operator decreases integer value by one A-- will give 9
64 of 176
Operators (3/10)
• Relational Operators
– Assume variable A holds 10 and variable B holds 20.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Operator Description Example
==
Checks if the values of two operands are equal or not, if yes
then condition becomes true.
(A == B) is not true.
!=
Checks if the values of two operands are equal or not, if values
are not equal then condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the value of
right operand, if yes then condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value of right
operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to
the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the
value of right operand, if yes then condition becomes true.
(A <= B) is true.
65 of 176
Operators (4/10)
• Logical Operators
– Assume variable A holds 1 and variable B holds 0.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Operator Description Example
&&
Logical AND operator. If both the operands are non-zero, then
condition becomes true.
(A && B) is false.
||
Logical OR Operator. If any of the two operands is non-zero,
then condition becomes true.
(A || B) is true.
!
Logical NOT Operator. Used to reverse the logical state of its
operand. If a condition is true, then Logical NOT operator will
make false and otherwise.
!(A && B) is true.
66 of 176
Operators (5/10)
• Bitwise Operators
– Assume variable A holds 60 and variable B holds 13.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Operator Description Example
&
Binary AND Operator copies a bit to the result if it
exists in both operands.
(A & B) will give 12 (0000 1100)
|
Binary OR Operator copies a bit if it exists in either
operand.
(A | B) will give 61 (0011 1101)
^
Binary XOR Operator copies the bit if it is set in one
operand but not both.
(A ^ B) will give 49 (0011 0001)
~
Binary Ones Complement Operator is unary and
has the effect of 'flipping' bits.
(~A ) will give -61 (1100 0011) in
2's complement form due to a
signed binary number.
<<
Binary Left Shift Operator. The left operands value
is moved left by the number of bits specified by the
right operand.
A << 2 will give 240 (1111 0000)
>>
Binary Right Shift Operator. The left operands value
is moved right by the number of bits specified by
the right operand.
A >> 2 will give 15 (0000 1111)
A = 0011 1100, B = 0000 1101
67 of 176
Operators (6/10)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Assignment Operators
Operator Description Example
=
Simple assignment operator, Assigns values from right side
operands to left side operand
C = A + B will assign value of A +
B into C
+=
Add AND assignment operator, It adds right operand to the
left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand
from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand
with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with
the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using
two operands and assign the result to left operand
C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 268 of 176
Operators (7/10)
• Miscellaneous Operators (1/2)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Operator Description
sizeof()
sizeof() operator returns the size of a variable.
For example, sizeof(a), where a is integer, will return 4.
Condition ? X : Y
Conditional operator If Condition is true ? then it returns value X :
otherwise value Y
,
Comma operator causes a sequence of operations to be performed. The
value of the entire comma expression is the value of the last expression
of the comma-separated list.
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes,
structures, and unions.
Cast
Casting operators convert one data type to another.
For example, int(2.2000) would return 2.
&
Pointer address operator & returns the address of an variable.
For example &a; will give actual address of the variable.
*
Pointer Indirection operator * is pointer to a variable.
For example *var; will pointer to a variable var.
69 of 176
Operators (8/10)
• Miscellaneous Operators (2/2)
– Member Operators
• The dot operator is applied to the actual object. The arrow
operator is used with a pointer to an object.
– Cast Operators
• Simple casting
• Other casting operators
– const_cast<type> (expr)
– dynamic_cast<type> (expr)
– reinterpret_cast<type> (expr)
– static_cast<type> (expr)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
70 of 176
Operators (9/10)
• Operator Precedence (1/2)
– Different operators have different priority.
– Precedence determines how an expression is evaluated
starting from high priority operators (with its operands) to low
priority ones.
– Associativity
• Decide on how an expression is evaluated if it has operators with
same precedence.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
71 of 176
Operators (10/10)
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Operator Precedence (2/2)
72 of 176
Storage Class Specifiers (1/5)
• They define the scope (visibility) and life-time of variables
and/or functions within a C++ Program. These specifiers
precede the type that they modify.
• C++ storage classes
– auto
– register
– static
– extern
– mutable
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
74 of 176
Storage Class Specifiers (2/5)
• auto storage class
– It is the default storage class for all local variables.
– Can only be used within functions.
• register storage class
– It is used to define local variables that should be stored in a
register instead of RAM.
• Note: Defining 'register' does not mean that the variable will
always be stored in a register. It means that it MIGHT be stored in
a register depending on hardware & implementation restrictions.
– The register should only be used for variables that require
quick access. E.g. Counters.
– The variable has a maximum size equal to the register size and
cannot have the unary '&' operator applied to it (as it does not
have a memory location).
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
75 of 176
Storage Class Specifiers (3/5)
• static storage class
– This instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope.
Therefore, making local variables static allows them to retain
their values between function calls.
– The static modifier may also be applied to global variables.
When this is done, it causes that variable's scope to be
restricted to the file in which it is declared.
– In C++, when static is used on a class data member, it causes
only one copy of that member to be shared by all objects of its
class.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
76 of 176
Storage Class Specifiers (4/5)
• extern storage class
– It is used to give a reference of a global variable that is visible
to ALL the program files. When you use 'extern' the variable
cannot be initialized as all it does is point the variable name at
a storage location that has been previously defined.
– When you have multiple files and you define a global variable
or function, which will be used in other files also, then extern
will be used in another file to give reference of defined
variable or function.
– The extern modifier is most commonly used when there are
two or more files sharing the same global variables or
functions.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
77 of 176
Storage Class Specifiers (5/5)
• mutable storage class
– The mutable specifier applies only to class objects.
– It allows a member of an object to override const definition.
• A mutable data member of const object can be modified whereas
a normal data member of const object cannot be modified.
– Example
• Class Employee has data members “salary”, “name”, and “id”. A
constant object of this class assumes “name” and “id” to be
constant, but not the “salary” when defined as mutable. i.e. An
object’s “salary” can change, but “name” & “id” may not change.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
78 of 176
Loops (1/4)
• In general statements are executed sequentially: The first
statement in a function is executed first, followed by the
second, and so on.
• Execute a block of code several number of times?
– Programming languages provide various control structures
that allow for more complicated execution paths.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Loop Type Description
while loop
Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while loop
Like a while statement, except that it tests the condition at the end of the loop
body.
nested loops You can use one or more loop inside any another while, for or do..while loop.
80 of 176
Loops (2/4)
• Flow Diagrams (Loop Control Structures)
– While loop For loop do..while loop
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
81 of 176
Loops (3/4)
• Loop Control Statements
– These statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that
were created in that scope are destroyed.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Control Statement Description
break statement
Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
continue statement
Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
goto statement
Transfers control to the labeled statement. It is not advised to use goto
statement in your program.
82 of 176
Loops (4/4)
• Flow Diagrams (Loop Control Statements)
– break continue goto
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
83 of 176
Decision making (1/6)
Statement Description
if statement
An if statement consists of a boolean expression followed by
one or more statements.
if...else statement
An if statement can be followed by an optional else statement,
which executes when the boolean expression is false.
switch statement
A switch statement allows a variable to be tested for equality
against a list of values.
nested if statements
You can use one if or else if statement inside another if or else
if statement(s).
nested switch statements
You can use one switch statement inside another switch
statement(s).
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Basic understanding of relational operators is essential
• Types
84 of 176
Decision making (2/6)
• If statement
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Test Condition
85 of 176
Decision making (3/6)
• If…else statement
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
86 of 176
Decision making (4/6)
• If…else if…statement
– It is very useful to test various conditions.
– Note:
• An if can have zero or one else's and it must come after any else
if's.
• An if can have zero to many else if's and they must come before
the else.
• Once an else if succeeds, none of the remaining else if's or else's
will be tested.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
87 of 176
Decision making (5/6)
• Switch statement (1/2)
– Allows a variable to be tested for
equality against a list of values.
Each value is called a case, and
the variable being switched on is
checked for each case.
– Constant-expression for a case
must be the same data type as
the variable in switch, and it must
be a constant or a literal.
– Can have any number of case
statements within a switch. Each
case is followed by the value to be
compared to and a colon.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
88 of 176
Decision making (6/6)
• Switch statement (2/2)
– When the variable being switched on is equal to a case, the
statements following that case will execute until a break
statement is reached and the switch terminates and the flow
of control jumps to next line following switch statement.
– Not every case needs to contain a break. If no break appears,
the flow of control will fall through to subsequent cases until a
break is reached.
– A switch statement can have an optional default case, which
must appear at the end of the switch. The default case can be
used for performing a task when none of the cases is true. No
break is needed in the default case.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
89 of 176
Functions (1/10)
• A function is a group of statements that together perform a
task. It is also known as method or sub-routine or
procedure.
• Every C++ program has at least one function, which is main(),
and can define additional functions.
• The C++ standard library provides many built-in functions.
• Function declaration
– Tells the compiler about a function's name, return type, and
parameters.
– Syntax
• return_type function_name( parameter list );
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
91 of 176
Functions (2/10)
• Function definition
– Provides the actual body of the function.
– Parts of a Functions
• Return Type
• Function Name
• Parameters
– Function signature?
• Function Body
– Syntax
return_type function_name( parameter list )
{
body of the function
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
92 of 176
Functions (3/10)
• Function Call (1/2)
– Invoke a function for using it.
– Control Transfer
• When a program calls a function, program control is transferred
to the called function. A called function performs defined task
and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back
to the main program.
• Return Value
– If a function can return a value then it is necessary to store the
returned value.
– Required function Arguments/Parameters can be passed along
with function name.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
93 of 176
Functions (4/10)
Call Type Description
Call by value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
Call by pointer
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
Call by reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the
parameter affect the argument.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Function Call (2/2)
– Types
• Simple Call, Default Values, Call by value/pointer/reference
94 of 176
Functions (5/10)
Name Purpose
double cos(double); This function takes an angle (as a double) and returns the cosine.
double sin(double); This function takes an angle (as a double) and returns the sine.
double tan(double); This function takes an angle (as a double) and returns the tangent.
double log(double); This function takes a number and returns the natural log of that number.
double pow(double,
double);
The first is a number you wish to raise and the second is the power you
wish to raise it.
double hypot(double,
double);
If you pass this function the length of two sides of a right triangle, it will
return you the length of the hypotenuse.
double sqrt(double); You pass this function a number and it gives you this square root.
int abs(int); This function returns the absolute value of an integer that is passed to it.
double fabs(double);
This function returns the absolute value of any decimal number passed to
it.
double floor(double); Finds the integer which is less than or equal to the argument passed to it.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Built-in Functions in <cmath>
95 of 176
Functions (6/10)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Home Work
– Study the Built-in Functions in the following
• <ctime>
• <cstdlib>
• <cstring>
• <iomanip>
• <string>
• Functions with Default Arguments
96 of 176
Functions (7/10)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Inline Function (1/2)
– The compiler places a copy of the code of that function at each
point where the function is called at compile time.
– Any change to an inline function could require all clients of the
function to be recompiled because compiler would need to
replace all the code once again otherwise it will continue with
old functionality.
– To inline a function, place the keyword inline before the
function name and define the function before any calls are
made to the function.
– A function definition in a class definition is an inline function
definition, even without the use of the inline specifier.
– Prefer inline functions over preprocessor macro.
• Macros are forcibly inlined.
97 of 176
Functions (8/10)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Inline Function (2/2)
– It is a compiler optimization technique.
• It saves overhead of variables push/pop on the stack, while
function calling.
• It saves overhead of return call from a function.
• It increases locality of reference by utilizing instruction cache.
• Inline the functions with small code size to get performance.
– Virtual functions and function templates should not be inlined.
– Issues
• May increase function size so that it may not fit on the cache,
causing lots of cache miss.
• It may cause compilation overhead in case if the code inside
inline function is changed.
98 of 176
Functions (9/10)
• Friend Function
– Refer Access Modifiers
– A friend function of a class is defined outside the scope of that
class. It has the right to access any members (even private) of
the class.
– Even though the prototypes for friend functions appear in the
class definition, friends are not member functions.
– A friend can be a function, function template, or member
function, or a class or class template, in which case the entire
class and all of its members are friends.
– Note:
• Friend Classes
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
99 of 176
Functions (10/10)
• Virtual Function
– Refer Polymorphism
– Implements the concept of Overriding.
– A virtual function is declared in base class with virtual keyword
and with another version in a derived class. This signals the
compiler that static linkage for this function is overridden.
– Function selected to be called at any given point in program is
based on the kind of object for which it is called. This sort of
operation is referred to as dynamic linkage, or late binding.
– Pure Virtual Functions
• A virtual function in base class is included without a meaningful
definition so that it must be redefined in a derived class to suit
the objects of that class.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
100 of 176
Access Modifiers (1/2)
• Provides access levels/restrictions for class members.
• Types (specified by keywords): public, private, and
protected.
• Access levels are labelled sections within the class body.
– A class can have multiple labeled sections. Each section
remains in effect until either another section label or the
closing right brace of the class body is seen.
• The default access for members and classes is private.
• Note:
– Data hiding is one of the important features of OOP which
prevents the functions of a program to access directly the
internal representation of a class type by using access
specifiers and other related concepts.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
102 of 176
Access Modifiers (2/2)
Public Private Protected
Visible to all classes
Visible only to the class to
which they belong.
Visible only to the class to which
they belong, and any subclasses.
Global access. Its scope is
not only within the class
but also outside the class.
Class access. It cannot be
accessible by its derived
members.
Class access & Derived access. Used
within the class in which it is defined
and derived members of it.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Comparison
• Refer Inheritance
• Return to friend functions
103 of 176
Arrays (1/2)
• Data Structure which stores a fixed-size sequential collection
of elements/variables of the same type.
– Instead of declaring individual variables one array variable can
be declared to represent individual variables.
• All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element.
• Array declaration specifies the type of the elements and the
number of elements required by an array.
• Array elements can be initialized either one by one or using
a single statement.
• A specific element in an array is accessed by an index.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
105 of 176
Arrays (2/2)
• Types
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Concept Description
Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of
the multidimensional array is the two-dimensional array.
Pointer to an array
You can generate a pointer to the first element of an array by
simply specifying the array name, without any index.
Passing arrays to functions
You can pass to the function a pointer to an array by
specifying the array's name without an index.
Return array from functions C++ allows a function to return an array.
106 of 176
Strings (1/3)
• C++ supports two types of string representations:
– The C-style character string in <cstring>
– The string object introduced with Standard C++ in <string>
• C-style character array
– This string is actually a one-dimensional array of characters
which is terminated by a null character '0'.
– Example: “str” is a string which holds 4 characters.
• char str[] = "C++"; char str1[4] = "C++";
• char str2[] = {'C', '+', '+', '0'}; char str3[4] = {'C', '+', '+', '0'};
– Note:
• Extraction operator >> considers a space as a terminating
character. Hence get() can be used to read the text containing
blank space
– Example: cin.get(str, 4);
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
107 of 176
Strings (2/3)
• String object
– To handle single word text, “cin” can be used
– To handle text containing blank space getline() could be used
instead of get()
• Example:
– string a; getline(cin, a);
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
108 of 176
Strings (3/3)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Function
(partial list)
Purpose
strcpy(s1, s2) Copies string s2 into string s1.
strcat(s1, s2) Concatenates string s2 onto the end of string s1.
strlen(s1) Returns the length of string s1.
strcmp(s1, s2) Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch) Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2) Returns a pointer to the first occurrence of string s2 in string s1.
109 of 176
Pointers (1/3)
• Every variable is assigned a memory location. Every memory
location has its address defined which can be accessed with:
– Ampersand (&) or Memory Reference operator.
– Asterisk (*) or Memory De-reference operator.
• A pointer is a variable whose value is the address of another
variable.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
111 of 176
Pointers (2/3)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Related Topics
Concept Description
C++ pointer arithmetic There are 4 arithmetic operators that can be used on pointers: ++, --, +, -
C++ pointer to pointer C++ allows you to have pointer on a pointer and so on.
Null Pointers
It is always a good practice to assign the pointer NULL to a pointer variable
in case you do not have exact address to be assigned. This is done at the
time of variable declaration. It cannot be dereferenced.
Void pointer
Pointer can point to objects of any data type. It cannot be dereferenced
directly. It must first be explicitly cast to another pointer type before it is
dereferenced.
Constant Pointers A pointer that cannot change the address its holding.
Pointer to Constant
A pointer through which one cannot change the value of variable it points.
These type of pointers can change the address they point to but cannot
change the value kept at those address.
Constant pointer to
constant
Its a mixture of above two types of pointers. This pointer can neither
change the address its pointing to nor it can change the value kept at that
address.
112 of 176
Pointers (3/3)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
• Related Topics
Concept Description
Array of pointers You can define arrays to hold a number of pointers.
Pointers & arrays There is a close relationship between pointers and arrays.
Passing pointers to
functions
Passing an argument by reference or by address both enable the passed
argument to be changed in the calling function by the called function.
Return pointer from
functions
C++ allows a function to return a pointer to local variable, static variable
and dynamically allocated memory as well.
Function Pointer Pointer is assigned with a normal function and can be used for invoking it.
C++ this pointer
Every object in C++ has access to its own address through an important
pointer called this pointer. The this pointer is an implicit parameter to all
member functions. Therefore, inside a member function, this may be used
to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
Pointer to class A pointer to a class is done exactly the same way a pointer to a structure.
113 of 176
Reference Variable
• It is an alias or another name for an already existing variable.
– Once a reference is initialized with a variable, either the
variable name or the reference name may be used to refer to
the variable.
• References vs Pointers
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Reference Variable Pointer Variable
NULL references are not allowed. A reference must
be connected to a legitimate piece of storage.
Null Pointer exists.
Once a reference is initialized to an object, it
cannot be changed to refer to another object.
Pointers can be pointed to
another object at any time.
A reference must be initialized when it is created.
Pointers can be initialized at
any time.
114 of 176
Encapsulation
• All programs are composed of two fundamental elements:
– Program statements (code): This is the part of a program that
performs actions. This includes functions.
– Program data: The data is the information of the program which
is affected by the program functions.
• Encapsulation binds together the data and functions that
manipulate the data.
• Note:
– Class members should be private unless exposure is required.
– Making one class a friend of another class exposes the
implementation details and reduces encapsulation.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
116 of 176
Abstraction (1/3)
• Data abstraction is a programming (and design) technique
that relies on the separation of interface and implementation.
– i.e., Represent the needed information in program without
presenting the details to the user.
• Example-1: Consider usage of a TV.
– TV can be turned on/off, channels & volume can be tuned, and
external components can be added. BUT its internal details like
signal reception/translation, and function of the screen is
unknown.
– Thus a TV clearly separates its internal implementation from its
external interface and users can have access through its
interface without having zero knowledge of its internals.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
117 of 176
Abstraction (2/3)
• Example-2: Consider usage of cout in simple C++ program.
– Classes are used to define ADTs and cout object of class ostream
is used to stream data to standard output. The user need not
understand how cout displays the text on the user's screen but
needs to only know the public interface. The underlying
implementation of cout is free to change.
• Access labels/specifiers enforce Abstraction
– Members defined with a public label are accessible to all parts
of the program. Members defined with a private label are not
accessible to code that uses the class.
– A class may contain zero or more access labels.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
118 of 176
Abstraction (3/3)
• Benefits
– Class internals are protected from inadvertent user-level
errors, which might corrupt the state of the object.
– The class implementation may evolve over time in response to
changing requirements or bug reports without requiring
change in interface or user-level code.
• Designing Strategy
– Abstraction separates code into interface and implementation.
So while designing, the interface should be independent of the
implementation and would remain intact amidst changes
made to the underlying implementation.
• Note: The program would need a recompilation with the latest
implementation.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
119 of 176
Constructors (1/3)
• Class constructor is a special member function of a class that
is executed whenever we create new objects of that class.
• Constructors can be very useful for setting initial values for
certain member variables.
• Properties of a constructor
– Has same name as the class.
– Does not have any return type (not even void).
• Types of Constructors
– Default Constructors
– Parameterized Constructors
– Copy Constructors
• Constructor Overloading
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
120 of 176
Constructors (2/3)
• Using Initialization Lists to initialize fields
– If it is required to initialize the members of class then a
parameterized constructor can be defined as:
rect::rect (int len, int bre) : length (len), breadth(bre)
{
cout << "Object is being created, length = " << len << endl;
}
Above syntax is equal to the following syntax:
rect::rect (int len, int bre)
{
cout << "Object is being created, length = " << len << endl;
length = len;
breadth = bre;
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
121 of 176
Constructors (3/3)
• Copy constructor
– Refer Dynamic Memory
– It creates an object by initializing it with an object of the same
class, which has been created previously.
– The copy constructor is used to:
• Initialize one object from another object of the same type/class.
• Copy an object to
– Pass it as an argument to a function.
– Return it from a function.
– If a copy constructor is not defined in a class, the compiler
itself defines one.
– A class having pointer variables and some dynamic memory
allocations should have a copy constructor.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
122 of 176
Destructor
• Class destructor is a special member function of a class that
is executed whenever an object of it's class goes out of scope
or whenever the delete expression is applied to a pointer to
the object of that class.
• Destructor can be very useful for releasing resources before
coming out of the program like closing files, releasing
memories, etc.
• Properties of a Destructor
– A destructor will have exact same name as the class prefixed
with a tilde (~).
– Does not have any return type at all, not even void.
– It cannot take any parameters.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
123 of 176
Static Members of Class (1/2)
• When member of a class is declared as static – no matter
how many objects of the class are created, there is only one
copy of the static member.
– i.e. A static member is shared by all objects of the class.
• All static data members are initialized to zero when the first
object is created, if no other initialization is present.
– Static data members should be initialized outside the class
using the scope resolution operator.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
124 of 176
Static Members of Class (2/2)
• Declaring a function member as static, makes it independent
of any particular object of the class.
– i.e. A static member function can be called even if no objects
of the class exist and the static functions are accessed using
only the class name and the scope resolution operator.
– A static member function can only access static data member,
other static member functions and any other functions from
outside the class.
– Static member functions have a class scope and they do not
have access to the this pointer of the class.
– A static member function can be used to determine whether
some objects of the class have been created or not.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
125 of 176
Inheritance (1/7)
• Inheritance defines a class in terms of another class, which
makes it easier to create and maintain an application.
• It also provides an opportunity to reuse the code and fast
implementation time.
• Base class & Derived class
– When creating a class, the programmer can designate that the
new class should inherit the members of an existing class. This
existing class is called the base class, and the new class is
referred to as the derived class.
• The idea of inheritance implements the is-a relationship.
– Example: mammal IS-A animal, dog IS-A mammal hence dog
IS-A animal as well and so on.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
126 of 176
Inheritance (2/7)
• A class can be derived from more than one classes.
– i.e. Class can inherit data and functions from multiple base
classes.
• Definition of a derived class
– Use a class derivation list to specify the base class(es).
– Syntax:
• class derived-class: access-specifier base-class
– Note:
• If the access-specifier is not used, then it is private by default.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
127 of 176
Inheritance (3/7)
• A derived class can access all the non-private members of its
base class.
– Note: Base-class members that should not be accessible to the
member functions of derived classes should be declared
private in the base class.
• A derived class inherits all base class methods with the
following exceptions
– Constructors, destructors and copy constructors of the base
class.
– Overloaded operators of the base class.
– The friend functions of the base class.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
128 of 176
Inheritance (4/7)
• Types of Inheritance (w.r.t. Access Specifier while inheriting)
– Public Inheritance (Deriving a class from a public base class)
• Public and Protected members of the base class become Public
and Protected members of the derived class respectively.
• Private members of base class are never accessible directly from
a derived class - but can be accessed through calls to the public
and protected members of the base class.
– Protected Inheritance (Deriving from a protected base class)
• Public and Protected members of the base class become
Protected members of the derived class.
– Private Inheritance (Deriving from a private base class)
• Public and Protected members of the base class become Private
members of the derived class.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
129 of 176
Inheritance (5/7)
• Types of Inheritance (w.r.t. Bases classes while inheriting)
– Single Inheritance Multiple Inheritance
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
130 of 176
Inheritance (6/7)
• Types of Inheritance (w.r.t. Bases classes while inheriting)
– Multi-level Inheritance Hierarchical Inheritance
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
131 of 176
Inheritance (7/7)
• Types of Inheritance (w.r.t. Bases classes while inheriting)
– Hybrid Inheritance
return to Access Specifers
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
132 of 176
Polymorphism (1/3)
• Polymorphism is based on following 3 concepts
– Adhoc Polymorphism
• Overloading (Early Binding or Compile-time Polymorphism)
– Dynamic Polymorphism
• Overriding (Late Binding or Run-time Polymorphism)
– Parametric Polymorphism
• Use of Templates (STL) for type-less description of user defined
data type (Classes, functions). Type is passed as argument and
Type resolution occurs at compilation time
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
133 of 176
Polymorphism (2/3)
• Overloading
– Overloaded declaration
• Specify more than one definition for a function name or an
operator in the same scope - called function overloading and
operator overloading respectively.
– Overload Resolution
• Process of selecting the most appropriate overloaded function or
operator during Function call
– The compiler determines the most appropriate definition to use by
comparing the argument types you used to call the function or
operator with the parameter types specified in the definitions.
– Operators that cannot be overloaded
• Scope resolution operator (::), access-pointer operator (.*),
member access operator (.), conditional operator (?:)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
134 of 176
Polymorphism (3/3)
• Overloading (contd.)
– Operator overloading with friend functions
– Constructor Overloading
• It is used to increase the flexibility of a class by having more
number of constructor for a single class.
• Objects can be initialized in more than one way using overloaded
constructors.
• Overriding
– A method in base class is defined with virtual keyword and
overridden by creating a similar method in derived class with
different definition to overcome static resolution (early
binding or static linkage).
Return to Virtual Functions
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
135 of 176
Interfaces (1/3)
• Describes the behavior or capabilities of a C++ class without
committing to a particular implementation of that class.
• The C++ interfaces are implemented using abstract classes.
– Note: Abstract classes should not be confused with data
abstraction (a concept of keeping implementation details
separate from associated data).
• A class is made abstract by declaring at least one of its
functions as pure virtual function.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
136 of 176
Interfaces (2/3)
• Abstract Class
– Provides an appropriate base class from which other classes
can inherit.
– Abstract classes cannot be used to instantiate objects and
serves only as an interface. Attempting to instantiate an object
of an abstract class causes a compilation error (i.e., Base Class
with no Objects).
• Concrete Class
– Subclass of an Abstract Class that is used to instantiate objects.
– It has to implement each of the virtual functions, which means
that it supports the interface declared by the Abstract Class.
– Failure to override a pure virtual function in a derived class,
then attempting to instantiate objects of that class causes a
compilation error.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
137 of 176
Interfaces (3/3)
• Ambiguity & Resolution
– Consider Classes A and B, both with a member named x. Class
C inherits from both A and B and attempts to access x from C
which would be ambiguous.
– Resolution: Qualifying a member with its class name & scope
resolution operator.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
138 of 176
Dynamic Memory (1/2)
• Memory in your C++ program is divided into two parts:
– Stack
• All variables declared inside the function will take up memory
from the stack.
– Heap
• This is the unused memory of the program that can be used for
dynamic allocation when program runs.
• Need of Dynamic Memory Allocation?
– Many times, the memory required to store particular
information in a defined variable is unknown. In such cases,
the size of required memory can be determined at run time.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
140 of 176
Dynamic Memory (2/2)
• new operator
– Special operator in C++ which returns the address of the heap
memory allocated at run time for the variable of a given type.
– The requested memory may be allocated if the heap had been
used up. So it is good practice to check if new operator is
returning NULL pointer before use.
– Syntax: new data-type;
• Data type could be any built-in data type (including array) or any
user defined data type (Class/objects or structure).
– Vs. malloc()
• Apart from memory allocation new operator constructs objects.
• delete operator
– De-allocate the memory dynamically allocated using new.
Return to Copy Constructor
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
141 of 176
Templates (1/3)
• Templates are the foundation of generic programming,
which involves writing code in a way that is independent of
any particular type.
• A template is a blueprint or formula for creating/defining a
generic class or a function.
• Types
– Function Template
– Class Template
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
143 of 176
Templates (2/3)
• Function Template
– The general form of a template function definition is:
template <class type>
return_type function_name(parameter list)
{
// body of function
}
– Here, type is a placeholder name for a data type used by the
function. This name can be used within the function definition.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
144 of 176
Templates (3/3)
• Class Template
– The general form of a generic class declaration is:
template <class type> class class_name
{
.
.
.
}
– Here, type is the placeholder type name, which will be
specified when a class is instantiated.
– More than one generic data type can be defined by using a
comma-separated list.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
145 of 176
Namespaces (1/5)
• Case study
– We have two students named Jessie in the same class.
Whenever it is needed to differentiate them definitely some
additional information should be used along with their name,
like either their parents name or date-of-birth.
– Learning
• Same situation can arise in C++ applications. For example, a C++
program has a function called xyz() and there is another library
available with another function with same name, xyz(). Now the
compiler has no way of knowing which version of xyz() function is
referred to within the program.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
147 of 176
Namespaces (2/5)
• A namespace is designed to overcome this difficulty and is
used as additional information to differentiate functions,
classes, variables etc. with the same name and available in
different libraries.
• Namespace defines the context in which names are defined.
i.e., Defines a scope.
• Definition
namespace namespace_name
{
// code declarations
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
148 of 176
Namespaces (3/5)
• Access to the namespace-enabled version of function or
variable
– (1) Prepend the namespace name with :: to function/variable.
– (2) Specify the namespace used to compiler with the using
namespace directive.
• The using directive can also be used to refer to a particular item
within a namespace. Hence the subsequent code can refer to the
item without prepending the namespace name. But other items
in the namespace will still need explicit prepending.
– E.g: cout and endl in namespace std
• Entities with the same name defined in an outer scope are
hidden.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
149 of 176
Namespaces (4/5)
• Dis-contiguous Namespaces
– A namespace can be defined in several parts.
– The separate parts of a namespace can be spread over
multiple files. So, if one part of the namespace requires a
name defined in another file, that name must still be declared.
• Following namespace definition either defines a new namespace
or adds new elements to an existing one:
namespace namespace_name
{
// code declarations
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
150 of 176
Namespaces (5/5)
• Nested Namespaces
– Namespaces can be defined one inside another as follows:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
– Member access
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
151 of 176
Exception Handling (1/8)
• A C++ exception is a response to a problem (exceptional
circumstance) that arises during program execution.
– E.g. An attempt to divide by zero.
• Exceptions provide a way to transfer control from one part
of a program to another.
• Exception handling is built upon three keywords: throw, try,
catch.
• Assuming a block will raise an exception, a method catches
an exception using a combination of the try and catch block.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
153 of 176
Exception Handling (2/8)
• Try block
– It identifies a code block referred to as protected code, that
might generate an exception.
– It can raise more than one exception in different situations.
– Syntax
try
{
// protected code
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
154 of 176
Exception Handling (3/8)
• Catch block
– It follows the try block to catch and handle an exception with
an exception handler at a place in the program.
– Exception declaration determines the type of exception to be
caught. It appears in parentheses following the keyword catch.
try
{
// protected code
}
catch( ExceptionName e1 )
{
// code to handle ExceptionName exception
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Exception Declaration
155 of 176
Exception Handling (4/8)
• Catch block (contd.)
– Handling multiple exceptions using (1) Multiple catch blocks,
(2) Exception declaration with Ellipsis inside parentheses.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
try
{
// protected code
}
catch( …)
{
// code to handle any exception
}
156 of 176
Exception Handling (5/8)
• Throw statement
– A program throws an exception when a problem shows up.
– The operand of throw statements determine an exception type.
The operand can be any expression. The result of the expression
determines the type of exception thrown.
double division (int a, int b)
{
if (b == 0)
{
throw "Division by zero condition!";
}
return (a/b);
}
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
157 of 176
Exception Handling (6/8)
• Standard Exceptions
– C++ provides a list of
standard exceptions
defined in <exception>
and arranged in a
parent-child class
hierarchy
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
158 of 176
Exception Handling (7/8)
• Standard Exceptions (contd.)
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Exception Description
std::exception An exception and parent class of all the standard C++ exceptions.
std::bad_alloc This can be thrown by new.
std::bad_cast This can be thrown by dynamic_cast.
std::bad_exception This is useful to handle unexpected exceptions in a C++ program
std::bad_typeid This can be thrown by typeid.
std::logic_error An exception that theoretically can be detected by reading the code.
std::domain_error This is an exception thrown when a mathematically invalid domain is used
std::invalid_argument This is thrown due to invalid arguments.
std::length_error This is thrown when a too big std::string is created
std::out_of_range
This can be thrown as a consequence of attempting to access elements out
of defined range.
std::runtime_error An exception that theoretically cannot be detected by reading the code.
std::overflow_error This is thrown if a mathematical overflow occurs.
std::range_error This occurs when storing a value that is out-of-range.
std::underflow_error This is thrown if a mathematical underflow occurs.
159 of 176
Exception Handling (8/8)
• Re-throwing Exceptions
– An exception can only be re-thrown from within a catch block.
When an exception is re-thrown, current exception is
propagated on to an outer try/catch sequence.
– Done by calling throw, by itself, with no exception or without
an argument.
• User-Defined Exceptions
– Exceptions can be user-defined in a standard way by inheriting
and overriding the exception class.
– The public method what() in exception class could be
overridden by all the child exception classes to return the
cause of an exception.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
160 of 176
Preprocessors (1/4)
• Preprocessors are directives, which give instruction to the
compiler to preprocess the information before actual
compilation starts.
• All preprocessor directives begin with #, and only white-
space characters may appear before a preprocessor directive
on a line.
• Preprocessor directives are not C++ statements, so they do
not end in a semicolon (;).
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
162 of 176
Preprocessors (2/4)
• Insert the contents of another file into source file.
– #include <file_name>
• Compiler searches for the given file to find it.
• Search is done through Standard Library directories.
– #include “file_name”
• Compiler does not search very hard for the file.
• Search is done through the current directory.
• Definition & Un-definition
– #define – create symbolic constants and function-like macros.
• Syntax: #define macro_name replacement_text
– #undef – un-defines a previously defined macro variable
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
163 of 176
Preprocessors (3/4)
• Conditional Compilation
– Directives can be used to compile/exclude selective portions of
program source code.
• Code Selection & Compilation
– #if, #elif, #endif
– #ifdef, #ifndef
#ifndef PI #ifdef PI
#define PI 3.14 cerr <<“PI is defined "<< endl;
#endif #endif
• Code Exclusion while Compilation
– #if 0
• #error directive
– Displays the diagnostic error message provided and renders
the program ill-formed as the compilation stops.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
164 of 176
Preprocessors (4/4)
• # directive
– Performs Stringification operation
• A # operator before an identifier in the replacement-list runs the
identifier through parameter replacement and encloses the
result in quotes, effectively creating a string literal.
• ## directive
– Performs Concatenation or Token passing operation
• A ## operator between any two successive identifiers in the
replacement-list runs parameter replacement on the two
identifiers and then concatenates the result.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
165 of 176
Files & Streams (1/9)
• To perform file processing in C++, header files <iostream>
and <fstream> must be included in source file.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Data Type Description
ofstream
Represents the output file stream and is used to create files and to
write information to files.
ifstream
Represents the input file stream and is used to read information
from files.
fstream
Represents the file stream generally, and has the capabilities of both
ofstream and ifstream. It is used to create files, read/write
information from/to files.
167 of 176
Files & Streams (2/9)
• Opening a File
– A file must be opened before read/write.
• ofstream/fstream object may be used to open a file for writing.
• ifstream object is used to open a file for reading purpose only.
• fstream object may be used to open a file for read & write.
– open() is a member of fstream, ifstream, and ofstream objects.
– Syntax:
• void open (const char *filename, ios::openmode mode);
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Mode in which file
should be opened
Name & Location of the
file to be opened
168 of 176
Files & Streams (3/9)
• Opening a File (contd.)
– File open modes
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Mode Description
ios::app Append mode. All output to the file is appended to the end.
ios::ate
Open a file for output and sets the initial position at the EOF.
If this is not used then then initial position is set at the BOF.
ios::in Open a file for reading.
ios::out Open a file for writing.
ios::trunc
If the file already exists & open for writing, its previous contents are deleted
before opening the file.
Ios::bin Open file in binary mode.
169 of 176
Files & Streams (4/9)
• Opening a File (contd.)
– A file can be opened in two or more modes using OR.
• Example:
– fstream obj; obj.open ("file.txt", ios::out | ios::in );
– Default file open modes
• i.e. File is opened without a second argument in open()
• Note: If another mode is passed as 2nd argument to open()
– ofstream & ifstream – default & passed arguments are ORed
– fstream – default mode is overridden & not combined
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
Class Default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
170 of 176
Files & Streams (5/9)
• Opening a File (contd.)
– The three classes include a constructor that automatically calls
open() and has the exact same parameters as this member.
• Example
– ofstream obj ("example.bin", ios::out | ios::app | ios::binary);
– is_open()
• Checks if a file stream was successful opening a file. This member
function returns a bool value.
• Example
– if (obj.is_open()) { /* Successful */ }
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
171 of 176
Files & Streams (6/9)
• Writing to a File
– Information can be written to a file using the stream insertion
operator (<<) as used to output information to the screen.
• The only difference is the usage of the ofstream/fstream object
instead of the cout object.
• Reading from a File
– Information from a file can be read using the stream extraction
operator (>>) as used to input information from the keyboard.
• The only difference is the usage of the ifstream/fstream object
instead of the cin object.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
172 of 176
Files & Streams (7/9)
• Closing a File
– Program termination automatically flushes all the streams,
releases all the allocated memory and closes all files opened.
– But it is always a good practice that a programmer should
close all the opened files before program termination.
– close() is a member of fstream, ifstream, and ofstream objects.
– Syntax:
• void close();
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
173 of 176
Files & Streams (8/9)
• Member functions for Random Access in files
– The 3 classes keeps an internal “position” in stream for read
(ifstream, fstream), write (ofstream, fstream)
– Repositioning file-position
• tellg() and tellp()
– These two member functions with no parameters return a value of
the member type streampos, which is a type representing the
current get position (in the case of tellg) or the put position (in the
case of tellp).
• seekg() – defined in ifstream.
• seekp() – defined in ofstream.
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
174 of 176
Files & Streams (9/9)
• Member functions for Random Access in files
– Arguments to seekg() and seekp()
• seekg (offset, direction);
• seekp (offset, direction);
– 1st argument: File location as a number of bytes (long integer).
– 2nd argument: File seek direction
» ios::beg (default) for positioning relative to beginning of a
stream
» ios::cur for positioning relative to current position in a stream
» ios::end for positioning relative to end of a stream
28-Mar-17
INFO121 - Advanced Data Structures
Instructor: Mr.S.Christalin Nelson
175 of 176
Programming in c++

More Related Content

What's hot

What's hot (20)

Lecture 1- History of C Programming
Lecture 1- History of C Programming Lecture 1- History of C Programming
Lecture 1- History of C Programming
 
Natural Language Processing for Tamil
Natural Language Processing for TamilNatural Language Processing for Tamil
Natural Language Processing for Tamil
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
kali linux
kali linuxkali linux
kali linux
 
Linux
LinuxLinux
Linux
 
Lisp
LispLisp
Lisp
 
Understand and optimize Linux I/O
Understand and optimize Linux I/OUnderstand and optimize Linux I/O
Understand and optimize Linux I/O
 
Storage system architecture
Storage system architectureStorage system architecture
Storage system architecture
 
Dennis Richie
Dennis RichieDennis Richie
Dennis Richie
 
Create a Unified View of Your Application Security Program – Black Duck Hub a...
Create a Unified View of Your Application Security Program – Black Duck Hub a...Create a Unified View of Your Application Security Program – Black Duck Hub a...
Create a Unified View of Your Application Security Program – Black Duck Hub a...
 
Advance linux presentation_0702011
Advance linux presentation_0702011Advance linux presentation_0702011
Advance linux presentation_0702011
 
An Introduction To Linux
An Introduction To LinuxAn Introduction To Linux
An Introduction To Linux
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
GDPS and System Complex
GDPS and System ComplexGDPS and System Complex
GDPS and System Complex
 
1. over view and history of c
1. over view and history of c1. over view and history of c
1. over view and history of c
 
Linux User Space Debugging & Profiling
Linux User Space Debugging & ProfilingLinux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
 
Computer Programming Overview
Computer Programming OverviewComputer Programming Overview
Computer Programming Overview
 
Cyber Threat Hunting Training (CCTHP)
Cyber Threat Hunting Training (CCTHP)Cyber Threat Hunting Training (CCTHP)
Cyber Threat Hunting Training (CCTHP)
 
Gstreamer plugin development
Gstreamer plugin development Gstreamer plugin development
Gstreamer plugin development
 

Viewers also liked

Ict handybook-la2-2-1
Ict handybook-la2-2-1Ict handybook-la2-2-1
Ict handybook-la2-2-1Azmiah Mahmud
 
SQL Sever 2012: Going Beyond the Data
SQL Sever 2012: Going Beyond the DataSQL Sever 2012: Going Beyond the Data
SQL Sever 2012: Going Beyond the DataJennifer Stevenson
 
TD-666-01-teknik-pemrograman
TD-666-01-teknik-pemrogramanTD-666-01-teknik-pemrograman
TD-666-01-teknik-pemrogramanTino Dwiantoro
 
role of nanotechnology in cosmetics
role of nanotechnology in cosmeticsrole of nanotechnology in cosmetics
role of nanotechnology in cosmeticsAakriti Kapoor
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
Sql 2012 development and programming
Sql 2012  development and programmingSql 2012  development and programming
Sql 2012 development and programmingLearnNowOnline
 
Регулярные выражения C++
Регулярные выражения C++Регулярные выражения C++
Регулярные выражения C++Dmitry Bulgakov
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
 
インフラ屋の友:Tera Term
インフラ屋の友:Tera Termインフラ屋の友:Tera Term
インフラ屋の友:Tera Termnetopscoding
 
recent updates in cosmetic technology
recent updates in cosmetic technologyrecent updates in cosmetic technology
recent updates in cosmetic technologyKhaled Al-Qaoud
 
Nanomaterials in cosmetics
Nanomaterials in cosmeticsNanomaterials in cosmetics
Nanomaterials in cosmeticsAnushi Jain
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17Sergey Platonov
 
Pt 2 matriks1-rev
Pt 2 matriks1-revPt 2 matriks1-rev
Pt 2 matriks1-revlecturer
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Treekhabbab_h
 

Viewers also liked (20)

Ict handybook-la2-2-1
Ict handybook-la2-2-1Ict handybook-la2-2-1
Ict handybook-la2-2-1
 
72
7272
72
 
SQL Sever 2012: Going Beyond the Data
SQL Sever 2012: Going Beyond the DataSQL Sever 2012: Going Beyond the Data
SQL Sever 2012: Going Beyond the Data
 
TD-666-01-teknik-pemrograman
TD-666-01-teknik-pemrogramanTD-666-01-teknik-pemrograman
TD-666-01-teknik-pemrograman
 
role of nanotechnology in cosmetics
role of nanotechnology in cosmeticsrole of nanotechnology in cosmetics
role of nanotechnology in cosmetics
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Analisa matriks
Analisa matriksAnalisa matriks
Analisa matriks
 
Mat.01.matrik
Mat.01.matrikMat.01.matrik
Mat.01.matrik
 
Sql 2012 development and programming
Sql 2012  development and programmingSql 2012  development and programming
Sql 2012 development and programming
 
Регулярные выражения C++
Регулярные выражения C++Регулярные выражения C++
Регулярные выражения C++
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
インフラ屋の友:Tera Term
インフラ屋の友:Tera Termインフラ屋の友:Tera Term
インフラ屋の友:Tera Term
 
recent updates in cosmetic technology
recent updates in cosmetic technologyrecent updates in cosmetic technology
recent updates in cosmetic technology
 
Nanomaterials in cosmetics
Nanomaterials in cosmeticsNanomaterials in cosmetics
Nanomaterials in cosmetics
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17
 
Gns3
Gns3Gns3
Gns3
 
Pt 2 matriks1-rev
Pt 2 matriks1-revPt 2 matriks1-rev
Pt 2 matriks1-rev
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 
Nanotechnology in nutraceuticals and cosmetics
Nanotechnology in nutraceuticals and cosmeticsNanotechnology in nutraceuticals and cosmetics
Nanotechnology in nutraceuticals and cosmetics
 

Similar to Programming in c++

Introduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaIntroduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaopenseesdays
 
Object oriented programming 2 elements of programming
Object oriented programming 2 elements of programmingObject oriented programming 2 elements of programming
Object oriented programming 2 elements of programmingVaibhav Khanna
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming languageVasavi College of Engg
 
Apache Spark sql
Apache Spark sqlApache Spark sql
Apache Spark sqlaftab alam
 
From Pipelines to Refineries: Scaling Big Data Applications
From Pipelines to Refineries: Scaling Big Data ApplicationsFrom Pipelines to Refineries: Scaling Big Data Applications
From Pipelines to Refineries: Scaling Big Data ApplicationsDatabricks
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...Jose Quesada (hiring)
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallJohn Mulhall
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassYogendra Rampuria
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
Database Systems - Lecture Week 1
Database Systems - Lecture Week 1Database Systems - Lecture Week 1
Database Systems - Lecture Week 1Dios Kurniawan
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9google
 
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...
Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...babak danyal
 
Parsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonParsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonDaniel S. Katz
 
From Pipelines to Refineries: scaling big data applications with Tim Hunter
From Pipelines to Refineries: scaling big data applications with Tim HunterFrom Pipelines to Refineries: scaling big data applications with Tim Hunter
From Pipelines to Refineries: scaling big data applications with Tim HunterDatabricks
 
NLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobil
NLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobilNLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobil
NLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobilDatabricks
 
Programming in C++ and Data Strucutres
Programming in C++ and Data StrucutresProgramming in C++ and Data Strucutres
Programming in C++ and Data StrucutresDr. C.V. Suresh Babu
 
Seminar on Parallel and Concurrent Programming
Seminar on Parallel and Concurrent ProgrammingSeminar on Parallel and Concurrent Programming
Seminar on Parallel and Concurrent ProgrammingStefan Marr
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programmingJuggernaut Liu
 

Similar to Programming in c++ (20)

_intro.ppt
_intro.ppt_intro.ppt
_intro.ppt
 
Introduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKennaIntroduction to OpenSees by Frank McKenna
Introduction to OpenSees by Frank McKenna
 
Object oriented programming 2 elements of programming
Object oriented programming 2 elements of programmingObject oriented programming 2 elements of programming
Object oriented programming 2 elements of programming
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 
Apache Spark sql
Apache Spark sqlApache Spark sql
Apache Spark sql
 
From Pipelines to Refineries: Scaling Big Data Applications
From Pipelines to Refineries: Scaling Big Data ApplicationsFrom Pipelines to Refineries: Scaling Big Data Applications
From Pipelines to Refineries: Scaling Big Data Applications
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
 
Introduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John MulhallIntroduction to Software - Coder Forge - John Mulhall
Introduction to Software - Coder Forge - John Mulhall
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
lecture1.ppt
lecture1.pptlecture1.ppt
lecture1.ppt
 
Database Systems - Lecture Week 1
Database Systems - Lecture Week 1Database Systems - Lecture Week 1
Database Systems - Lecture Week 1
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
 
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...
Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...Se 381 - lec 26  - 26 - 12 may30 - software design -  detailed design - se de...
Se 381 - lec 26 - 26 - 12 may30 - software design - detailed design - se de...
 
Parsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in PythonParsl: Pervasive Parallel Programming in Python
Parsl: Pervasive Parallel Programming in Python
 
From Pipelines to Refineries: scaling big data applications with Tim Hunter
From Pipelines to Refineries: scaling big data applications with Tim HunterFrom Pipelines to Refineries: scaling big data applications with Tim Hunter
From Pipelines to Refineries: scaling big data applications with Tim Hunter
 
NLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobil
NLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobilNLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobil
NLP-Focused Applied ML at Scale for Global Fleet Analytics at ExxonMobil
 
Programming in C++ and Data Strucutres
Programming in C++ and Data StrucutresProgramming in C++ and Data Strucutres
Programming in C++ and Data Strucutres
 
Seminar on Parallel and Concurrent Programming
Seminar on Parallel and Concurrent ProgrammingSeminar on Parallel and Concurrent Programming
Seminar on Parallel and Concurrent Programming
 
Reading Notes : the practice of programming
Reading Notes : the practice of programmingReading Notes : the practice of programming
Reading Notes : the practice of programming
 

More from Christalin Nelson

Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfChristalin Nelson
 
Relational_Algebra_Calculus Operations.pdf
Relational_Algebra_Calculus Operations.pdfRelational_Algebra_Calculus Operations.pdf
Relational_Algebra_Calculus Operations.pdfChristalin Nelson
 
Data Modeling - Enhanced ER diagrams & Mapping.pdf
Data Modeling - Enhanced ER diagrams & Mapping.pdfData Modeling - Enhanced ER diagrams & Mapping.pdf
Data Modeling - Enhanced ER diagrams & Mapping.pdfChristalin Nelson
 
Data Modeling - Entity Relationship Diagrams-1.pdf
Data Modeling - Entity Relationship Diagrams-1.pdfData Modeling - Entity Relationship Diagrams-1.pdf
Data Modeling - Entity Relationship Diagrams-1.pdfChristalin Nelson
 
Overview of Databases and Data Modelling-2.pdf
Overview of Databases and Data Modelling-2.pdfOverview of Databases and Data Modelling-2.pdf
Overview of Databases and Data Modelling-2.pdfChristalin Nelson
 
Overview of Databases and Data Modelling-1.pdf
Overview of Databases and Data Modelling-1.pdfOverview of Databases and Data Modelling-1.pdf
Overview of Databases and Data Modelling-1.pdfChristalin Nelson
 
Packages and Subpackages in Java
Packages and Subpackages in JavaPackages and Subpackages in Java
Packages and Subpackages in JavaChristalin Nelson
 
Advanced Data Structures - Vol.2
Advanced Data Structures - Vol.2Advanced Data Structures - Vol.2
Advanced Data Structures - Vol.2Christalin Nelson
 
Data Storage and Information Management
Data Storage and Information ManagementData Storage and Information Management
Data Storage and Information ManagementChristalin Nelson
 
Application Middleware Overview
Application Middleware OverviewApplication Middleware Overview
Application Middleware OverviewChristalin Nelson
 

More from Christalin Nelson (20)

Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdf
 
Relational_Algebra_Calculus Operations.pdf
Relational_Algebra_Calculus Operations.pdfRelational_Algebra_Calculus Operations.pdf
Relational_Algebra_Calculus Operations.pdf
 
Data Modeling - Enhanced ER diagrams & Mapping.pdf
Data Modeling - Enhanced ER diagrams & Mapping.pdfData Modeling - Enhanced ER diagrams & Mapping.pdf
Data Modeling - Enhanced ER diagrams & Mapping.pdf
 
Data Modeling - Entity Relationship Diagrams-1.pdf
Data Modeling - Entity Relationship Diagrams-1.pdfData Modeling - Entity Relationship Diagrams-1.pdf
Data Modeling - Entity Relationship Diagrams-1.pdf
 
Overview of Databases and Data Modelling-2.pdf
Overview of Databases and Data Modelling-2.pdfOverview of Databases and Data Modelling-2.pdf
Overview of Databases and Data Modelling-2.pdf
 
Overview of Databases and Data Modelling-1.pdf
Overview of Databases and Data Modelling-1.pdfOverview of Databases and Data Modelling-1.pdf
Overview of Databases and Data Modelling-1.pdf
 
Packages and Subpackages in Java
Packages and Subpackages in JavaPackages and Subpackages in Java
Packages and Subpackages in Java
 
Bitwise complement operator
Bitwise complement operatorBitwise complement operator
Bitwise complement operator
 
Advanced Data Structures - Vol.2
Advanced Data Structures - Vol.2Advanced Data Structures - Vol.2
Advanced Data Structures - Vol.2
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 
CPU Scheduling
CPU SchedulingCPU Scheduling
CPU Scheduling
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 
Process Management
Process ManagementProcess Management
Process Management
 
Applications of Stack
Applications of StackApplications of Stack
Applications of Stack
 
Data Storage and Information Management
Data Storage and Information ManagementData Storage and Information Management
Data Storage and Information Management
 
Application Middleware Overview
Application Middleware OverviewApplication Middleware Overview
Application Middleware Overview
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 

Recently uploaded (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 

Programming in c++

  • 2. At a Glance (1/3) • Generation of Programming Languages • Programming Language Paradigms • From C to C++ • Programming Basics – Program Structure and Environment – Statement & Terminator, Block, Identifier, Keyword, Tri-graphs – Variable & Data Types • Modifiers, sizeof(), Scope (Local/Global/Environment), Type Qualifier (const/volatile), Casting – Constant & Literals, Operators • Storage Class Specifiers • Looping & Decision Making 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 2 of 176
  • 3. At a Glance (2/3) • Functions – Basics, Function Callss, Inline Functions, Friend Functions, Virtual Functions • Access Modifiers • Arrays & Strings • Pointers & References • OOP Concepts – Encapsulation & Abstraction – Constructors & Destructors – Static Members – Inheritance – Polymorphism – Interfaces & Abstract Classes28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 3 of 176
  • 4. At a Glance (3/3) • Dynamic Memory Allocation • Templates • Namespaces • Exception Handling • Preprocessors • File Handling 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 4 of 176
  • 5.
  • 6. Generations • Generation -1: Machine Level Programming Languages (late 1940s) • Generation -2: Assembly Languages (early 1950s) • Generation -3: High-Level Languages (mid 1950s to present) • Generation -4: Specification/Query Language, Report Generators (1970s to present) • Generation -5: Artificial Intelligence 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 6 of 176
  • 7. Features of Languages (1/2) • Machine Level Language – Fast and efficient, executed directly on the CPU – Consists only of 0s and 1s – Difficult for humans to read, write, and debug • Assembly Language – Also included Interpreting Routines & early Compilers – Simple mnemonic instructions <opcode> <operands> – Assembler translates into machine code – Hand coding in assembly only for low-level needs 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 7 of 176
  • 8. Features of Languages (2/2) • High Level Languages – Easier for humans to read, write, debug – Compiler translates into machine code before running – Interpreter translates into machine code at runtime – Examples: FORTRAN, LISP, COBOL, ALGOL (Ada, Basic, C, C++, Java, Pascal, Smalltalk, …) • Fourth Generation – Examples: Maple, Mathematica, Postscript, SPSS, SQL • Fifth Generation – Examples: Prolog 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 8 of 176
  • 9. Family Tree of Languages 28-Mar-17 Fortran BASIC Cobol LISP Scheme ML Prolog PL/1 Algol 60 Algol 68 Pascal Modula 3 Ada C C++ Simula Smalltalk Java Dylan Ruby Perl PythonC# INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 9 of 176
  • 10.
  • 11. Procedural Paradigm • Procedures, sequential execution of code are basic building blocks of program • Examples – FORTRAN (FORmula TRANslating; John Backus, IBM, 1950s) – ALGOL (ALGOrithmic Language, 1958) – COBOL (COmmon Business Oriented Language, 1960) – BASIC (Beginner's All-purpose Symbolic Instruction Code, John Kemeny and Thomas Kurtz, Dartmouth, 1963) – Pascal (Niklaus Wirth, 1970) – C (Dennis Ritchie, Bell Labs, 1972) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson K. Thompson and D. Ritchie 11 of 176
  • 12. Object Oriented Paradigm • Program is designed around the objects required to solve the problem • Examples – Smalltalk (Alan Kay, Xerox PARC, 1971) – Ada (US Dept of Defense, 1975) – C++ (Bjarne Stroustrup, Bell Labs, 1983) – Java (James Gosling, Sun Microsystems, 1995) – C# (Microsoft, 2000) 28-Mar-17 Alan Kay B. Stroustrup J. Gosling INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 12 of 176
  • 13. Functional Paradigm • Program is designed around the evaluation of functions, rather than modifying state • Examples – LISP (John McCarthy, MIT, 1958) – Common Lisp – Dylan – Logo – Scheme – ML (Robin Milner et al, Edinburgh, 1970s) – Haskell (purely functional language, 1990) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 13 of 176
  • 14. Logic & Scripting Paradigms • Logic – Program is declarative, based on mathematical logic – Example: Prolog (1972) • Scripting – Used for text processing, shells, HTML, CGI – Examples • awk (Aho, Weinberger, Kerningham, Bell labs, 1978) • Perl (Larry Wall, NASA, 1987) • Tcl/Tk (John Ousterhout, 1988) • Python (Guido van Rossum, CWI, 1991) • PHP (Rasmus Lerdorf, 1995) • Ruby (Yukihiro Matsumoto, 1996) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 14 of 176
  • 15. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 15
  • 16.
  • 17. C Language (1/4) • Salient Features – Powerful and Efficient – Frequently used for small/medium sized programs – Compact obj. codes (after compilation) – Large presence (OS: Linux & Windows, DB: Oracle, TCP/IP) – Procedural / Structured Programming 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 17 of 176
  • 18. C Language (2/4) • Limitations – Inability to express large program as an abstraction (group together related data & functions) of smaller individual units • Programs Global view (single concept) is lost – Soln.: Modular programming support – Eg. Mark-sheet print prog., MS Word, VB prog., Car driving – Unsuited for very large scale programming (Modules are not totally independent) – No Mechanism for information reuse with little modification • Team Contribution & Correction due to error is difficult • Eg. Use of Employee Info. to HR & Payroll program – Can only identify Errors & cannot handle Exceptions 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 18 of 176
  • 19. C Language (3/4) • Limitations (contd.) – Features like Data Hiding, Polymorphism, Inheritance are not available – Top-down approach as opposed with Bottom-Top approach of C++ – NAMESPACE feature (which avoid name collision) is absent – Does not allow use of reference variables (two variable names point to the same memory location) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 19 of 176
  • 20. C Language (4/4) • Limitations (contd.) – C is not a Multi-paradigm language like C++. Hence C++ is: • Generic – Generalize concepts as templates & reuse them • Imperative – Work with a sequence of commands to change the state of program (Procedural / Structural) – Organize code in form of blocks of codes (functions, structure, etc.) that are executed to achieve expected output – Focus is on the process (Function driven) • Object-Oriented – Use classes which are blueprints of objects that share common behavior & properties – Focus is on the data & instructions 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 20 of 176
  • 21. C++ Language (1/3) • C++ is regarded as a middle-level language [Combination of both high-level and low-level language features] • C++ is superset of C • C++ does not impose Object Orientation to offer flexibility – Object-based Programming (OBP) offers more flexibility and more efficiency (Execution speed) than Object-Oriented Programming (OOP) • ANSI Standard – Ensures that C++ is portable • i.e. Code you write for Microsoft's compiler will compile without errors using a compiler on a Mac, UNIX, etc. – All the major C++ compiler manufacturers support the ANSI standard 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 21 of 176
  • 22. C++ Language (2/3) • Standard Libraries - three important parts – Core language • Gives all building blocks including variables, data types and literals, etc. – C++ Standard Library • Gives a set of functions for manipulating files, strings, etc. – Standard Template Library (STL) • Gives a set of methods for manipulating data structures like Queue, etc. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 22 of 176
  • 23. C++ Language (3/3) • C++ fully supports object-oriented programming including the four pillars of object-oriented development – Encapsulation – Data hiding – Inheritance – Polymorphism 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 23 of 176
  • 24.
  • 25. C++ program (1/4) • C++ Program can be considered as a collection of objects that communicate via invoking each other's methods • Definitions – Object - Objects have states and behaviors. An object is an instance of a class. – Class - A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support. – Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. – Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 25 of 176
  • 26. C++ program (2/4) • Defining Classes and Objects • Class vs. Object • Classes vs. C Structures – Contains Attributes & Functions – Controlled access to Attributes 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Class Object Abstract Data Type Variable of ADT Abstraction of what an object should have & should do, does nothing Instance of class that does the actions (method or function) Sketch from where actual objects are derived Objects can operate only on the functions owned by them 26 of 176
  • 27. C++ program (3/4) • Defining Member Functions – It is a function that has its definition or its prototype within the class definition like any other data member. • Defining a member function within the class definition declares the function inline, even if inline specifier is not used. • It can be defined outside the class definition using scope resolution operator (::). – It operates on any object of the class of which it is a member, and has access to all the members of a class for that object. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 27 of 176
  • 28. C++ program (4/4) • Accessing Data Members & Member Functions using a dot operator (.) on a object. • Memory Allocation – For Member function @Class Definition – For Member Data @Object definition 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 28 of 176
  • 29. Discussion (1/5) • Case: C++ program to maintain roll call of a class – Roll Call Procedure? – Entities & Types 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Roll Call System Entities Mapped from Real World Student Teacher Subject Designed for Program Roll Call 29 of 176
  • 30. Discussion (2/5) • Discussion [contd.] – Attributes & Types 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Attributes of Entity (Teacher) Data Attributes Name Subject Name Time Table Function Attributes Enroll Associate to subject Printing details 30 of 176
  • 31. Discussion (3/5) • Discussion [contd.] – Usefulness of Attributes – Experience & Intuition 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Attributes of Entity (Student) Useful Attributes • Data Attributes • Name • Address • Roll Number • Course Name • Function Attributes • Enrolment • Getting Mark Sheet • Exam Registration Attributes – not useful • Data Attributes • Name of Parents • List of Friends • Hobbies • Function Attributes • Add a Friend • Scrap • Upload Photo 31 of 176
  • 32. Discussion (4/5) • Discussion [contd.] – Designing Classes • Decide other Entities & Attributes of the Entire System (At larger scope) – A College Admin. System with 4 programs and their entities 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Roll Call Management Roll Call Teacher Student Mark sheet Printing Student Mark sheet Subject Subject maintenance Teacher Student Subject Teacher’s Information Management Teacher Student Subject 32 of 176
  • 33. Discussion (5/5) • Discussion [contd.] – Entities identified • Roll Call, Teacher, Student, Mark sheet, Subject – Associate Entities with programs – Find relations between Different Entities • How are Entities associated with each other? – E.g. Association of Teacher with Roll Call? – The method to generate the answer must be provided to the receiving entity – i.e. “Identify Methods inside Entity” 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 33 of 176
  • 34. Program Structure (1/2) • Sample Program #include <iostream> //Header file using namespace std; //Namespace class Student { //Class definition public: //Member Access Modifier int sap; //Data Member void printf() { cout<<sap; } //Member fn. definition }; int main() { // program execution begins Student obj1; // Creating object cin>>obj1.sap; // Member data access obj1.printf(); // Member function access return 0; }28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 34 of 176
  • 35. Program Structure (2/2) • # include <iostream.h> C++ language defines several headers, which contain information that is either necessary or useful to program. • using namespace std; tells the compiler to use the “std” namespace. Namespaces is a recent addition to C++. • // is a single-line comment available in C++ • int main() is the main function where program execution begins. • cout << "This is my first C++ program."; causes the message "This is my first C++ program" to be displayed on the screen. • return 0; terminates main( )function and causes it to return the value 0 to the calling process. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 35 of 176
  • 36. Compile & Execute • Open a editor to create a file – vi filename.cpp (or) notepad • Add the necessary code. • Save the file with .cpp extension. • Open a command prompt and go to the directory where you saved the file. Press ESC key followed with :wq (save & quit) • Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate “a.out” executable file. • Type ./a.out to run your program. • You will be able to see the desired output on the window. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 36 of 176
  • 37. Statement Terminator - Block - Identifier • Statement Terminator – Each individual statement must be ended with a semicolon. It indicates the end of one logical entity. • Block – Set of logically connected statements that are surrounded by opening and closing braces. • Identifier – It is a name used to identify a variable, function, class, module, or any other user-defined item. – Identifier starts with a letter A-Z or a-z or underscore (_) followed by zero or more letters, underscores, and digits (0-9). Special characters are not allowed within identifiers. – C++ is a case-sensitive programming language. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 37 of 176
  • 38. Keywords • Keywords are reserved words that may not be used as constant or variable or any other identifier names. – Alternative tokens28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq const Export mutable signed typedef const_cast Extern namespace sizeof typeid continue false new static typename asm default float operator static_cast union auto delete for private struct unsigned bool do friend protected switch using break double goto public template virtual case dynamic_cast if register this void catch else inline reinterpret_cast throw volatile char Enum int return true wchar_t class Explicit long short try while 38 of 176
  • 39. Digraphs • Two-letter alternative tokens that represents a single character and are expanded anywhere they appear • Example 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Primary Alternative { <% } %> [ <: ] :> # %: ## %:%: 39 of 176
  • 40. Trigraphs • Trigraph is a three-character sequence that represents a single character and are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives. • Note: – All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature. – For compilation of a program with trigraph • $g++ -trigraphs sample.cpp 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Primary Trigraph { ??< } ??> [ ??( ] ??) # ??= ??/ ^ ??' | ??! ~ ??- 40 of 176
  • 41. Variables (1/4) • Variables are reserved memory locations to store values. This means that some space in memory is created when a variable is created. • A variable provides a named storage that programs can manipulate. • Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 41 of 176
  • 42. Variables (2/4) • Variable Definition – Compiler is informed of where and how much storage is to be created for the variable. – Syntax: type variable_list; • Variable Initialization – Variables can be assigned an initial value in their definition. The initializer consists of equal sign followed by constant expression – Syntax: type variable_name = value; 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 42 of 176
  • 43. Variables (3/4) • Variable Declaration – Provides assurance to compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail. – Has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program. • While using multiple files, we define our variable in one of the files which will be available at the time of linking of the program. – A variable can be declared multiple times in a C++ program, but it can be defined only once in a file, a function or a block of code. – Use extern keyword to declare a variable at any place. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 43 of 176
  • 44. Variables (4/4) • There are two kinds of expressions in C++ – lvalue Expression • Refer to a memory location • An lvalue may appear as either the left-hand or right-hand side of an assignment. – Rvalue • Refers to a data value that is stored at some address in memory. • An rvalue may appear on the right- but not left-hand side of an assignment. – Note: • Variables are lvalues and so may appear on the left-hand side of an assignment. • Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 44 of 176
  • 45. Data Types (1/9) • Primitive Data types 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Type Keyword Description Boolean bool Stores either value true or false. Character char Typically a single octet(one byte). This is an integer type. Integer int The most natural size of integer for the machine. Floating point float A single-precision floating point value. Double floating point double A double-precision floating point value. Value-less void Represents the absence of type. Wide character wchar_t A wide character type. 45 of 176
  • 46. Data Types (2/9) • User-defined Data types – typedef types – Enumerated types • Typedef types – Creation of a new name for an existing type – Syntax: typedef type newname; – Example: typedef int feet; feet distance; • The above tells the compiler that ‘feet’ is another name for int and creates an integer variable called distance. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 46 of 176
  • 47. Data Types (3/9) • Enumerated Types – This type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration. – Syntax: enum enum-name { list of names } var-list; – Example: enum color { red, green, blue } c; c = blue; • The above tells the compiler that variable c (of enum type color) is assigned the value "blue“ = 2. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 47 of 176
  • 48. Data Types (4/9) • Derived Types – These types are derived from the primitive types. – Example: Pointer, Array, Reference, Data structures, Classes. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 48 of 176
  • 49. Data Types (5/9) • Modifiers – Basic types can be modified using one or more of these type • signed, unsigned, short, long – Modifiers signed, unsigned, long, and short can be applied to integer base types. – Modifiers signed and unsigned can also be applied to char, and long can also be applied to double. – The modifiers signed and unsigned can also be used as prefix to long or short modifiers. • Example: unsigned long int – C++ allows a shorthand notation for declaring unsigned, short, or long integers by simply using the word unsigned, short, or long, without the int. The int is implied. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 49 of 176
  • 50. Data Types (6/9) • sizeof() operator – To get size of various data types • Note: The sizes of variables might be different depending on the compiler and the computer being used. – Syntax: • sizeof() • sizeof expression – Example # include <iostream> using namespace std; main() { int a; cout << sizeof(int) << sizeof a << endl; } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 50 of 176
  • 51. Data Types (7/9) • Scope of Variables – A scope is a region of the program where variables can be declared • Local variable: Defined inside a function definition or a block. • Formal variable/parameter: Defined as a function’s parameter or argument. • Global variable: Defined outside all functions in a program. • Environment variable: Available for all applications/programs. They can be accessed anywhere in a program without declaring and initializing in an application or program. – Note: • A program can have same name for local and global variables but value of local variable inside a function will take preference. • Reference Variable is an alias to the actual variable created. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 51 of 176
  • 52. Data Types (8/9) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Initializing Local/Global Variables – When a local variable is defined, it is not initialized by the system, the programmer should initialize it instead. – Global variables are initialized automatically by the system according to the definition as follows: Data Type Initializer int 0 char '0' float 0 double 0 pointer NULL 52 of 176
  • 53. Data Types (9/9) • Type Qualifiers in C++ – They provide additional information about the variables they precede. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Qualifier Meaning const Objects of type const cannot be changed by your program during execution volatile The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program. 53 of 176
  • 54. Casting (1/2) • Implicit Cast – Support to Lossless Conversion (i.e. promotion) and Lossy Conversions (E.g. Mixed Mode Expressions) – Lossy conversions could be handled explicitly • Traditional C-style – Example » double a = 3.14; int b = (int) a; • Functional-style casting – Example » double a = 3.14; int b = int (a); 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 54 of 176
  • 55. Casting (2/2) • Implicit conversion with Classes – Implicit conversions can be controlled by means of 3 member functions • Single-argument Constructors: allow implicit conversion from a particular type to initialize an object. • Assignment Operator: allow implicit conversion from a particular type on assignments. • Type-cast Operator: allow implicit conversion to a particular type. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 55 of 176
  • 56. Constants/Literals (1/7) • Constants refer to fixed values that the program may not alter and they are called literals. • Constants can be of any of the basic data types – Integer Numerals – Floating-Point Numerals – Characters – Strings – Boolean Values • Constants are treated just like regular variables except that their values cannot be modified after their definition. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 56 of 176
  • 57. Constants/Literals (2/7) • Prefix and Suffix in Integer Literal – A prefix sometimes specifies the base or radix • 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. – A suffix is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. – Examples • 0213 // octal • 0x4b // hexadecimal • 30 // int • 30u // unsigned int • 30l // long 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 57 of 176
  • 58. Constants/Literals (3/7) • Floating-point Literal – Has an integer part, a decimal point, a fractional part, and an exponent part. – Can be represented either in decimal form or exponential form. • While representing using decimal form, decimal point, the exponent, or both must be included. • While representing using exponential form, the integer part, the fractional part, or both must be included. The signed exponent is introduced by e or E. – Examples • 3.14159 // Legal • 314159E-5L // Legal 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 58 of 176
  • 59. Constants/Literals (4/7) • Boolean Literal – There are two Boolean literals and they are part of standard C++ keywords • A value of true representing true. • A value of false representing false. – Neither the value of true or false should be considered equal to 1 or 0. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 59 of 176
  • 60. Constants/Literals (5/7) • Character Literal – They are enclosed in single quotes. • If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable. Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type. – A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., 't'), or a universal character (e.g., 'u02C0'). – Escape sequences • There are certain characters in C++ when they are preceded by a backslash they will have special meaning. • Example: newline (n), tab space (t) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 60 of 176
  • 61. Constants/Literals (6/7) • String Literal – They are enclosed in double quotes. – String contains characters that are similar to character literals. • E.g. Plain characters, escape sequences, and universal characters. – Note: A long line can be broken into multiple lines using string literals and separate them using whitespaces. – Examples (Are the following same?) • "hello, dear" • "hello, dear" • "hello, " "d" "ear" 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 61 of 176
  • 62. Constants/Literals (7/7) • Defining Constants – There are two simple ways in C++ to define: • Using #define preprocessor. [Symbolic Constants] – Syntax: #define identifier value • Using const keyword. – Syntax: const type variable = value; • Note: An enumerator can be used to define a group of symbolic constants. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 62 of 176
  • 63. Operators (1/10) • An operator is a symbol that tells the compiler to perform specific manipulations. • Types of built-in operators – Arithmetic Operators – Relational Operators – Logical Operators – Bitwise Operators – Assignment Operators – Miscellaneous Operators 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 63 of 176
  • 64. Operators (2/10) • Arithmetic Operators – Assume variable A holds 10 and variable B holds 20. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by denominator and provide quotient B / A will give 2 % Divides numerator by denominator and provide remainder B % A will give 0 ++ Increment Operator increases integer value by one A++ will give 11 -- Decrement Operator decreases integer value by one A-- will give 9 64 of 176
  • 65. Operators (3/10) • Relational Operators – Assume variable A holds 10 and variable B holds 20. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. 65 of 176
  • 66. Operators (4/10) • Logical Operators – Assume variable A holds 1 and variable B holds 0. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Operator Description Example && Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. || Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. ! Logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make false and otherwise. !(A && B) is true. 66 of 176
  • 67. Operators (5/10) • Bitwise Operators – Assume variable A holds 60 and variable B holds 13. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 (0000 1100) | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 (0011 1101) ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 (0011 0001) ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 (1100 0011) in 2's complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 (1111 0000) >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 (0000 1111) A = 0011 1100, B = 0000 1101 67 of 176
  • 68. Operators (6/10) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Assignment Operators Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A <<= Left shift AND assignment operator C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 268 of 176
  • 69. Operators (7/10) • Miscellaneous Operators (1/2) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Operator Description sizeof() sizeof() operator returns the size of a variable. For example, sizeof(a), where a is integer, will return 4. Condition ? X : Y Conditional operator If Condition is true ? then it returns value X : otherwise value Y , Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. . (dot) and -> (arrow) Member operators are used to reference individual members of classes, structures, and unions. Cast Casting operators convert one data type to another. For example, int(2.2000) would return 2. & Pointer address operator & returns the address of an variable. For example &a; will give actual address of the variable. * Pointer Indirection operator * is pointer to a variable. For example *var; will pointer to a variable var. 69 of 176
  • 70. Operators (8/10) • Miscellaneous Operators (2/2) – Member Operators • The dot operator is applied to the actual object. The arrow operator is used with a pointer to an object. – Cast Operators • Simple casting • Other casting operators – const_cast<type> (expr) – dynamic_cast<type> (expr) – reinterpret_cast<type> (expr) – static_cast<type> (expr) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 70 of 176
  • 71. Operators (9/10) • Operator Precedence (1/2) – Different operators have different priority. – Precedence determines how an expression is evaluated starting from high priority operators (with its operands) to low priority ones. – Associativity • Decide on how an expression is evaluated if it has operators with same precedence. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 71 of 176
  • 72. Operators (10/10) Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Operator Precedence (2/2) 72 of 176
  • 73.
  • 74. Storage Class Specifiers (1/5) • They define the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. • C++ storage classes – auto – register – static – extern – mutable 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 74 of 176
  • 75. Storage Class Specifiers (2/5) • auto storage class – It is the default storage class for all local variables. – Can only be used within functions. • register storage class – It is used to define local variables that should be stored in a register instead of RAM. • Note: Defining 'register' does not mean that the variable will always be stored in a register. It means that it MIGHT be stored in a register depending on hardware & implementation restrictions. – The register should only be used for variables that require quick access. E.g. Counters. – The variable has a maximum size equal to the register size and cannot have the unary '&' operator applied to it (as it does not have a memory location). 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 75 of 176
  • 76. Storage Class Specifiers (3/5) • static storage class – This instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to retain their values between function calls. – The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. – In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 76 of 176
  • 77. Storage Class Specifiers (4/5) • extern storage class – It is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. – When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. – The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 77 of 176
  • 78. Storage Class Specifiers (5/5) • mutable storage class – The mutable specifier applies only to class objects. – It allows a member of an object to override const definition. • A mutable data member of const object can be modified whereas a normal data member of const object cannot be modified. – Example • Class Employee has data members “salary”, “name”, and “id”. A constant object of this class assumes “name” and “id” to be constant, but not the “salary” when defined as mutable. i.e. An object’s “salary” can change, but “name” & “id” may not change. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 78 of 176
  • 79.
  • 80. Loops (1/4) • In general statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. • Execute a block of code several number of times? – Programming languages provide various control structures that allow for more complicated execution paths. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Loop Type Description while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loop Like a while statement, except that it tests the condition at the end of the loop body. nested loops You can use one or more loop inside any another while, for or do..while loop. 80 of 176
  • 81. Loops (2/4) • Flow Diagrams (Loop Control Structures) – While loop For loop do..while loop 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 81 of 176
  • 82. Loops (3/4) • Loop Control Statements – These statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Control Statement Description break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. goto statement Transfers control to the labeled statement. It is not advised to use goto statement in your program. 82 of 176
  • 83. Loops (4/4) • Flow Diagrams (Loop Control Statements) – break continue goto 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 83 of 176
  • 84. Decision making (1/6) Statement Description if statement An if statement consists of a boolean expression followed by one or more statements. if...else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. switch statement A switch statement allows a variable to be tested for equality against a list of values. nested if statements You can use one if or else if statement inside another if or else if statement(s). nested switch statements You can use one switch statement inside another switch statement(s). 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Basic understanding of relational operators is essential • Types 84 of 176
  • 85. Decision making (2/6) • If statement 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Test Condition 85 of 176
  • 86. Decision making (3/6) • If…else statement 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 86 of 176
  • 87. Decision making (4/6) • If…else if…statement – It is very useful to test various conditions. – Note: • An if can have zero or one else's and it must come after any else if's. • An if can have zero to many else if's and they must come before the else. • Once an else if succeeds, none of the remaining else if's or else's will be tested. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 87 of 176
  • 88. Decision making (5/6) • Switch statement (1/2) – Allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. – Constant-expression for a case must be the same data type as the variable in switch, and it must be a constant or a literal. – Can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 88 of 176
  • 89. Decision making (6/6) • Switch statement (2/2) – When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached and the switch terminates and the flow of control jumps to next line following switch statement. – Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. – A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 89 of 176
  • 90.
  • 91. Functions (1/10) • A function is a group of statements that together perform a task. It is also known as method or sub-routine or procedure. • Every C++ program has at least one function, which is main(), and can define additional functions. • The C++ standard library provides many built-in functions. • Function declaration – Tells the compiler about a function's name, return type, and parameters. – Syntax • return_type function_name( parameter list ); 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 91 of 176
  • 92. Functions (2/10) • Function definition – Provides the actual body of the function. – Parts of a Functions • Return Type • Function Name • Parameters – Function signature? • Function Body – Syntax return_type function_name( parameter list ) { body of the function } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 92 of 176
  • 93. Functions (3/10) • Function Call (1/2) – Invoke a function for using it. – Control Transfer • When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function- ending closing brace is reached, it returns program control back to the main program. • Return Value – If a function can return a value then it is necessary to store the returned value. – Required function Arguments/Parameters can be passed along with function name. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 93 of 176
  • 94. Functions (4/10) Call Type Description Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by pointer This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call by reference This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Function Call (2/2) – Types • Simple Call, Default Values, Call by value/pointer/reference 94 of 176
  • 95. Functions (5/10) Name Purpose double cos(double); This function takes an angle (as a double) and returns the cosine. double sin(double); This function takes an angle (as a double) and returns the sine. double tan(double); This function takes an angle (as a double) and returns the tangent. double log(double); This function takes a number and returns the natural log of that number. double pow(double, double); The first is a number you wish to raise and the second is the power you wish to raise it. double hypot(double, double); If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse. double sqrt(double); You pass this function a number and it gives you this square root. int abs(int); This function returns the absolute value of an integer that is passed to it. double fabs(double); This function returns the absolute value of any decimal number passed to it. double floor(double); Finds the integer which is less than or equal to the argument passed to it. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Built-in Functions in <cmath> 95 of 176
  • 96. Functions (6/10) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Home Work – Study the Built-in Functions in the following • <ctime> • <cstdlib> • <cstring> • <iomanip> • <string> • Functions with Default Arguments 96 of 176
  • 97. Functions (7/10) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Inline Function (1/2) – The compiler places a copy of the code of that function at each point where the function is called at compile time. – Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality. – To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. – A function definition in a class definition is an inline function definition, even without the use of the inline specifier. – Prefer inline functions over preprocessor macro. • Macros are forcibly inlined. 97 of 176
  • 98. Functions (8/10) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Inline Function (2/2) – It is a compiler optimization technique. • It saves overhead of variables push/pop on the stack, while function calling. • It saves overhead of return call from a function. • It increases locality of reference by utilizing instruction cache. • Inline the functions with small code size to get performance. – Virtual functions and function templates should not be inlined. – Issues • May increase function size so that it may not fit on the cache, causing lots of cache miss. • It may cause compilation overhead in case if the code inside inline function is changed. 98 of 176
  • 99. Functions (9/10) • Friend Function – Refer Access Modifiers – A friend function of a class is defined outside the scope of that class. It has the right to access any members (even private) of the class. – Even though the prototypes for friend functions appear in the class definition, friends are not member functions. – A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. – Note: • Friend Classes 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 99 of 176
  • 100. Functions (10/10) • Virtual Function – Refer Polymorphism – Implements the concept of Overriding. – A virtual function is declared in base class with virtual keyword and with another version in a derived class. This signals the compiler that static linkage for this function is overridden. – Function selected to be called at any given point in program is based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. – Pure Virtual Functions • A virtual function in base class is included without a meaningful definition so that it must be redefined in a derived class to suit the objects of that class. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 100 of 176
  • 101.
  • 102. Access Modifiers (1/2) • Provides access levels/restrictions for class members. • Types (specified by keywords): public, private, and protected. • Access levels are labelled sections within the class body. – A class can have multiple labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. • The default access for members and classes is private. • Note: – Data hiding is one of the important features of OOP which prevents the functions of a program to access directly the internal representation of a class type by using access specifiers and other related concepts. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 102 of 176
  • 103. Access Modifiers (2/2) Public Private Protected Visible to all classes Visible only to the class to which they belong. Visible only to the class to which they belong, and any subclasses. Global access. Its scope is not only within the class but also outside the class. Class access. It cannot be accessible by its derived members. Class access & Derived access. Used within the class in which it is defined and derived members of it. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Comparison • Refer Inheritance • Return to friend functions 103 of 176
  • 104.
  • 105. Arrays (1/2) • Data Structure which stores a fixed-size sequential collection of elements/variables of the same type. – Instead of declaring individual variables one array variable can be declared to represent individual variables. • All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. • Array declaration specifies the type of the elements and the number of elements required by an array. • Array elements can be initialized either one by one or using a single statement. • A specific element in an array is accessed by an index. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 105 of 176
  • 106. Arrays (2/2) • Types 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Concept Description Multi-dimensional arrays C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. Pointer to an array You can generate a pointer to the first element of an array by simply specifying the array name, without any index. Passing arrays to functions You can pass to the function a pointer to an array by specifying the array's name without an index. Return array from functions C++ allows a function to return an array. 106 of 176
  • 107. Strings (1/3) • C++ supports two types of string representations: – The C-style character string in <cstring> – The string object introduced with Standard C++ in <string> • C-style character array – This string is actually a one-dimensional array of characters which is terminated by a null character '0'. – Example: “str” is a string which holds 4 characters. • char str[] = "C++"; char str1[4] = "C++"; • char str2[] = {'C', '+', '+', '0'}; char str3[4] = {'C', '+', '+', '0'}; – Note: • Extraction operator >> considers a space as a terminating character. Hence get() can be used to read the text containing blank space – Example: cin.get(str, 4); 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 107 of 176
  • 108. Strings (2/3) • String object – To handle single word text, “cin” can be used – To handle text containing blank space getline() could be used instead of get() • Example: – string a; getline(cin, a); 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 108 of 176
  • 109. Strings (3/3) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Function (partial list) Purpose strcpy(s1, s2) Copies string s2 into string s1. strcat(s1, s2) Concatenates string s2 onto the end of string s1. strlen(s1) Returns the length of string s1. strcmp(s1, s2) Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. strchr(s1, ch) Returns a pointer to the first occurrence of character ch in string s1. strstr(s1, s2) Returns a pointer to the first occurrence of string s2 in string s1. 109 of 176
  • 110.
  • 111. Pointers (1/3) • Every variable is assigned a memory location. Every memory location has its address defined which can be accessed with: – Ampersand (&) or Memory Reference operator. – Asterisk (*) or Memory De-reference operator. • A pointer is a variable whose value is the address of another variable. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 111 of 176
  • 112. Pointers (2/3) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Related Topics Concept Description C++ pointer arithmetic There are 4 arithmetic operators that can be used on pointers: ++, --, +, - C++ pointer to pointer C++ allows you to have pointer on a pointer and so on. Null Pointers It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. It cannot be dereferenced. Void pointer Pointer can point to objects of any data type. It cannot be dereferenced directly. It must first be explicitly cast to another pointer type before it is dereferenced. Constant Pointers A pointer that cannot change the address its holding. Pointer to Constant A pointer through which one cannot change the value of variable it points. These type of pointers can change the address they point to but cannot change the value kept at those address. Constant pointer to constant Its a mixture of above two types of pointers. This pointer can neither change the address its pointing to nor it can change the value kept at that address. 112 of 176
  • 113. Pointers (3/3) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson • Related Topics Concept Description Array of pointers You can define arrays to hold a number of pointers. Pointers & arrays There is a close relationship between pointers and arrays. Passing pointers to functions Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. Return pointer from functions C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well. Function Pointer Pointer is assigned with a normal function and can be used for invoking it. C++ this pointer Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer. Pointer to class A pointer to a class is done exactly the same way a pointer to a structure. 113 of 176
  • 114. Reference Variable • It is an alias or another name for an already existing variable. – Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. • References vs Pointers 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Reference Variable Pointer Variable NULL references are not allowed. A reference must be connected to a legitimate piece of storage. Null Pointer exists. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time. 114 of 176
  • 115.
  • 116. Encapsulation • All programs are composed of two fundamental elements: – Program statements (code): This is the part of a program that performs actions. This includes functions. – Program data: The data is the information of the program which is affected by the program functions. • Encapsulation binds together the data and functions that manipulate the data. • Note: – Class members should be private unless exposure is required. – Making one class a friend of another class exposes the implementation details and reduces encapsulation. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 116 of 176
  • 117. Abstraction (1/3) • Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. – i.e., Represent the needed information in program without presenting the details to the user. • Example-1: Consider usage of a TV. – TV can be turned on/off, channels & volume can be tuned, and external components can be added. BUT its internal details like signal reception/translation, and function of the screen is unknown. – Thus a TV clearly separates its internal implementation from its external interface and users can have access through its interface without having zero knowledge of its internals. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 117 of 176
  • 118. Abstraction (2/3) • Example-2: Consider usage of cout in simple C++ program. – Classes are used to define ADTs and cout object of class ostream is used to stream data to standard output. The user need not understand how cout displays the text on the user's screen but needs to only know the public interface. The underlying implementation of cout is free to change. • Access labels/specifiers enforce Abstraction – Members defined with a public label are accessible to all parts of the program. Members defined with a private label are not accessible to code that uses the class. – A class may contain zero or more access labels. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 118 of 176
  • 119. Abstraction (3/3) • Benefits – Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object. – The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in interface or user-level code. • Designing Strategy – Abstraction separates code into interface and implementation. So while designing, the interface should be independent of the implementation and would remain intact amidst changes made to the underlying implementation. • Note: The program would need a recompilation with the latest implementation. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 119 of 176
  • 120. Constructors (1/3) • Class constructor is a special member function of a class that is executed whenever we create new objects of that class. • Constructors can be very useful for setting initial values for certain member variables. • Properties of a constructor – Has same name as the class. – Does not have any return type (not even void). • Types of Constructors – Default Constructors – Parameterized Constructors – Copy Constructors • Constructor Overloading 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 120 of 176
  • 121. Constructors (2/3) • Using Initialization Lists to initialize fields – If it is required to initialize the members of class then a parameterized constructor can be defined as: rect::rect (int len, int bre) : length (len), breadth(bre) { cout << "Object is being created, length = " << len << endl; } Above syntax is equal to the following syntax: rect::rect (int len, int bre) { cout << "Object is being created, length = " << len << endl; length = len; breadth = bre; } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 121 of 176
  • 122. Constructors (3/3) • Copy constructor – Refer Dynamic Memory – It creates an object by initializing it with an object of the same class, which has been created previously. – The copy constructor is used to: • Initialize one object from another object of the same type/class. • Copy an object to – Pass it as an argument to a function. – Return it from a function. – If a copy constructor is not defined in a class, the compiler itself defines one. – A class having pointer variables and some dynamic memory allocations should have a copy constructor. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 122 of 176
  • 123. Destructor • Class destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. • Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories, etc. • Properties of a Destructor – A destructor will have exact same name as the class prefixed with a tilde (~). – Does not have any return type at all, not even void. – It cannot take any parameters. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 123 of 176
  • 124. Static Members of Class (1/2) • When member of a class is declared as static – no matter how many objects of the class are created, there is only one copy of the static member. – i.e. A static member is shared by all objects of the class. • All static data members are initialized to zero when the first object is created, if no other initialization is present. – Static data members should be initialized outside the class using the scope resolution operator. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 124 of 176
  • 125. Static Members of Class (2/2) • Declaring a function member as static, makes it independent of any particular object of the class. – i.e. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator. – A static member function can only access static data member, other static member functions and any other functions from outside the class. – Static member functions have a class scope and they do not have access to the this pointer of the class. – A static member function can be used to determine whether some objects of the class have been created or not. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 125 of 176
  • 126. Inheritance (1/7) • Inheritance defines a class in terms of another class, which makes it easier to create and maintain an application. • It also provides an opportunity to reuse the code and fast implementation time. • Base class & Derived class – When creating a class, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. • The idea of inheritance implements the is-a relationship. – Example: mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 126 of 176
  • 127. Inheritance (2/7) • A class can be derived from more than one classes. – i.e. Class can inherit data and functions from multiple base classes. • Definition of a derived class – Use a class derivation list to specify the base class(es). – Syntax: • class derived-class: access-specifier base-class – Note: • If the access-specifier is not used, then it is private by default. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 127 of 176
  • 128. Inheritance (3/7) • A derived class can access all the non-private members of its base class. – Note: Base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class. • A derived class inherits all base class methods with the following exceptions – Constructors, destructors and copy constructors of the base class. – Overloaded operators of the base class. – The friend functions of the base class. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 128 of 176
  • 129. Inheritance (4/7) • Types of Inheritance (w.r.t. Access Specifier while inheriting) – Public Inheritance (Deriving a class from a public base class) • Public and Protected members of the base class become Public and Protected members of the derived class respectively. • Private members of base class are never accessible directly from a derived class - but can be accessed through calls to the public and protected members of the base class. – Protected Inheritance (Deriving from a protected base class) • Public and Protected members of the base class become Protected members of the derived class. – Private Inheritance (Deriving from a private base class) • Public and Protected members of the base class become Private members of the derived class. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 129 of 176
  • 130. Inheritance (5/7) • Types of Inheritance (w.r.t. Bases classes while inheriting) – Single Inheritance Multiple Inheritance 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 130 of 176
  • 131. Inheritance (6/7) • Types of Inheritance (w.r.t. Bases classes while inheriting) – Multi-level Inheritance Hierarchical Inheritance 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 131 of 176
  • 132. Inheritance (7/7) • Types of Inheritance (w.r.t. Bases classes while inheriting) – Hybrid Inheritance return to Access Specifers 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 132 of 176
  • 133. Polymorphism (1/3) • Polymorphism is based on following 3 concepts – Adhoc Polymorphism • Overloading (Early Binding or Compile-time Polymorphism) – Dynamic Polymorphism • Overriding (Late Binding or Run-time Polymorphism) – Parametric Polymorphism • Use of Templates (STL) for type-less description of user defined data type (Classes, functions). Type is passed as argument and Type resolution occurs at compilation time 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 133 of 176
  • 134. Polymorphism (2/3) • Overloading – Overloaded declaration • Specify more than one definition for a function name or an operator in the same scope - called function overloading and operator overloading respectively. – Overload Resolution • Process of selecting the most appropriate overloaded function or operator during Function call – The compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. – Operators that cannot be overloaded • Scope resolution operator (::), access-pointer operator (.*), member access operator (.), conditional operator (?:) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 134 of 176
  • 135. Polymorphism (3/3) • Overloading (contd.) – Operator overloading with friend functions – Constructor Overloading • It is used to increase the flexibility of a class by having more number of constructor for a single class. • Objects can be initialized in more than one way using overloaded constructors. • Overriding – A method in base class is defined with virtual keyword and overridden by creating a similar method in derived class with different definition to overcome static resolution (early binding or static linkage). Return to Virtual Functions 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 135 of 176
  • 136. Interfaces (1/3) • Describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. • The C++ interfaces are implemented using abstract classes. – Note: Abstract classes should not be confused with data abstraction (a concept of keeping implementation details separate from associated data). • A class is made abstract by declaring at least one of its functions as pure virtual function. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 136 of 176
  • 137. Interfaces (2/3) • Abstract Class – Provides an appropriate base class from which other classes can inherit. – Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error (i.e., Base Class with no Objects). • Concrete Class – Subclass of an Abstract Class that is used to instantiate objects. – It has to implement each of the virtual functions, which means that it supports the interface declared by the Abstract Class. – Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class causes a compilation error. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 137 of 176
  • 138. Interfaces (3/3) • Ambiguity & Resolution – Consider Classes A and B, both with a member named x. Class C inherits from both A and B and attempts to access x from C which would be ambiguous. – Resolution: Qualifying a member with its class name & scope resolution operator. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 138 of 176
  • 139.
  • 140. Dynamic Memory (1/2) • Memory in your C++ program is divided into two parts: – Stack • All variables declared inside the function will take up memory from the stack. – Heap • This is the unused memory of the program that can be used for dynamic allocation when program runs. • Need of Dynamic Memory Allocation? – Many times, the memory required to store particular information in a defined variable is unknown. In such cases, the size of required memory can be determined at run time. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 140 of 176
  • 141. Dynamic Memory (2/2) • new operator – Special operator in C++ which returns the address of the heap memory allocated at run time for the variable of a given type. – The requested memory may be allocated if the heap had been used up. So it is good practice to check if new operator is returning NULL pointer before use. – Syntax: new data-type; • Data type could be any built-in data type (including array) or any user defined data type (Class/objects or structure). – Vs. malloc() • Apart from memory allocation new operator constructs objects. • delete operator – De-allocate the memory dynamically allocated using new. Return to Copy Constructor 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 141 of 176
  • 142.
  • 143. Templates (1/3) • Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. • A template is a blueprint or formula for creating/defining a generic class or a function. • Types – Function Template – Class Template 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 143 of 176
  • 144. Templates (2/3) • Function Template – The general form of a template function definition is: template <class type> return_type function_name(parameter list) { // body of function } – Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 144 of 176
  • 145. Templates (3/3) • Class Template – The general form of a generic class declaration is: template <class type> class class_name { . . . } – Here, type is the placeholder type name, which will be specified when a class is instantiated. – More than one generic data type can be defined by using a comma-separated list. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 145 of 176
  • 146.
  • 147. Namespaces (1/5) • Case study – We have two students named Jessie in the same class. Whenever it is needed to differentiate them definitely some additional information should be used along with their name, like either their parents name or date-of-birth. – Learning • Same situation can arise in C++ applications. For example, a C++ program has a function called xyz() and there is another library available with another function with same name, xyz(). Now the compiler has no way of knowing which version of xyz() function is referred to within the program. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 147 of 176
  • 148. Namespaces (2/5) • A namespace is designed to overcome this difficulty and is used as additional information to differentiate functions, classes, variables etc. with the same name and available in different libraries. • Namespace defines the context in which names are defined. i.e., Defines a scope. • Definition namespace namespace_name { // code declarations } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 148 of 176
  • 149. Namespaces (3/5) • Access to the namespace-enabled version of function or variable – (1) Prepend the namespace name with :: to function/variable. – (2) Specify the namespace used to compiler with the using namespace directive. • The using directive can also be used to refer to a particular item within a namespace. Hence the subsequent code can refer to the item without prepending the namespace name. But other items in the namespace will still need explicit prepending. – E.g: cout and endl in namespace std • Entities with the same name defined in an outer scope are hidden. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 149 of 176
  • 150. Namespaces (4/5) • Dis-contiguous Namespaces – A namespace can be defined in several parts. – The separate parts of a namespace can be spread over multiple files. So, if one part of the namespace requires a name defined in another file, that name must still be declared. • Following namespace definition either defines a new namespace or adds new elements to an existing one: namespace namespace_name { // code declarations } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 150 of 176
  • 151. Namespaces (5/5) • Nested Namespaces – Namespaces can be defined one inside another as follows: namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } } – Member access // to access members of namespace_name2 using namespace namespace_name1::namespace_name2; 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 151 of 176
  • 152.
  • 153. Exception Handling (1/8) • A C++ exception is a response to a problem (exceptional circumstance) that arises during program execution. – E.g. An attempt to divide by zero. • Exceptions provide a way to transfer control from one part of a program to another. • Exception handling is built upon three keywords: throw, try, catch. • Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch block. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 153 of 176
  • 154. Exception Handling (2/8) • Try block – It identifies a code block referred to as protected code, that might generate an exception. – It can raise more than one exception in different situations. – Syntax try { // protected code } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 154 of 176
  • 155. Exception Handling (3/8) • Catch block – It follows the try block to catch and handle an exception with an exception handler at a place in the program. – Exception declaration determines the type of exception to be caught. It appears in parentheses following the keyword catch. try { // protected code } catch( ExceptionName e1 ) { // code to handle ExceptionName exception } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Exception Declaration 155 of 176
  • 156. Exception Handling (4/8) • Catch block (contd.) – Handling multiple exceptions using (1) Multiple catch blocks, (2) Exception declaration with Ellipsis inside parentheses. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } try { // protected code } catch( …) { // code to handle any exception } 156 of 176
  • 157. Exception Handling (5/8) • Throw statement – A program throws an exception when a problem shows up. – The operand of throw statements determine an exception type. The operand can be any expression. The result of the expression determines the type of exception thrown. double division (int a, int b) { if (b == 0) { throw "Division by zero condition!"; } return (a/b); } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 157 of 176
  • 158. Exception Handling (6/8) • Standard Exceptions – C++ provides a list of standard exceptions defined in <exception> and arranged in a parent-child class hierarchy 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 158 of 176
  • 159. Exception Handling (7/8) • Standard Exceptions (contd.) 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Exception Description std::exception An exception and parent class of all the standard C++ exceptions. std::bad_alloc This can be thrown by new. std::bad_cast This can be thrown by dynamic_cast. std::bad_exception This is useful to handle unexpected exceptions in a C++ program std::bad_typeid This can be thrown by typeid. std::logic_error An exception that theoretically can be detected by reading the code. std::domain_error This is an exception thrown when a mathematically invalid domain is used std::invalid_argument This is thrown due to invalid arguments. std::length_error This is thrown when a too big std::string is created std::out_of_range This can be thrown as a consequence of attempting to access elements out of defined range. std::runtime_error An exception that theoretically cannot be detected by reading the code. std::overflow_error This is thrown if a mathematical overflow occurs. std::range_error This occurs when storing a value that is out-of-range. std::underflow_error This is thrown if a mathematical underflow occurs. 159 of 176
  • 160. Exception Handling (8/8) • Re-throwing Exceptions – An exception can only be re-thrown from within a catch block. When an exception is re-thrown, current exception is propagated on to an outer try/catch sequence. – Done by calling throw, by itself, with no exception or without an argument. • User-Defined Exceptions – Exceptions can be user-defined in a standard way by inheriting and overriding the exception class. – The public method what() in exception class could be overridden by all the child exception classes to return the cause of an exception. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 160 of 176
  • 161.
  • 162. Preprocessors (1/4) • Preprocessors are directives, which give instruction to the compiler to preprocess the information before actual compilation starts. • All preprocessor directives begin with #, and only white- space characters may appear before a preprocessor directive on a line. • Preprocessor directives are not C++ statements, so they do not end in a semicolon (;). 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 162 of 176
  • 163. Preprocessors (2/4) • Insert the contents of another file into source file. – #include <file_name> • Compiler searches for the given file to find it. • Search is done through Standard Library directories. – #include “file_name” • Compiler does not search very hard for the file. • Search is done through the current directory. • Definition & Un-definition – #define – create symbolic constants and function-like macros. • Syntax: #define macro_name replacement_text – #undef – un-defines a previously defined macro variable 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 163 of 176
  • 164. Preprocessors (3/4) • Conditional Compilation – Directives can be used to compile/exclude selective portions of program source code. • Code Selection & Compilation – #if, #elif, #endif – #ifdef, #ifndef #ifndef PI #ifdef PI #define PI 3.14 cerr <<“PI is defined "<< endl; #endif #endif • Code Exclusion while Compilation – #if 0 • #error directive – Displays the diagnostic error message provided and renders the program ill-formed as the compilation stops. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 164 of 176
  • 165. Preprocessors (4/4) • # directive – Performs Stringification operation • A # operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. • ## directive – Performs Concatenation or Token passing operation • A ## operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers and then concatenates the result. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 165 of 176
  • 166.
  • 167. Files & Streams (1/9) • To perform file processing in C++, header files <iostream> and <fstream> must be included in source file. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Data Type Description ofstream Represents the output file stream and is used to create files and to write information to files. ifstream Represents the input file stream and is used to read information from files. fstream Represents the file stream generally, and has the capabilities of both ofstream and ifstream. It is used to create files, read/write information from/to files. 167 of 176
  • 168. Files & Streams (2/9) • Opening a File – A file must be opened before read/write. • ofstream/fstream object may be used to open a file for writing. • ifstream object is used to open a file for reading purpose only. • fstream object may be used to open a file for read & write. – open() is a member of fstream, ifstream, and ofstream objects. – Syntax: • void open (const char *filename, ios::openmode mode); 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Mode in which file should be opened Name & Location of the file to be opened 168 of 176
  • 169. Files & Streams (3/9) • Opening a File (contd.) – File open modes 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Mode Description ios::app Append mode. All output to the file is appended to the end. ios::ate Open a file for output and sets the initial position at the EOF. If this is not used then then initial position is set at the BOF. ios::in Open a file for reading. ios::out Open a file for writing. ios::trunc If the file already exists & open for writing, its previous contents are deleted before opening the file. Ios::bin Open file in binary mode. 169 of 176
  • 170. Files & Streams (4/9) • Opening a File (contd.) – A file can be opened in two or more modes using OR. • Example: – fstream obj; obj.open ("file.txt", ios::out | ios::in ); – Default file open modes • i.e. File is opened without a second argument in open() • Note: If another mode is passed as 2nd argument to open() – ofstream & ifstream – default & passed arguments are ORed – fstream – default mode is overridden & not combined 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson Class Default mode parameter ofstream ios::out ifstream ios::in fstream ios::in | ios::out 170 of 176
  • 171. Files & Streams (5/9) • Opening a File (contd.) – The three classes include a constructor that automatically calls open() and has the exact same parameters as this member. • Example – ofstream obj ("example.bin", ios::out | ios::app | ios::binary); – is_open() • Checks if a file stream was successful opening a file. This member function returns a bool value. • Example – if (obj.is_open()) { /* Successful */ } 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 171 of 176
  • 172. Files & Streams (6/9) • Writing to a File – Information can be written to a file using the stream insertion operator (<<) as used to output information to the screen. • The only difference is the usage of the ofstream/fstream object instead of the cout object. • Reading from a File – Information from a file can be read using the stream extraction operator (>>) as used to input information from the keyboard. • The only difference is the usage of the ifstream/fstream object instead of the cin object. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 172 of 176
  • 173. Files & Streams (7/9) • Closing a File – Program termination automatically flushes all the streams, releases all the allocated memory and closes all files opened. – But it is always a good practice that a programmer should close all the opened files before program termination. – close() is a member of fstream, ifstream, and ofstream objects. – Syntax: • void close(); 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 173 of 176
  • 174. Files & Streams (8/9) • Member functions for Random Access in files – The 3 classes keeps an internal “position” in stream for read (ifstream, fstream), write (ofstream, fstream) – Repositioning file-position • tellg() and tellp() – These two member functions with no parameters return a value of the member type streampos, which is a type representing the current get position (in the case of tellg) or the put position (in the case of tellp). • seekg() – defined in ifstream. • seekp() – defined in ofstream. 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 174 of 176
  • 175. Files & Streams (9/9) • Member functions for Random Access in files – Arguments to seekg() and seekp() • seekg (offset, direction); • seekp (offset, direction); – 1st argument: File location as a number of bytes (long integer). – 2nd argument: File seek direction » ios::beg (default) for positioning relative to beginning of a stream » ios::cur for positioning relative to current position in a stream » ios::end for positioning relative to end of a stream 28-Mar-17 INFO121 - Advanced Data Structures Instructor: Mr.S.Christalin Nelson 175 of 176