[go: up one dir, main page]

0% found this document useful (0 votes)
14 views14 pages

1 Basics of OOP

C++ normal basic

Uploaded by

kishanshiyal9988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

1 Basics of OOP

C++ normal basic

Uploaded by

kishanshiyal9988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Dr.

Piyush Arora Object Oriented Programming using C++


Who is the inventor of Smalltalk? – “Alan Kay”
Who is the inventor of C++? – Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill,
New Jersey, USA in 1980’s

Difference between (POP) & (OOP)


No Procedure Oriented Programming Object Oriented programming
1 Emphasis is on action rather than data. Emphasis is on data rather than procedures.
2 Programs are divided into subprograms Programs are divided into objects.
or sub procedures or functions (e.g.: use
of flowchart to show flow of control
from one function to another).
3 Data structures are designed for simple Data structures are designed, such that they
data for simple data types. characterize the objects.
4 Functions & data are separate. Functions that operate on the data of an
object are typed together in the data
structure, in the class.
5 Data can be accessed by external Data is hidden and can’t be accessed by
function. external functions. Objects may
So, most of the functions share global communicate with each other through
data. functions by message passing.
6 New data & functions for the whole New data & functions can be easily added
application can’t be easily added whenever necessary
whenever necessary.
7 Follows top-down approach in program Follows bottom-up approach in program
8 design. design.
e.g.: C, FORTRAN, COBOL e.g.: C++, Smalltalk, java, Eiffel
Global Data Global Data Object A Object B
Data Data

Functions Functions

Function-1 Function-2 Function-1 Object C


Data
Local Data Local Data Local Data
Functions

Basic Concepts of Object Oriented Programming Object: STUDENT


DATA MEMBER
1. Objects Name
Date-of-Birth
• Objects are basic run time entities in an object-oriented system. Marks
MEMBER FUNCTIONS
• An object is also called as instance variable. Total

• They may also represent user-defined data such as vectors, time and lists. Average
Display
The Key to Success = Mind + Intellect + Soul Page | 1
Dr. Piyush Arora Object Oriented Programming using C++
• Programs objects name should match closely with the real-world objects.
• Objects represent a person, a place, a bank account, a table of data or any item that the
program handles.
• Objects take up space in the memory and have an associated address like a variable or
a structure in c.
• Objects can communicate with each other using message passing. Objects can interact
without knowing the details of each other’s data or code.
e.g.: if “customer” and “account” are two objects in a program, then the customer
object may send a message to the account object requesting for the bank balance.

2. Classes
• Classes are user-defined data types and behave like built-in data types of a
programming language.
• The entire set of data and code of an object can be made a user-defined data type with
the help of class.
• Objects are variables of the type class.
• We can create any number of objects belonging to a single class.
• Each object is associated with the data of type class with which they are created.
• A class is a collection of objects of similar types.
e.g.: Mango, Apple and orange are members of class “fruit”.
• Syntax to create an object of a class: Similar to syntax to declare a variable
➔ Class_name object_name It is same as “data_type variable_name”
e.g.: Fruit Mango It is same as “int a”

3. Encapsulation OR Data Hiding OR Information Hiding


• The wrapping up of data and function into a single unit (called class) is known as
encapsulation.
• Data encapsulation is the most important and useful feature of a class.
• This data is not accessible to the outside world.
• Only those functions which are wrapped in the class, can access it.
• Functions provide the interface (communication medium) between the object’s data
and program.
• This insulation of the data from direct access by the program is called data hiding or
information hiding.

4. Abstraction
• Abstraction refers to the act of representing essential features without including the
background details or explanation.
• Classes use the concept of abstraction.
• We define the list of attributes of a class such as size, weight, and cost. Attributes are
also called as data members.
• We define the functions that operate on these attributes. Functions are also called as
methods or member functions.
e.g.: When we define an object “duster”, we simply use that object, without even
thinking that how the duster is made, what is the size (dimension) or weight of the
duster, etc.

