Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

C++ Programming Language-: Unit-1

1. Introduction to OOPs and Basics of C++


1.1 Object Oriented Programming

➢ Object Oriented Programming is an approach that


provides a way of modularizing programs by creating
partitioned memory area for both data and functions
that can be used as templates for creating copies of such
modules on demand.
1.2 Basic Concepts of OOPs
1. Objects:
Objects are the basic run time entities in an object-oriented
system. They may represent a person , a place, a bank account, a
table of data or any item that the program has to handle, they
may also represent user-defined data such as vectors, time and
lists. Programming problem is analyzed in term of object and the
nature of communication between them. Program objects should
be chosen such that they match closely with the real-world
objects.
Object: STUDENTS STUDENTS
DATA: name,
Date of birth ,marks Total Average Display
Functions: Total,
Average, Display
2. Classes:
We just mentioned that objects contain data, and code to
manipulate that data. The entire set of data and code of an
object can be made a user-defined data type with the help of a
class. In fact, objects are variables of the type class. Once a
class has been defined , we can create any number of objects
belonging to that class. Each object is associated with the data
of type class with which they are created.
A class is thus a collection of objects of similar type. For
example, mango, apple and orange are member of the class
fruit. Classes are user-defined data types and behave like the
built-in types of a programming language. The syntax used to
create an object is no different than the syntax used to create an
integer object in C. If fruits has been defined as a class, then the
statement
Fruit mango;
Will create an object mango belonging to the class fruit.

3. Data Abstraction and Encapsulation:


The wrapping up of data and function into a single unit called
class is known as encapsulation.
Data encapsulation is the most striking feature of a class. The
data is not accessible to the outside world, and only those
function which are wrapped in the class can access it. These
functions provide the interface between the object’s data and
the program. This insulation of the data from direct access by
the program is called data hiding or information hiding.
4. Inheritance:
Inheritance is the process by which objects of one class
acquire the properties of objects of another class. It supports
the concept of hierarchical classification. For example, the
bird ‘robin’ is a part of the class ‘flying bird’ which is again a
part of the class ‘bird’. The principle behind the sort of
division is that each derived class shares common
characteristics. In OOP, the concepts of inheritance provides
the idea of reusability. This means that we can add additional
features to an existing class without modifying it. This is
possible by deriving a new class from the existing one.
OR
The idea of classes lead to idea of inheritance. In our daily
lives, we use the concept of dividing class into subclasses.
E.g. The class of Vehicle is divided into cars, buses,
motorcycles etc.
In the similar way, an OOP class can be further divided into
small classes called base classes; other classes can be defined
that share it’s characteristics, but add their own as well. These
are called as Derived classes. Derived classes inherit some
characteristics from their base class but can also have some
their own properties and methods.
5. Polymorphism:
Polymorphism is another important OOP concept.
Polymorphism, a Geek term, means the ability to take
more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends
upon the types of data used in the operation.
For example, consider the operation of addition. For
two numbers, the operation will generate a sum. If the
operands are strings, then the operation would produce a
third string by concatenation. The process of making an
operator to exhibit different behaviors in different
behaviors in different instances is known as operator
overloading

6. Dynamic Binding:
Binding refers to the linking of a procedure call to the
code to be executed In response to the call. Dynamic
binding (also known as late binding) means that the code
associated with a given procedure call is not known until
the time of the call at run time.
It is associated with polymorphism and inheritance. A
function call associated with a polymorphism reference
depends on the dynamic type of that reference.
7. Message Passing:
An object oriented program consist of a set of
objects that communicate with each other. The process
of programming in an object oriented language,
therefore, involves the following basic steps:
1. Creating classes that define objects and their
behavior.
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by
sending and receiving information much the same
way as people pass messages to one another. The
concept of message passing makes it easier to talk
about building system that directly model or
simulate their real-world counterparts.

1.3 Benefits of OOPs:

1. Through inheritance, we can eliminate redundant code


