Chapter 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 47

Object Oriented

Programming
with C++

Reema Thareja

© Oxford University Press 2015. All rights reserved.


Chapter Two
Basics of C++
Programming

© Oxford University Press 2015. All rights reserved.


INTRODUCTION TO C++

• C++ is a general purpose programming language developed by


Bjarne Stroustrup in 1979 at Bell Labs. Similar to C
programming, C++ is also considered as an intermediate level
language because it includes the features of both high-level
and low-level languages.
• C++ is a very popular programming language that can be
implemented on a wide variety of hardware and operating
system platforms.
• It is a powerful language for high-performance applications,
including writing operating systems, system software,

© Oxford University Press 2015. All rights reserved.


INTRODUCTION TO C++

• application software, device drivers, embedded software, high-


performance client and server applications, software
engineering, graphics, games, and animation software.
• C++ is an object oriented programming (OOP) language and
facilitates design, reuse, and maintenance for complex
software.

© Oxford University Press 2015. All rights reserved.


HISTORY OF C++

• In 1979, Bjarne Stroustrup started working on ‘C with Classes’, with an aim to


integrate OOP features such as classes, inheritance, inline functions, and default
arguments with the C language.
• This new language was easily portable and fast, provided low-level functionality, and
included OOP concepts.
• In 1983, the name of the language was changed to C++, where ++ refers to adding
new features in the C language. At this time, some more features such as virtual
functions, function overloading, references with the & symbol, const keyword, and
single-line comments were added.
• C++ was again updated to include protected members, static members, and multiple
inheritance in 1990.
• The latest version of C++ known as C++11 was released in 2011. It added new
features such as support for regular expression, a new C++ time library, atomics
support, a standard threading library, a new for loop syntax (similar to for each
loop), the auto keyword, new container classes,
and better support for unions and array-initialization.
© Oxford University Press 2015. All rights reserved.
STRUCTURE OF C++ PROGRAM

• The preprocessor directives contain special instructions


that indicate how to prepare the program for
compilation.
• Global declaration section is used to declare data
(variables), functions, and structures that have global
scope.
• The class declaration and method definition section can
be considered as a part of global declaration section that
is used to declare classes the execution of a C++
program begins at this function as the operating system
automatically calls it main().
• The method definition section is optional and required
only if there are functions other than class methods in
the program

© Oxford University Press 2015. All rights reserved.


Writing the first C++ Program

© Oxford University Press 2015. All rights reserved.


Files used in C++ Program

• The source code file contains the source code of the program.
The file extension of any C++ source code file is .cpp .
• There are functions which are used without coding. These
functions are already written and compiled for ease of
programmers. We just need to link the desired library
function’s code with our code.
• Such functions provided by all C++ compilers are included in
standard header files.

© Oxford University Press 2015. All rights reserved.


Files used in C++ Program
• Object files are generated by the compiler after processing the
source code file. Object files contain a compact binary code of
the function definitions
• The binary executable file is generated by the linker. The
linker links the various object files to produce a binary file that
can be directly executed.

© Oxford University Press 2015. All rights reserved.


Using comments
• Comments are used to explain what a program does.
• They are non-executable statements.
• C++ supports two types of commenting.
• // is used to comment a single statement. This is known as a line comment.
• /* is used to comment multiple statements. A /* is ended with */ and all
statements that lie within these characters are commented. This type of
comment is known as block comment.

© Oxford University Press 2015. All rights reserved.


COMPILING AND EXECUTING C++ PROGRAMS
• The programming process starts with creating a source file
that consists of the statements of the program written in C++
language.
• The compiler translates the source code into an object code the
object file is processed with another special program called a
linker.
• The output of the linker is an executable or runnable file.

© Oxford University Press 2015. All rights reserved.


TOKENS IN C++

• Tokens are the basic buildings blocks in C++


language. You may think of a token as the
smallest individual unit in a C++ program.
• This means that a program is constructed
using a combination these tokens.
• There are six main types of tokens in C++.

© Oxford University Press 2015. All rights reserved.


CHARACTER SET

• Computer languages also use a character set that defines the


fundamental raw material used to represent information.
• In C++, a character means any alphabet, digit, or special
symbols used to represent information. These characters when
combined together forms a token that acts as the basic building
block of a C++ program. The character set of C++ can,
therefore, be given as:
• Alphabets include both lower case (a − z) as well as upper
case (A − Z) characters.

© Oxford University Press 2015. All rights reserved.


CHARACTER SET

• Digits include numerical digits from 0 to 9.