The Key to Success = Mind + Intellect + Soul Page | 2


Dr. Piyush Arora Object Oriented Programming using C++
• Since classes use the concept of data abstraction, they are also called as Abstract Data
Types (ADT).

5. Inheritance
• Through inheritance, objects of one class acquire the properties of objects of another
class.
• It supports the concept of hierarchical classification.
• e.g.: The bird, ‘Sparrow’ is a part of class ‘flying bird’ which is again a part of the
class ‘bird’.
• Each derived class shares common characteristics with the class from which it is
derived (Figure below).
• In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it.
• We can derive a new class from the existing class. The new class will have the
combined features of both the classes.
• So, we can reuse the class.
• Without inheritance, each class would be required to include all the features in it.
Bird Shape
Attributes
Feathers Draw( )
Lay Eggs

Flying Bird Non-Flying Bird


Attributes Attributes
Light Weight Heavy Weight

Sparrow Swallow Penguin Peacock


Attributes Attributes Attributes Attributes Circle Object Box Object Triangle Obj
Wood nest Stone nest Swim Colourfull
Draw(circle) Draw(box) Draw (triang)

Figure of Inheritance Figure of Polymorphism


6. Polymorphism
• It means the ability to take more than one form.
• An operation may have different behaviors in different instances.
• The behavior depends upon the types of data used in the operation.
e.g.: consider the operation of addition. For two numbers, the operation will generate a
sum. But, if the operands are strings, then the operation would produce a third string by
concatenation.
• The process of making an operator to have different behaviors in different situations is
known as operator overloading.
• A single function name can be used to handle different number and different types of
arguments.
• Using a single function name to perform different types of task is known as function
overloading.
• Polymorphism is extensively used in implementing inheritance.

The Key to Success = Mind + Intellect + Soul Page | 3


Dr. Piyush Arora Object Oriented Programming using C++
7. Dynamic Binding
• Binding means linking the procedure call to the code to be executed in response to the
call.
• Dynamic binding means that, the code for the given procedure call is not known until
the time of the call at run time.
• It is associated with polymorphism and inheritance.
e.g.: Consider the procedure “draw ( )” above. By inheritance, every object will have
this procedure.
But, its algorithm is unique to each object.
So, the draw procedure will be redefined in each class that defines the object.
At run-time, the code matching the object under current reference will be called.

8. Message Passing
• Objects communicate with each other by sending and receiving information.
• The concept of message passing makes it easier to build systems that describe the real-
world situations.
• A Message for an object is a “Request for execution of a procedure”. So, a message
will call a function (procedure) in the receiving object that generates the desired
results.
• Object has a life cycle. They can be created and destroyed. Objects can communicate
as long as they are alive.
• Message passing involves specifying:
a. The name of object
b. The name of the function (message)
c. The information to be sent

Benefits of OOP
• Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
• We can build programs from the standard working modules that communicate with one
another.
• We don’t require to write the code from the scratch (starting). So, we can save
development time and we can have higher productivity.
• The principle of data hiding helps the programmer to build secure programs that cannot
be accessed by the code in other parts of the programs.
• It is possible to have multiple instances of an object to co-exist without any
interference.
• It is possible to create objects in the program that define real world problems.
• It is easy to partition the work in a project based on objects. So, work load can be
distributed.
• By using data-centered design approach, we can design the model of a system easily
and its implementation is easy.
• Object-oriented systems can be easily upgraded from small systems to large systems.
• Message passing techniques for communication allow the objects to have easy
communication that makes the interface easy.
• Software complexity can be easily managed.
Types of Languages based on Object Oriented Features
The Key to Success = Mind + Intellect + Soul Page | 4
Dr. Piyush Arora Object Oriented Programming using C++
a. Object – Based Programming Languages
• These languages support:
o Data encapsulation and object identity
o Data hiding (Encapsulation) and access mechanisms
o Automatic initialization and clear-up of objects (e.g.: Constructor and destructor)
o Operator overloading
• These languages do not support:
o Inheritance
o Dynamic Binding
e.g.: Ada language
b. Object – Oriented Programming Languages
• These languages support all object-oriented features.
• So, we can say that: OOP = Object-Based features + Inheritance + Dynamic Binding
e.g.: C++, java, Smalltalk, Pascal language
Applications of OOP
Object oriented languages can be used in the Design of:
• user interface, such as windows
• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, Hypermedia
• AI (Artificial Intelligence) and expert systems
• Neural networks and parallel programming
• Decision support and Office Automation Systems (OAS)
• Computer Integrated Manufacturing (CIM), Computer Aided (Assisted) Manufacturing
(CAM), Computer Aided (Assisted) Design (CAD) systems