and extend the use of existing classes.
2. We can build programs from the standard working
modules that communicate with one another, rather than
having to start writing the code from scratch. Thus leads
to saving of development time and higher productivity.
3. The principle of data hiding helps the programmer to
build secure programs that cannot be changed by code in
any other parts of the programs.
4. Decision support and office automation systems.
5. Real time systems, simulation and modeling can be done.
6. Neural networks and parallel programming AI and
expert systems.
7. CIM/CAM/CAD systems.
1.4 C++ Tokens, Variables, Constants and data types:
As we known, the smallest individual units in a
program are known as tokens. C++ has the following
tokens:
• Keywords
• Identifiers and Constants
A C++ program is written using tokens, white
spaces, and the syntax of the language Most of
the C++ token are basically similar to the C
tokens with exception of some additions and
minor modifications.
• Keywords:
The Keywords implement specific C++
languages features. They are explicitly reserved
identities and cannot be used as names for the
program variables or other user-defined program
elements.
Many of them are common to both C and C++
The ANSI keywords are shown in boldface. Additional
keywords have been added to the ANSI C keywords in order
to enhance its features and make it an object oriented
language. ANSI C++ standard committee has added some
more keywords to make the language more versatile.
C++ Keywords
The wide-character type is a wide-character literal
introduced by ANSI C++ and is intended for character sets
that cannot fit a character into a single byte. Wide-character
literals begin with the letter L.
• Identifier :
The quantity or identity whose value allow to change
during the program execution is called variable. The
mathematical expression 5x+2y where x and y are the
variables the value of this variable, stored in the computer
memory which is reference by a variable. The following
rules are define variable:
• Only alphabetic characters, digits, and underscores are
permitted.
• The name start with a digit.
• Uppercase and lowercase letter and distinct.
• A declared keyword cannot be used as a variable name.
• Constants:
• The quantity or identifier whose value does not change
during the program execution is called constant. It is fixed
value which is not change in the mathematical expression
5X+6y where 5 and 7 are constants.
• A major difference between C and C++ is the limit on the
length of a name. while ANSI C recognizes only the first
32 characters in a name, ANSI C++ places no limit on its
length and, therefore, all the character in a name are
significant.
• Care should be exercised while naming a variable which is
being shared by more than one file containing C and C++
programs. Some operating system impose a restriction on
the length of such a variable name.
• Constants refer to fixed values that do not change
during the execution of a program.
• Like C, C++ supports several kinds of literal constants.
They include integers, character, floating point numbers
and strings. Literal constant do not have memory locations.
Examples:
Constant having 2 main types:
1. Numeric Constant:
2. Non numeric Constant:

1.Numeric Constant:
The numeric constant are the number which is
again classified into two parts:
• Integer constant:
• Real or float constant:
• Integer constant:
A number does not include decimal points is called
integer constant. ex. Any natural numbers is an
example of this constant.
Ex. 500, -200 etc.
The integer constant defines some rule:
1. It does not include decimal point
2. It is a single digit
3. Default sign is positive
4. The range of this constant is -32768 to 32767
• Real or float constant:
A number include a decimal point is reffered as real or
float constant.
eg. 4.5, 6.45, -19.54 etc.
it defines the rules
Rules:-
1. It must include decimal point
2. It must only one decimal point is included
3. it may be either positive or negative
4. The default sign is positive
5. It is available in single pricigion and double pricigion.
6. The number in the range of -3.4e38 to 3.4e38.
7. The number is too large and too small, these numbers
are converted into exponent which is separated by a
letter e i.e. 3.4e38 where 3.4 is mantisa and 38 is
exponent.
2.Non numeric constant:
It is a character and not a number it is classified
into two types.
a. character constant:
b. string constant:

a. character constant:
It is a single character is must be enclosed is single
correct is referred as character constant. eg. ‘a’ ‘1’
etc.
b. string constant:
The group of character is called string. The string
constant consist of group of character it must be
enclosed in double coatation mark(“”) eg.
“mumu”, “welcome” etc.
• Data types:

Both C and C++ compilers support all the built-in (also


known as basic or fundamental) data types. With the exception
of Void, the basic data types may have several modifiers
preceding them to serve the needs of various situations.
The modifiers signed, unsigned, ling, and short may be
applied to character and integer basic data types. However, the
modifier long may also be applied to double. Data types
representation in machine specific in C++. In the above figure
all combinations of the basic data types and modifiers with their
size and range for a 16-bit word machine.
OR
In C programming we can use the different data, those data
belongs to the certain types is referred as data types. In C
programming language the data types are classified into four
types.
Size and range of C++ basic data types