• Special characters include symbols like ~, @, %, ^, &, ∗,{, },
<. >, =, _, +, −, $, /, , (, ), \, ;, :, [, ], ‘, “, ?, ., !,.
• White space characters are used to print a blank space on the
screen.
• Escape sequences have already been discussed in Section 2.8.
They include- \\, \’, \”, \n, \a, \0, \?.

© Oxford University Press 2015. All rights reserved.


KEYWORDS

• C++ has a set of reserved words, often known as keywords


that cannot be used as an identifier. All keywords are basically
a sequence of characters that have a fixed meaning.
• The meaning of a keyword cannot be changed by the
programmer. Conventionally, all keywords must be written in
lowercase.

© Oxford University Press 2015. All rights reserved.


IDENTIFIER
• Identifiers, as the name suggests, helps us to identify data and other objects
in the program. Identifiers are basically the names given to program
elements such as variables, arrays, and functions.
• An identifier may consist of an alphabet, digit, or an underscore.
• The name cannot include any special characters or punctuation marks,
except the underscore "_" .There cannot be two successive underscores.
• Keywords cannot be used as identifiers.
• The case of alphabetic characters that form the identifier name is
significant. The identifier name must begin with an alphabet or an
underscore.
• Identifiers can be of any reasonable length.

© Oxford University Press 2015. All rights reserved.


DATA TYPES IN C++

• Data are used to represent information.

© Oxford University Press 2015. All rights reserved.


VARIABLES

• Variable is defined as a meaningful name given to the data


storage location in computer memory.
• When using a variable, we actually refer to address of the
memory where the data is stored.
• Numeric variables can be used to store either integer values or
floating point values.
• Character variables can include any letter from the alphabet or
from the ASCII chart and numbers 0 – 9 inserted between
single quotes.
• In C++, a number that is put in single quotes is not the same
as a number without them.

© Oxford University Press 2015. All rights reserved.


Declaring Variables
• Each variable to be used in the program must be declared. To declare a
variable, specify the data type of the variable, followed by its name.
• In C++, variables are declared at three basic places as follows:
• First, when a variable is declared inside a function it is known as a local
variable.
• Second, when a variable is declared in the definition of function
parameters, it is known as formal parameter (we will study this in Chapter
4).
• Third, when the variable is declared outside all functions, it is known as a
global variable.

© Oxford University Press 2015. All rights reserved.


Initializing Variables

© Oxford University Press 2015. All rights reserved.


Reference Variables
• Reference variable is a new feature added to C++. A reference variable
basically assigns an alternative name (alias) to an existing variable.
• For example, if we want a variable num to be a reference to the variable n ,
then n and num can be interchangeably used to represent that variable.
• This is same as if someone calls us by our nick name or by our formal
name, both names refer to the same person.
• Therefore, if we write

© Oxford University Press 2015. All rights reserved.


CONSTANTS
• Constants are identifiers whose value does not change. While variables can
change their value at any time, constants can never change their value.
• Constants are used to define fixed values such as Pi or the charge on an
electron so that their value does not get changed in the program even by
mistake.
• A constant is an explicit data value specified by the programmer.
• The value of the constant is known to the compiler at the compile time.

© Oxford University Press 2015. All rights reserved.


Declaring Constants
• Rule 1 Constant names are usually written in capital letters to
visually distinguish them from other variable names which are
normally written in lower case characters.
• Rule 2 No blank spaces are permitted in between the # symbol
and define keyword.
• Rule 3 Blank space must be used between #define and
constant name and between constant name and constant value.
• Rule 4 #define is a preprocessor compiler directive and not a
statement. Therefore, it does not end with a semi-colon.

© Oxford University Press 2015. All rights reserved.


Streams
• A stream involves transfer of information as a sequence of bytes. A stream
acts in two ways. It is the source as well as the destination of data. C++
programs input data and output data from a stream.
• Streams are associated with a physical device such as the monitor or with
a file stored on the secondary memory.
• In a text stream, the sequence of characters is divided into lines, with each
line being terminated.
• With a new-line character (\n) . On the other hand, a binary stream contains
data values using their memory representation.

© Oxford University Press 2015. All rights reserved.


Cascading of Input or Output Operators

• We can use the << operator multiple times in the same line.
This is called cascading.
• Similar to cout, cin can also be cascaded. For example,

© Oxford University Press 2015. All rights reserved.


Reading and Writing Characters and Strings

© Oxford University Press 2015. All rights reserved.


Formatted Input and Output Operations

© Oxford University Press 2015. All rights reserved.


Formatting with Flags

• The setf() is a member function of the ios class that is used to