Introduction to C++ and Applications of C++


C++ was initially called “C with classes”.
C++ is named from the C increment operator ++, suggesting that C++ is augmented
(increment) version of C.
C++ is the superset of C.
Almost all C programs are also C++ programs.
C++ is a versatile language for handling very large programs.
It is suitable for any programming task such as development of editors, compilers, databases,
communication systems and any complex real life applications systems.
• Since C++ allow us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
• As C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get close to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to
be implemented, it is very easy to add to the existing structure of an object.
• In the near future C++ will replace C as a general purpose language.

A simple C++ program


#include<iostream.h>
#include<conio.h>
The Key to Success = Mind + Intellect + Soul Page | 5
Dr. Piyush Arora Object Oriented Programming using C++
void main()
{
int a, b, c;
clrscr();
cout<<"\n Enter value of a : ";
cin>>a;
cout<<"\n Enter value of b : ";
cin>>b;
c = a+b;
cout<<"Value of c = "<<c;
getch();
}
• The above example contains only one function main().
• The execution always begins at main ( ). Every C++ program must have a main ( ).
• Like C, the C++ statements terminate with semicolons.

Comments in C++
We can specify comments in two ways:
1. Single line comments:
By using symbol // (double slash).
A comment may start anywhere in the line, and whatever follows till the end of the line
is ignored.
Note that there is no closing symbol.
e.g.: // This is an example of …….
// C++ program to illustrate …….

2. Multiline comments:
By using the symbols /*…….*/
e.g.: /* This is an example of
C++ program to illustrate
some of its features */

Note: Double slash comment cannot be used in the following manner:


for (j = 0 ; j < n ; /* loops n times */ j++)
This for loop is wrong.

The iostream File


• The statement:
o #include <iostream.h>
• The #include directive instructs the compiler to include the contents of the file
“iostream”, enclosed within angular brackets into the source file. The header file
iostream.h should be included at the beginning of all programs that use input/output
statements.

Output Operator
• The statement is:
cout << “C++ is better than C.”;

The Key to Success = Mind + Intellect + Soul Page | 6


Dr. Piyush Arora Object Oriented Programming using C++
• It causes the string in quotation marks to be displayed on the screen.
• The identifier cout is a predefined object that represents the standard output stream in
C++. Here, the standard output stream is the screen.
• It is also possible to redirect the output to other output devices.

• The operator << is called the insertion or put to operator. It inserts (or sends) the
contents of the variable on its right to the object on its left.
• We can also write:
o cout << string;
Here, string is the variable name. It will display the contents of the variable.

Input Operator
• Suppose we have a statement:
o cin >> a;
• It is an input statement and causes the program to wait for the user to type in a number
• The number keyed in, is placed in the variable a.

• The identifier cin is a predefined object in C++ that corresponds to the standard input
stream. Here, this stream represents the keyboard.
• The operator >> is known as extraction or get from operator. It extracts (or takes) the
value from the keyboard and assigns it to the variable on its right.

Cascading of I/O Operators