1.Primary or Built in data type:-


Those data types are already defined in the c compiler
such data type called as built in data type.
It consist of four data types with different storage capacity.
• char can hold 1 byte
• int can hold 2 byte
• float can hold 4 byte
• double can hold 8 byte
The storage capacity can be increased or decreased with the
help of qualifiers i.e. short and long
Eg. Short int , long int
2.Secondary data type:-
This data type can be used for special purpose i.e.
Array, structure, union, pointer, function.
3.User defined data types:-
Those data types defined be a user, such data type
called user defined data type
In C language the enum keyword we can define user defined
data type
4.Empty data type:-
Those data type does not return any value, such data type
referred as empty data type.
Eg. Void is an empty data type.
1.5 Scope Resolution Operator:
Like C, C++ is also a block-structural language. Blocks and
scopes can be used in constructing programs. We know that the
same variable name can be used to have different meanings in
different blocks. The scope of the variable extends form the
point of its declaration till the end of the block containing the
declaration. A variable declared inside a block is said to be local
to that block.
………
………
{
Int x = 10;
………
………
}
………
………
{
………
……….
{
Int x = 1;
……..
………
}
The two declaration of x refer to two different memory location
containing different values. Statement in the second blocks
cannot refer to the declared in the first block, and vice versa.
Blocks in C++ are often nested. For ex following style is
common:
Block2 is contained in Block1. Note that a declaration in an
inner block hides a declaration of the same variable in an outer
block and, therefore, each declaration of x causes it to refer to a
different data object. Within the inner block, the variable X will
refer to the data object declared therein.
In C, the global version of a variable cannot be accessed
from within the inner block. C++ resolves this problem by
introduced a new operator :: called the scope resolution operator.
This can be used to uncover a hidden variable. It takes the
following form
:: variable-name
This operator allow access to the global version of a variable.
For example, ::count means the global version of the variable
count (and not the local variable count declared in that block).
Scope Resolution Operator:
#inlcude<iostram.h>
using name space std;
int m= 10; //global m
int main()
{
Int m=20; //m redeclared, local to main
{
int k = m;
int m = 30;//m declared again
//local to inner block
cout<<”we are in inner block \n”;
cout<<”k=”<<k<<”\n;
cout<<”m=”<<m<<”\n;
cout<<”::m”<<::m<<”\n”;
}
cout <<”\nwe are the outer block \n”;
cout<<”k=”<<k<<”n\;
cout<<”m=”<<m<<”\n;
cout<<”::m=”<<::m<<”\n”;
return 0;
}
The output of program is
we are in inner block
k=20
m = 30
::m = 10
we are in outer block
m = 20
::m =10
In the above program the variable m is declared at three places,
namely, outside the main(),function, inside the main(), and inside
the inner block.
1.6 Basic Input / Output Statements:-

• I/O Library Header Files:

There are following header files important to C++ programs:

Header File Function and Description

<iostream> This file defines the cin, cout, cerr


and clog objects, which correspond to
the standard input stream, the
standard output stream, the un-
buffered standard error stream and the
buffered standard error stream,
respectively.

<iomanip> This file declares services useful for


performing formatted I/O with so-
called parameterized stream
manipulators, such as setw and
setprecision.

<fstream> This file declares services for user-


controlled file processing.

The standard output stream cout:


The predefined object cout is an instance of ostream class. The
cout object is said to"connected to" the standard output device,
which usually is the display screen. The cout is used in

conjunction with the stream insertion operator, which is written


as << which are two less than signs.

Output Stream - A sequence of characters from the computer


to an output device. To output information in C++ we will use a
variable called cout
(pronounced "see-out"). The identifier cout stands for common
output. cout is a predefined variable in C++ that indicates you
are going to output a stream of characters to an output device.
cout uses an operator called the insertion operator (<<). You
will often see << referred to as “put to”. The insertion operator
requires two operands. For our purposes the operand on the left
will be the cout variable and the operand on the right will be an
expression. Examples:
The following expression is a literal constant of type c-string.

cout << “Hello World!”;


The following expression is a simple arithmetic expression.
cout << (num1 + num2) /2;
The following expression contains a literal constant of type c-
string followed by a variable. Note the insertion operator must
be used to separate the various items in the output stream..
cout << "The average is " << averageAge;

A general form specifies the proper syntax for a given


statement. The general form for the output statement is shown
below.
GENERAL FORM for cout:
cout << Expr Or String << Expr Or String ...;

The standard input stream cin:

Input Stream - A sequence of characters from an input device


to the computer. To input information in C++ we will use a
variable called cin (pronounced "see-in"). The identifier cint
stands for common input.
cin is a predefined variable in C++ that indicates you are going
to input a stream of characters from an input device (cin is
associated with the standard input device which is the
keyboard). cin uses an operator called the extraction operator
(>>). You will often see >> referred to as “get from”.
The extraction operator requires two operands. For our purposes
the operand on the left will be the cin variable and the operand
on the right will be a variable (char, int, float etc.). The general
form for the input statement in shows below:
GENERAL FORM for cin:
cin >> variable >> variable ...;

1.7Structure of C++ program:


C++ program would contain four section as shown below
these section may be placed in separate code files and then
compiled independently or jointly.
Include files
Class declaration
Member function def.
Main function prog.
It is common practice to organize a program into three separate
files. The class declaration are placed in a header file and the
definitions of member function go into another file. This
approach enables the programmer to separate the abstract
specification of the interface (class definition) from the
implementation details (member function definition). Finally the
main program that uses the class in placed in a third file which
“includes” the previous two files as well as any other files
required.
This approach is based on the concept of client server
model as shown below.

Member function

class definition

Server
Main function
program
Client
The class definition including the member functions constitute
the server that provides service to the main program known as
client. The client uses the server through the public interface of
the class.
1.8 Control Structure:
In C++, a large number of functions are used that pass
messages, and process the data contained in objects. A
function is set up to perform a task. When the task is
complex, many different algorithms can be designed to
achieve the same goal. Some are simple to comprehend,
while other are not. Experience has also shown that the
number of bugs that occur is related to the format of the
program. All the simple types of program will be executed
from top to bottom but user wants to some part of the
program to be executed again and again then we can
usages control statement or control structure.
In C++ programming language there are three
conditional structure can be used i.e. Conditional
statement, looping statement and jumping statement
1. Conditional statement:

• if statement: syntax:
if(condition)
{
Statement block;
}
“if” is a conditional statement it execute given statement block,
if the condition is true. Condition is always written in
parenthesis after if keyword in same line. To check condition we
have to use relational or logical operator. If we have to exectute
more than one statement when condition is true, then we have to
write these statements within closing and opening curly
brackets{}
Program:
#include<iostream.h>
#include<conio.h>
void main( )
{
int marks;
clrscr( );
cout<<”enter your marks”;
cin>>marks;
if(marks>35)
{
cout<<”you are pass”;
}
cout<<”please check you marks”;
}
• if------else statement: syntax:
if (condition)
{
statement _block 1;
}
else
{
statement_block2;
}
“if---else” statement consist of two parts as ‘if’ block and ‘else’
block condition is always written in parenthesis after ‘if’
keyword in same line. To check the condition we have to use
relational or logical operators.
Program:
#include<iostream.h>
#include<conio.h>
Void main( )
{
int marks;
clrscr( );
cout<<”enter your marks”;
cin>>marks;
if(marks>=35)
{
cout<<”you are pass”;
}
Else
{
cout<<”you are fail”;
}
}
• Multiple if statement: syntax:
if (condition)
{
statement _block 1;
}
else
if (condition)
{
Statement _block2;
}
else
-----
-----
If (condition n)
{
statement _block n;
}
else
{
statements;
}
When more than one ‘if’ are placed in a series or sequence ,then
such ‘if’ structure is called as multiple structure. In this structure
first ‘if’ condition is checked if it is true then statement block is
executed. If condition is false then second ‘if’ condition is
checked. If it is true then, statement block for that ‘if’ is
executed and rest of ‘if’ conditions are skipped.
Program:
#include<iostream.h>
#include<conio.h>
Void main( )
{
Int num1, num2, ch;
Clrscr( );
Cout <<”enter values”;
Cin>>num1>>num2;
Cout<<”\add\n2sub\n3 mul \n4 div \n type choice (1-4):”;
Cin>>ch;
If (ch==1)
{
Cout<<”n\ addition is num1+num2”;
}
Else
If(ch

You might also like