smu c++ slm unit 1
TRANSCRIPT
-
7/31/2019 SMU C++ SLM UNIT 1
1/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 1
Unit 1 Introduction to OOP and C++
Structure
1.1 Introduction
1.2 Evolution of Programming methodologies
Self Assessment Questions
1.3 Introduction to OOP and its basic features
Self Assessment Questions
1.4 Basic components of a C++ Program and program structure
Self Assessment Questions1.5 Compiling and Executing C++ Program
Self Assessment Questions
Summary
Terminal Questions
1.1 Introduction
This unit has the following objectives
To understand the importance of object oriented programming approach
over procedural languages
To learn the basic features supported by OOP languages
To learn the basic construct of a C++ program and learn to compile and
execute it
1.2 Evolution of Programming methodologies
The programming languages have evolved from machine languages,assembly languages to high level languages to the current age of
programming tools. While machine level language and assembly language
was difficult to learn for a layman, high level languages like C, Basic, Fortran
-
7/31/2019 SMU C++ SLM UNIT 1
2/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 2
and the like was easy to learn with more English like keywords. These
languages were also known as procedural languages as each and everystatement in the program had to be specified to instruct the computer to do
a specific job. The procedural languages focused on organizing program
statements into procedures or functions. Larger programs were either
broken into functions or modules which had defined purpose and interface
to other functions.
Procedural approach for programming had several problems as the size of
the softwares grew larger and larger. One of the main problems was data
being completely forgotten. The emphasis was on the action and the data
was only used in the entire process. Data in the program was created by
variables and if more than one functions had to access data, global
variables were used. The concept of global variables itself is a problem as it
may be accidentally modified by an undesired function. This also leads to
difficulty in debugging and modifying the program when several functions
access a particular data.
The object oriented approach overcomes this problem by modeling data and
functions together there by allowing only certain functions to access the
required data.
The procedural languages had limitations of extensibility as there was
limited support for creating user defined datatypes and defining how these
datatypes will be handled. For example if the programmer had to define his
own version of string and define how this new datatype will be manipulated,
it would be difficult. The object oriented programming provides this flexibility
through the concept of class.
Another limitation of the procedural languages is that the program model is
not closer to real world objects . For example, if you want to develop a
gaming application of car race, what data would you use and what functions
-
7/31/2019 SMU C++ SLM UNIT 1
3/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 3
you would require is difficult questions to answer in a procedural approach.
The object oriented approach solves this further by conceptualizing theproblem as group of objects which have their own specific data and
functionality. In the car game example, we would create several objects
such as player, car, traffic signal and so on.
Some of the languages that use object oriented programming approach are
C++, Java, Csharp, Smalltalk etc. We will be learning C++ in this text to
understand object oriented programming. C++ is a superset of C. Several
features are similar in C and C++.
Self Assessment Questions
1. List the limitations of procedural languages
2. _______ is an OOP Language
3. In OOP approach programmers can create their own data types.
True/False
4. In procedural languages, the programs are written by dividing the
programs into smaller units known as __________
1.3 Introduction to OOP and its basic features
As discussed earlier, one of the basic concept in Object Oriented
Programming approach is bundling both data and functions into one unit
known as object. The functions of a particular object can only access the
data in the object providing high level of security for the data. The functions
in the object are known as member functions or sometimes as methods.
The key features of OOP programming languages are:
Objects and Classes
An Object is a program representation of some real-world thing (i.e
person, place or an event). Objects can have both attributes(data) and
behaviours (functions or methods). Attributes describe the object with
-
7/31/2019 SMU C++ SLM UNIT 1
4/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 4
respect to certain parameters and Behaviour or functions describe the
functionality of the object.
Table 1.1 Example of Objects
Polygon Object Bank Account
Attributes
Position
Fill Color
Border color
Behaviour
Move
Erase
Changecolor
Attributes
Accountnumber
Balance
Behaviour
Deduct Funds
Transferfunds
DepositFunds
Showbalance
According to Pressman, Objects can be any one of the following:
a) External entities
b) Things
c) Occurrences or events
d) Roles
e) Organisational units
f) Places
g) Data Structures
For example, objects can be an menu or button in an graphic user interface
program or it may be an employee in an payroll application. Objects can
also represent a data structure such as a stack or a linked list. It may be a
server or a client in an networking environment.
Objects with the same data structure and behavior are grouped together as
class. In other words, Objects are instances of a class. Classes are
templates that provide definition to the objects of similar type. Objects are
like variables created whenever necessary in the program. For example,
Employee may be a class and Pawan, Sujay and Ganesh are objects of the
class employees. Just as you can create as many variables of a default
datatype such as integer, you can create as many objects of a class.
-
7/31/2019 SMU C++ SLM UNIT 1
5/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 5
Classes and Objects support data encapsulation and data hidingwhich are
key terms describing object oriented programming languages. Data andfunctions are said to be encapsulated in an single entity as object. The data
is said to be hidden thus not allowing accidental modification.
Inheritance
Inheritance is one of the most powerful feature of Object Oriented
Programming Languages that allows you to derive a class from an
existing class and inherit all the characteristics and behaviour of the
parent class. This feature allows easy modification of existing code and
also reuse code. The ability to reuse components of a program is an
important feature for any programming language
Polymorphism and Overloading
Operator overloading feature allows users to define how basic operators
work with objects. The operator + will be adding two numbers when
used with integer variables. However when used with user defined string
class, + operator may concatenate two strings. Similarly same functions
with same function name can perform different actions depending upon
which object calls the function. This feature of C++ where same
operators or functions behave differently depending upon what they are
operating on is called as polymorphism (Same thing with different forms).
Operator overloading is a kind of polymorphism.
OOP approach offers several advantages to the programmers such as
Code can be reused in situations requiring customization
Program modeling and development closer to real world situations and
objects
Easy to modify code
Only required data binded to operations thus hiding data from unrelated
functions
-
7/31/2019 SMU C++ SLM UNIT 1
6/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 6
Self Assessment Questions
1. _____________ feature in OOP allows to reuse code.2. The concept of bundling data and functions into single unit is termed as
___________
3. Object is an __________ of a class
4. Give an example of a class and an object
5. ______________ is an advantage of OOP approach
1.4 Basic components of a C++ Program and program structure The C++ is a superset of C. At the basic level, the programs look similar in
both C and C++. Every statement in C++ ends with a semicolon (). All the
reserved words have to be written in small case and the c++ compiler is
case sensitive. Data in programming languages are stored in variables. To
create a variable, the variable should support an inbuilt datatype. The
variable is a name given to a particular location in the memory and the value
stored in a variable can be altered during program execution. The datatypes
supported in C++ are listed below
Table 1.2 Basic Datatypes in c++
Data Type Size (in bytes) Values that can be taken
Int 2 -32768 to 32767
Bool 1 False and true / 0 and 1
Char 1 -128 to 127
Long 4 -2,147,483,648 to 2,147,483,647
Float 4 3.4 X 10-38
to 3.4 X 1038
(Precision 7)
Double 8 1.7 X 10-308 to 1.7 X 10308 (Precision 15)
Long double 10 3.4 X 10-4932 to 1.1 X 104932 (Precision 19)
Unsigned int 2 0 to 65,535
-
7/31/2019 SMU C++ SLM UNIT 1
7/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 7
Variables can be named according to following rules
Can comprise of 1 to 8 alphabets, digits or underscore
First character should be an alphabet
Names are case sensitive
Reserve words of c++ cannot be used
Variables have to be declared before using them in the program. The
declaration is done in the following way:
datatype variablename
Eg: int data
The above declaration declares a integer variable named data. The value
stored in int data by default is a junk value. Values can also be assigned to
the variable during declarations or initialized separately using the
assignment operator =.
Eg: int data=0
Or
int data
data=0
Constants are those which do not change during execution of a program.
The constants in C++ can be numeric, character or string constants.
Examples of each are shown in table 1.3
Table 1.3 Example of Constants
Constant Example Constraints
NumericConstant
23000
450.6 (Floating point)
Can be negative or positive, cannotcontain blanks or commas, or $
Character
Constant
A Any character enclosed within single
quotes, represented by unique ASCIInumber in the memory
String Constant Hello Set of characters enclosed in doublequotes, last character in the string isnull character \0
-
7/31/2019 SMU C++ SLM UNIT 1
8/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 8
Operators supported in C++ are listed below. Unary operators are used with
one operand and binary operator is used with two operands.
Table 1.4 Operators in C++
Arithmetic Operators Type Action
- Unary aswell asbinary
Subtraction for binary and minus forunary
+ Binary Addition
* Binary Multiplication
/ Binary Division
% Binary Modulus (remainder after dividing)-- Unary Decrement value by one
++ Unary Increment value by one
Relational Operators Type Action
> Binary Greater than
>= Binary Greater than or equal
< Binary Less than
-
7/31/2019 SMU C++ SLM UNIT 1
9/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 9
sum=a+b
cout
-
7/31/2019 SMU C++ SLM UNIT 1
10/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 10
two integers. The values entered by the user is then stored in the variables
a and b. Each variable in cin statement should separated by >> operator.
Comment statements can be included in the program by prefixing the
statement with // for single line comments. Comments add clarity to the
program. Multiple line comments can be added by enclosing the statements
between /* and */.
Self Assessment Questions
1. ______________ is a header file used in c++ that handles input and
output functions.
2. ____________ statement is used to input data from the user in c++.
3. ______________ statement is used to display data on the display
screen in c++.
4. ______________ is a master function required in all C++ program and
program execution begins from the first statement of this function.
1.5 Compiling and Executing C++ Program
1. There are three steps in executing a c++ program: Compiling, Linkingand Running the program. The c++ programs have to be typed in a
compiler. All the programs discussed in the book will be compiled on
turbo c++ compiler. The turbo c++ compiler comes with an editor to type
and edit c++ program. After typing the program the file is saved with an
extension .cpp. This is known as source code. The source code has to
be converted to an object code which is understandable by the machine.
This process is known as compiling the program. You can compile your
program by selecting compile from compile menu or press Alt+f9. Aftercompiling a file with the same name as source code file but with
extension .obj. is created.
-
7/31/2019 SMU C++ SLM UNIT 1
11/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 11
Second step is linking the program which creates an executable file .exe
(filename same as source code) after linking the object code and thelibrary files (cs.lib) required for the program. In a simple program, linking
process may involve one object file and one library file. However in a
project, there may be several smaller programs. The object codes of
these programs and the library files are linked to create a single
executable file. Third and the last step is running the executable file
where the statements in the program will be executed one by one.
Fig 1.1 shows the entire process. When you execute the program, the
compiler displays the output of the program and comes back to theprogram editor. To view the output and wait for user to press any key to
return to the editor, type getch() as the last statement in the program.
Getch() is an inbuilt predefined library function which inputs a character
from the user through standard input. However you should include
another header file named conio.h to use this function. Conio.h contains
the necessary declarations for using this function. The include statement
will be similar to iostream.h.
Fig. 1.1: Compiling and Linking
-
7/31/2019 SMU C++ SLM UNIT 1
12/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 12
During compilation, if there are any errors that will be listing by the compiler.
The errors may be any one of the following1. Syntax error
This error occurs due to mistake in writing the syntax of a c++ statement
or wrong use of reserved words, improper variable names, using
variables without declaration etc. Examples are : missing semi colon or
paranthesis, type integer for int datatype etc. Appropriate error message
and the statement number will be displayed. You can see the statement
and make correction to the program file, save and recompile it.
2. Logical errorThis error occurs due to the flaw in the logic. This will not be identified by
the compiler. However it can be traced using the debug tool in the editor.
First identify the variable which you suspect creating the error and add
them to watch list by selecting Debug ->Watches->Add watch. Write the
variable name in the watch expression. After adding all the variables
required to the watch list, go to the statement from where you want to
observe. If you are not sure, you can go to the first statement of the
program. Then select Debug ->Toggle Breakpoint (or press ctrl + f8). Ared line will appear on the statement. Then Run the program by
selecting Ctrl + f9 or Run option from run menu. The execution will halt
at the statement where you had added the breakpoint. The watch
variables and their values at that point of time will be displayed in the
bottom in the watch window. Press F8 to execute the next statement till
you reach the end of the program. In this way you can watch closely the
values in the watch variables after execution of each and every
statement in the program. If you want to exit before execution of the laststatement press Ctrl + Break. To remove the breakpoint in the program
go to the statement where you have added breakpoint select Debug -
>Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch ->remove
-
7/31/2019 SMU C++ SLM UNIT 1
13/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 13
watches to remove the variables in the watch list. This tool helps in
knowing the values taken by the variable at each and every step. Youcan compare the expected value with the actual value to identify the
error.
3. Linker error
This error occur when the files during linking are missing or mispelt
4. Runtime error
This error occurs if the programs encounters division by zero, accessing
a null pointer etc during execution of the program
Self Assessment Questions
1. ___________, ______________ and _____________ are phases in
execution of a C++ program
2. The logical error is identified by the compiler. True/False
3. ________________ is the extension of C++ program source files
4. ________________ is the extension of C++ object code
Summary
Object oriented Programming enables storing data and functions togetherwhich enables hiding data from unnecessary exposure. Procedural
languages differs from the Object oriented programming in the approach
used in solving the problem. While the former focuses on organizing
programs around functions, the later focuses organizing programs around
classes. Classes allow users to define their own datatypes and functionality.
This allows extension of the basic datatypes supported by the language.
Reusability of code through inheritance allows users to use the existing
code without modifying it but also extend the functionality of the existing
code. The C++ programs are similar to C except for the object orientedprogramming features. Every C++ program has a main function from where
the execution starts. C++ programs goes through two phases ie compiling
and linking before execution.
-
7/31/2019 SMU C++ SLM UNIT 1
14/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 14
Terminal Questions
1. Which of the following is not a feature of Object Oriented Programminga. Data encapsulation b. Inheritance c. Operator Overloading
d. Data Structure
2. Which one of the following is not an inbuilt basic datatype in c++
a. Int b. Bool c. String d.Float
3. Write a program that accepts two numbers from the user and swaps the
two numbers without using a temporary variable.
4. Write a program that accepts two numbers a and b and divides a by b
and displays the quotient and the remainder.
5. Object constitutes of ____________ and _____________
Answers to SAQs and TQs
Answers to SAQs in 1.2
1. Limitations of procedural languages are no importance to data and
inability to define user defined datatypes and define functionality for the
same
2. C++, smalltalk, Java are all OOP Languages
3. True
4. Functions or procedures
Answers to SAQs in 1.3
1. Inheritance
3. Data Abstraction
4. Object is an instance of a class
5. Class - car and object Maruti 800
6. Reusability of code
Answers to SAQs in 1.4
1. iostream.h2. cin
3. cout
4. main() function
-
7/31/2019 SMU C++ SLM UNIT 1
15/15
OOPS Using C++ Unit 1
Sikkim Manipal University Page No. 15
Answers to SAQs in 1.5
1. Compiling, Linking and Running2. False, it can assist in identifying using debug tool
3. .cpp
4. .obj
Answers TQs
1. d
2. c
3. Program to swap two numbers without using a temporary variable
# include
void main()
{ int num1,num2
cout num1>>num2
Num1=num1+num2
Num2=num1-num2
Num1=num1-num2
cout