• The statement
o cout << “Sum =” << sum << “\n”;
• First sends the string “Sum = ” to cout and then it sends the value of sum. Finally, it
sends the newline character so that the next output will be in the new line.
• The multiple use of << in one statement is called cascading.
• We can combine the below two statements, using the cascading technique as follows:
The Key to Success = Mind + Intellect + Soul Page | 7
Dr. Piyush Arora Object Oriented Programming using C++
o cout << “Sum =” << sum << “\n”;
o cout << “Average =” << average << “\n”;

o cout << “Sum = ” << sum << “\n” << “Average = ” << average << “\n”;
• This is one statement, but provides two lines of output, because of “\n”
• If you want only one line of output, the statement will be:
o cout << “Sum =” << sum << “,” << “Average =” << average << “\n”;
• The output will be:
o Sum = 14, average = 7

• We can also cascade input operator >> as shown below:


o cin >> number1 >> number2;
The values are assigned from left to right.
If we key in two values, say, 10 and 20, then 10 will be assigned to number1 and 20
to number2.

Structure of C++ Program


• A typical C++ program would contain four sections.
• Each section may be placed in separate code files and then compiled independently or
jointly.
• We organize a program into three separate files.
• The class declarations are placed in the header file and the definitions of member
functions go into another file.
• Finally, the main program that uses the class is placed in a third file which “includes”
the previous two files as well as any other file required.
• This approach is based on the concept of client-server model.
• The class definition including the member functions forms the server.
• The server provides services to the main program known as client.
• The client uses the server through the public interface of the class.

Include Files Member


Functions
Class Declaration Server
Class Definitions
Member Functions
Definitions
Main Function Main Function
Client
Program Program

List of some commonly used header files


• <assert.h> - Contains macros and information for adding diagnostics that help in
program debugging.
• <ctype.h> - Contains function prototypes for functions that test characters for certain
properties. Also, used to convert lowercase letters to uppercase letters and vice versa.
• <float.h> - Contains floating point size limits of the system.
• <limits.h> - Contains the integral size limits of the system.
• <math.h> - Contains function prototypes for math library functions.

The Key to Success = Mind + Intellect + Soul Page | 8


Dr. Piyush Arora Object Oriented Programming using C++
• <stdio.h> - Contains function prototypes for the standard input/output library functions
and information used by them.
• <stdlib.h> - Contains function prototypes for conversion of numbers to text, text to
numbers, memory allocation, random numbers.
• <string.h> - Contains function prototypes for C-style string processing functions.
• <time.h> - Contains function prototypes and types for manipulating the time and data.
• <iostream.h> - Contains function prototypes for the standard input and standard output
functions.
• <iomanip.h> - Contains function prototypes for the stream manipulators that enable
formatting of streams of data.
• <fstream.h> - Contains function prototypes for the functions that perform input from
files on disk and output to files on the disk.
• <exception.h> , <stdexcept.h> - These header files contain classes that are used for
exception handling.
• <memory> - Contains classes and functions used by the standard library to allocate
memory to the standard library containers.
• <limits.h> - Contains a class for defining the numerical data type limits on each
computer.

Tokens in C++
It consists of:
1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Operators

• The keywords are explicitly reserved identifiers or words.


• They cannot be used as the names for the program variables or other user-defined
program elements.
Auto break catch char class const continue delete do
double else extern float for friend goto if inline
Int long new operator private protected public register return
Short signed sizeof static struct switch this throw try
typedef union unsigned virtual void volatile while
• Identifiers refer to the names of the variables that are used in the program.
• It should be properly named.
• Constants refer to fixed values that do not change during the execution of the program.

Basic Data Types in C++

• Built-in data types are also called as basic or fundamental data types.
• We can specify the modifiers before the built in data types. This is useful in several
situations.
e.g.: signed, unsigned, short, long – these are generally applied to character and integer
basic data types.
e.g.: long – is applied to double.

Size and Range of data types with modifiers for 16-bit word machine
The Key to Success = Mind + Intellect + Soul Page | 9
Dr. Piyush Arora Object Oriented Programming using C++
Type Size (in Bytes) Range
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned char 2 0 to 65535
signed char 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4E -38 to 3.4E +38
double 8 1.7E -308 to 1.7E +38
long double 10 3.4E -4932 to 1.1E +4932