set flags for formatting output.
• The syntax for setf function that stands for set flags can be
given as cout.setf(flag, bit-field)
• Here, flag defined in the ios class specifies how the output
should be formatted and bit-field is a constant (defined in ios )
that identifies the group to which the formatting flag belongs
to.
• There are two types of setf()—one that takes both flag and
bit-fields and the other that takes only the flag .

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights reserved.
© Oxford University Press 2015. All rights
reserved.
Formatted Output Using Manipulators

• C++ has a header file iomanip.h that contains certain


manipulators to format the output.
• Though you can do the same formatting using ios class flags ,
formatting with manipulators is easier to learn and convenient
to use.

© Oxford University Press 2015. All rights reserved.


© Oxford University Press 2015. All rights r
eserved.
OPERATORS IN C++

• An operator is defined as a symbol that specifies the


mathematical, logical, or relational operation to be performed.
• C++ language supports a lot of operators to be used in
expressions. These operators can be categorized into the
following major groups:
• Arithmetic operators Relational operators
• Equality operators Logical operators
• Unary operators Conditional operators
• Bitwise operators Assignment operators
• Comma operator Sizeof operator

© Oxford University Press 2015. All rights reserved.


Arithmetic Operators

© Oxford University Press 2015. All rights reserved.


Relational Operators

Equality Operators

© Oxford University Press 2015. All rights reserved.


Logical Operators

© Oxford University Press 2015. All rights reserved.


Unary Minus (-)

• Unary minus operator is strikingly different from the binary


arithmetic operator that operates on two operands and
subtracts the second operand from the first operand. When an
operand is preceded by a minus sign, the unary operator
negates its value.
• For example, if a number is positive, it becomes negative
when preceded with a unary minus operator. Similarly, if the
number is negative, it becomes positive after applying the
unary minus operator.

© Oxford University Press 2015. All rights reserved.


Increment Operator (++) and Decrement
Operator (−−)
• The increment operator is a unary operator that increases the
value of its operand by 1 .
• Similarly, the decrement operator decreases the value of its
operand by 1. For example, −−x is equivalent to writing x = x
− 1.
• The increment/decrement operators have two variants—
prefix or postfix. In a prefix expression(++x or −−x) , the
operator is applied before an operand is fetched for
computation; thus, the altered value is used for the
computation of the expression in which it occurs.

© Oxford University Press 2015. All rights reserved.


Increment Operator (++) and Decrement
Operator (−−)
• On the contrary, in a postfix expression (x++ or x−−) , an
operator is applied after an operand is fetched for computation.
• Therefore, the unaltered value is used for the computation of
the expression in which it occurs.

© Oxford University Press 2015. All rights reserved.


Conditional Operators

© Oxford University Press 2015. All rights reserved.


Bitwise Operators

© Oxford University Press 2015. All rights reserved.


Assignment Operators

© Oxford University Press 2015. All rights reserved.


Comma Operator

• The comma operator in C++ takes two operands. It works by


evaluating the first and discarding its value, and then evaluates
the second and returns the value as the result of the expression.
• Comma separated operands, when chained together, are
evaluated in a left-to-right sequence with the rightmost value
yielding the result of the expression.
• Among all the operators, the comma operator has the lowest
precedence.
• Therefore, when a comma operator is used, the entire
expression evaluates to the value of the right expression.

© Oxford University Press 2015. All rights reserved.


Size of Operator
• The sizeof is a unary operator used to calculate the sizes of
data types. It can be applied to all data types.
• When using this operator, the keyword ‘ sizeof ’ is followed by
a type name, variable, or expression.
• The operator returns the size of the variable, data type, or
expression in bytes. Therefore, the sizeof operator is used to
determine the amount of memory space that the variable,
expression, or data type will take.

© Oxford University Press 2015. All rights reserved.


Size of Operator

• When a type name is used, it is enclosed in parentheses;


however, in case of variable names and expressions, they can
be specified with or without parentheses.
• A sizeof expression returns an unsigned value that specifies
the size the space in bytes required by the data type, variable,
or expression.

© Oxford University Press 2015. All rights reserved.


Type conversion and type casting
• Type conversion or typecasting of variables refers to changing
a variable of one data type into another. While type conversion
is done implicitly, casting has to be done explicitly by the
programmer.

© Oxford University Press 2015. All rights reserved.


Type Casting

• Type casting an arithmetic expression tells the compiler to


represent the value of the expression in a certain format.
• It is done when the value of a higher data type has to be
converted into the value of a lower data type.
• However, this cast is under the programmer’s control and not
under the compiler’s control. The general syntax for type
casting is destination_variable_name=destination_data_ty--
pe(source_variable_name);

© Oxford University Press 2015. All rights reserved.

You might also like