Uses of void
Void data type is used for following purposes:
a. To specify the return type of a function, when it is not returning any value
void addition ( );

b. To specify an empty argument list to a function.


void addition (void);
c. For the declaration of generic pointers. It is also called as void pointer.
void *gp;
A generic pointer can be assigned a pointer value of any basic data type.
int *ip;
gp = ip;
The above statement is valid, as the data type of gp is initially “void”, and the data type
of ip is “int”, we can assign ip to gp.

• The void pointer cannot be dereferenced.


Dereferencing means, assigning the value of the pointer variable to which it points, to
another pointer variable of the same type.
So, following is invalid:
void *gp;
int *ip;
*gp = *ip; // This is not valid because data type of ip is int and type of gp is
void.

• We cannot assign a void pointer directly to other type pointers in C++.


void *ptr1;
char *ptr2;
ptr2 = ptr1;
So, we need to use cast operator as shown below:
Ptr2 = (char *) ptr1;
The Key to Success = Mind + Intellect + Soul Page | 10
Dr. Piyush Arora Object Oriented Programming using C++

User-Defined Data Types


a. Structures (refer later)
b. Unions (refer later)
c. Classes (refer later)
d. Enumerated Data Types
• It provides a way for attaching names to numbers.
• enum keyword enumerates a list of words by assigning them values 0, 1, 2 and so on.
• So, we can create symbolic constants using enum.
• Its syntax is similar to “struct”.
enum shape {circle, square, triangle}; // implicitly
enum position {off, on};
enum colour {red, green, blue};
• The tag names shape, colour and position become new type names. By using these tag
names, we can declare new variables:
shape circle; // circle is of type shape
colour background // background is of type colour
• Note: In C, the data types of enum is integer. But, in C++, each enumerated data type
has a separate data type. So, we cannot convert int value to enum value automatically.
colour background = blue; // Correct and allowed
colour background = 7; // Error in C++
colour background = (colour) 7; // Ok, correct and allowed
• By default, the enumerators are assigned integer values starting with 0 for the first
enumerator, 1 for the second and so on. But, we can change this value.
enum colour { red, blue=4, green=8 }; // red is 0 by default
enum colour { red=5, blue, green }; // blue is 6 and green is 7
• We can also create anonymous enums in C++, i.e. enums without tag names.
enum {off, on}; // off is 0 and on is 1
We can refer these constants in the same manner as regular constants. That is, we can
write:
int switch_1 = off;
int switch_2 = on;

Derived Data Types


a. Arrays
• It is similar to C and is declared and used in the same way in C++
int arr[5] = {1, 2, 3, 4, 5};
• Character array is also declared and initialized in the similar manner with NULL ‘\0’
character at the end.
char string1[6] = {hello};

b. Functions (refer later)

c. Pointers
• Pointers are declared and used in the same way as in C.
int *p, x;
x = 10;
The Key to Success = Mind + Intellect + Soul Page | 11
Dr. Piyush Arora Object Oriented Programming using C++
p = &x;
*p = 25;
• C++ also uses the concept of constant pointer and pointer to constant.
o Constant Pointer
char * const ptr1 = “Good”; // Constant Pointer
We cannot modify the address that ptr1 is initialized to.
o Pointer to a constant
int const * ptr2 = &m;
ptr2 is declared as pointer to a constant. It can point to any variable of correct
type, but wherever it points, its contents cannot be changed.
• We can declare both the pointer and the variable as constants in the following way:
const char * const cp = “Good”;
This statement declares cp as a constant pointer to the string which has been declared
as a constant.
So, neither we can change the address assigned to the pointer cp nor the contents it
points to.

Symbolic Constants
We can create symbolic constants in C++ in two ways:
1. By using the qualifier const.
• Any value declared as const, cannot be modified by the program in any way. So, we
cannot change its value.
• We can use const in a constant expression, such as:
const int size = 10;
char name[size];
Note: This was illegal in C;
• So, we don’t need to create constants using #define.
• If we use long and short keywords with const modifier it defaults to int.
const size = 10;
Means
const int size = 10;
• In C++, variable declared as const have local scope. It is local to the file where it is
declared.
• In C, variables declared as const have global scope. They are visible outside the file,
where they are declared. We can make them local by declaring them as static.
• If we want that the const value should be allowed to be referenced by another file (used
outside the file), we must define it as extern.
extern const total = 100;

2. By defining a set of integer constants using enum keyword. (Also refer enum in user
defined data types)
• We can create integer constants by enumeration.
enum { x, y, z };
This define x, y, z as integer constants with value 0, 1, 2 respectively. This is similar
to:
const x = 0;
const y = 1;
The Key to Success = Mind + Intellect + Soul Page | 12
Dr. Piyush Arora Object Oriented Programming using C++
const z = 2;
• We can also assign value to x, y and z explicitly.
enum { x = 100, y = 50, z = 200 };

Type Compatibility
• If we define variables of one data types, compiler will not automatically convert them
to different types.
• The int, short int and long int data types are different in C++. They must be cast (data
type must be changed), when their values are assigned to one another.
• Even if the size of unsigned char, char and signed char is same, that is 1 byte, they are
considered as different data types.
• We need to do casting of data types that is conversion to correct types, to support
function overloading.
• In function overloading, we have two functions with the same name, but different
number or different types of arguments.
• There is one major difference in the way, how char constants are stored in C and C++.
o In C,
sizeof (‘x’)
is equivalent to:
sizeof (int)
o In C++,
sizeof (‘x’)
Is equivalent to:
sizeof (char)

Declaration of variables
• In C, we have to declare and define all the variables at the beginning of the scope.
• So, we declare them at the top in the beginning of the program, where the main
function starts, or some other function starts.
• We cannot declare them in the middle of the program or function.
• We actually use them elsewhere in the program, which may be too far from the
declaration location.
• So, if we need a new variable, we again need to go back to the beginning of the
program and declare it.
• In C++, we can declare the variables, anywhere in the scope of the program.
• So, we can declare the variable at the place of its first use.
• So, this makes the program much easier to write and reduces the errors that may be
caused by scanning back and forth (up and down) in the program.
• Also, understanding the program becomes easy.

Dynamic initialization of variables


• In C, a variable must be initialized using a constant expression
e.g.: int a = 10; // Constant value initialized to x
So, variable is initialized at compile time.
• In C++, we can initialize the variables at run time. This is called as dynamic
initialization.
This is done by using expressions at run time at the place of declaration.
The Key to Success = Mind + Intellect + Soul Page | 13
Dr. Piyush Arora Object Oriented Programming using C++
e.g.: int n = strlen(string1);
This is allowed, where we are calculating the length of the string and
assigning its length to the variable n. But, n is declared before it is
assigned the value.
float area = 3.14159 * radius * radius;
Here we calculate the radius, assign it to area, but area is declared before
it is assigned the value.
So, declaration and initialization are done simultaneously at the place where variable is
used for the first time.
• So, we can combine the two below statements:
float average;
average = sum/i;
can be written as:
float average = sum/i;
• Dynamic initialization is extensively used in object oriented programming.

Reference Variables

200 202 204 206 208


d2[0] d2[1] d2[2] d2[3] d2[4]
**p *d1[0] 5 10 15 20 25
200 200 300 302 304 306 308
850 d2[0] d2[1] d2[2] d2[3] d2[4]
100 *d1[1] 30 35 70 40 85
300 400 402 404 406 408
950 d2[0] d2[1] d2[2] d2[3] d2[4]
*d1[2] 98 96 54 63 41
400
1040

The Key to Success = Mind + Intellect + Soul Page | 14

You might also like