Sunteți pe pagina 1din 35

History of C++

C++ is an object oriented programming language. It is


developed by Bajarne Stroustrup at AT & T Bells laboratory
in Murray hills New jersey USA in early 1980s. Stroustrup was
an admirer of Simula 67 and a strong supporter of C wanted
to combine the best of both the languages & create a more
powerful language that could support object oriented
programming (OOP) & still retained the power and alligence
of C. The result was C++. Therefore C++ is an extension of
C with major addition of the class construct feature of Simula
67. Since the class was a major addition to the original C
language Stroustrup initially called the new language C with
classes. Later in 1963 the name changed to C++. C++ comes
from C increment operator ++. During the early 1990s the
language underwent a no. of improvements and changes. In
November 1997 NC-ISO standard committee standardized
these changes & added several new features to the language.
Specification:
The object oriented features of C++ allows programmers to
built large programme with clarity, extensibility & ease of
maintenance incorporating the spirit and efficiency of C.
Applications of C++

C++ is a versatile language for handling very large


program. It is suitable for virtuality, any programming
task including development of editor, compiler, database,
communication

system

&

any

complex

real

life

application system.
Since C++ allows us to create hierarchy related objects we
can built special object oriented libraries which can be
used later by many programs.
While C++ is able to map the real world problem
properly. The C part of C++ gives the language the ability
to get close to machine level details.
C++ programs are easily maintainable & expandable.
When a new feature needs to be implemented it is very
easy to add to the existing structure of an object.
It is expected that C++ will replace C as a general
purpose language in a near future.
Striking features of OOPS
Emphasis on data rather than procedure.
Programs are divided into classes & classes can be used
with the creation of objects.
Data structures are designed such that they characterized
the objects.

Functions that operate on that data of an object are tied


together in the data structure.
Data hidden cannot be accessed by external functions.
Objects may communicate with each other through
functions.
New data & functions can be easily added whenever
necessary.
Follows bottom-up approach in program design.

Basics of OOPS
Objects
Classes
Data Abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
Objects: The object is often instance of class. Objects are
the basic runtime entities in an object oriented system.
They may represent a person, a place, a bank account or
any item that program has to handle. Programming

problem is analyzed in terms of objects & the nature of


communication between them. Program objects should be
chosen such that they match closely with real world
objects. Objects take up place in the memory & have an
associated address like a record in PASCAL or a
structure in C. When a program is executed the objects
interact by sending message to one another. Each object
contains data & code to manipulate the data. The objects
can interact without having to know details of each
others data or code. It is sufficient to know the type of
message excepted & type of response returned by the
objects.
Classes: Objects maintain data & code to manipulate that
data. The entire set of data & code of an object can be
made a user defined data type with the help of class.
Infact, objects are variables of type class or objects are
members of class. Once a class has been defined we can
create any no. 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 object of
similar type. Classes are user defined data types and
behave like the built in types of the programming

language. The syntax used to create an object is no


different than syntax used to create an integer object in C.
Eg: int a, b, c;
student s1, s2, s3;
Data Abstraction and Encapsulation: The wrapping of a
data and function into a small unit (called class) is known
as encapsulation. Data encapsulation is most striking
feature of a class. The data is not accessible to the outside
world and only those functions which are wrapped in the
class can access data. This functions provide the interface
between the objects, data and the program. This
insulation of the data from the direct access by the
program is called data hiding or information hiding.
Abstraction: It refers to the act of representing the
features without including the background details or
explanation. Classes use the concept of abstraction and
are defined as a list of abstract attributes.
Eg: Size, weigh or costs and functions to operate on these
attribute. They encapsulate all the essential properties of
the objects that are to be created. The attributes are
sometimes called data members because they hold
information. The function that operate on these data are
called methods or member functions. Since the classes use

the concept of data abstraction, they are known as


abstract data type.
Inheritance: This is a process by which objects of one
acquire the properties of objects of another class. It
supports the concept of hierarchical classification. In
OOPS 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 existing one. The
new class will have the combined features of both the
classes. The real appeal and power of the inheritance
mechanism is that it allows the programmer to reuse a
class i.e. almost but not exactly what he wants and to
tackle the class in such a way that it does not introduce
any undesirable side effects into the rest of the classes.
Polymorphism: It is another important OOPS concept. It
is a Greek word means the ability to take more than one
form and operation may exhibit different behavior in
different instances. The behavior depends upon the types
of data used in the operation. The process of making an
operator to exhibit different behavior in different
instances is known as operator overloading.

E.g. A single name can be used to handle different


number and different type of arguments.
Shape
Draw ( )
Circle Object
Draw (circle)

Box Object
Draw (box)

Triangle Object
Draw (triangle)

Polymorphism plays important role in allowing the


objects having different internal structures to share same
external interface. This means that general class of
operation may be accessed in the same manner. Even
though specific action associated with each operation may
differ.
Dynamic Binding: Binding refers to linking of procedure
called to the code to be executed and 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 is not known until the
time of the call at runtime. It is associated with
polymorphism reference. A function call associated with a
polymorphic reference depends on a dynamic time of that
reference i.e. at runtime the code, the object and their
current reference will be called.

Message Passing: An OOPS consists of set of objects that


communicate

with

each

other.

The

process

of

programming in an object-oriented language therefore


involves the following basics steps:
1) Creating class: That defines objects and their
behavior.
2) Creating objects from the class definition.
3) Establishing communications among objects.
Objects communicates with one another by sending
and receiving information much the same way as the
people pass message to one another. The concept of
message passing makes it easier to talk about building
systems that directly modal or simulate their real world
counter parts. A message for an object is a request for
execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired
result. Message passing involves specifying the name of
the object, the name of the function(message) and
information to be send.

NameSpace
It is the new concept introduced by NCC++ standard and
committee. This defines a scope for the identifier that are

used in a program. For using the identifier defined in the


namespace scope are must include the using directive.
Syntax: Using namespace std;
Here, std is the namespace where NCC++ std class libraries
are defined. All NCC++ programs must include this
directive. This will bring all the identifier defined in std to
the current global scope. Using and namespace are the
new keywords of C++.
Tokens: The smallest individual units in the program are
known as token. C++ has the following token:
1) Keyword
2) Identifier
3) Constants
4) String
5) Operators
Keywords:
ASM, AUTO, BREAK, case, catch, char, class, const,
continue, default, delete, do, double, else, enum, extern, float,
for, friend, goto, if, inline, int, long, new, operator, private,
protected, public, register, return, short, signed, sizeof, static,
struct, switch, template, this, throw, try, typedef, union,
unsigned, virtual, void, volatile and while.

Basic Datatypes:
C++ Datatypes

User Defined
Datatype

Built-in
Datatype

Structure
Union
Class
enum

Integral
Type

int

Derived Datatype

void

char

array
function
pointer
reference

Floating
Point

float

double

Type

Size

Range

Char
Unsigned char
Signed char
int
Unsigned int
Signed int
Long int
Signed long int
Unsigned long int
Float
Double
Long double

1
1
1
2
2
2
4
4
4
4
8
10

-128 to 127
0 to 255
-128 to 127
-32768 to 32767
0 to 65535
-32768 to 32767
-2147483648 to 2147483647
0 to 429496795
0 to 429496795
3.4E-38 to 3.4E+38
1.4E-308 to 1.7E+308
3.4E-4942 to 1.1E4932

Reference Variable:
C++ introduces a new kind of variable known as reference
variable. It provides an alternative name for the previously
defined variable.
Syntax: datatype &reference name=variable name
E.g. float total=100;
float &sum=total;
total is the float type variable that has already been declared.
sum has an alternative name declared to represent the variable
total. Both the variable refer to the same data object in the
memory.
//p1.cpp

Operators
::

Scope resolution operator

::*
->*

Pointer to member declarator


Pointer to member operator

.*
Delete

Pointer to member operator


Memory release operator

Endl

Line feed operator

New

Memory allocation operator

Setw

Field width operator

//p2.cpp
Like C, C++ is also a block structured language. Blocks and
scopes can be used in constructing programs. We know that
same variable name can be used to have differentiation
meanings in differentiation blocks. The scope of the variable
extent from the points of its declaration till the end of the block
containing the declaration. A variable declared in site of block
is said to be local to that block. In C, global version of the
variable cannot be accessed from within the inner block. C++
resolves this problem by introducing a new operator called the
scope resolution operator. This can be used to uncover the
hidden variable. This operator allows access to the global
version of the variable in the inner block.
Member Dereferencing Operators
C++ permits to define a class containing various types of data
and functions as members. C++ also permits to access the class
members through pointers.
Operators
::*
*

Functions
To declare a pointer to a member of a class.
To access a member using object name and a

->*

pointer to that member.


To access the member using a pointer to the object
and a pointer to that member.

Memory Management Operator


New
Delete
All the functions in C used to allocate memory dynamically at
runtime are also supported by C++. It also defines two unary
operators new and delete that perform the task of
allocation and freeing the memory in a better and easier way.
Since these operators manipulate memory on the free store
they are also known as free store operator. An object can be
created by using new, destroyed by using delete as and
when required.
Manipulator
Manipulators are the operators that are used to format the
data display. The most commonly used manipulators are
endl and setw.
The endl manipulator when used in an output statement
ends the line and goto next line, setw is used to set the width.
Objects

Initially, different parts (entities) of a problem are examined


independently. These entities are chosen because they have
some physical or conceptual boundaries that separate them
from the rest of the problem. The entities are then represented
as objects in the program. The goal is to have a clear
correspondence between physical entities in the problem
domain and objects in the program.
In other words, an object can be a person, a place, or a
thing with which the computer must deal. Some objects may
correspond to real-world entities such as students, employees,
bank accounts, inventory items, etc. Whereas, others may
correspond to computer hardware and software components.
Hardware components include a keyboard, port, video display,
mouse etc and software components include stacks, queues,
trees etc.
Objects mainly serve the following purposes:
Understanding of the real world and a practical base for
designers.
Decomposition of a problem into objects depends on
judgment and nature of the problem.
Every object will have data structures called attributes
and behavior called operations.
The different notations of an object uniting both the data
and operations are as shown:

Object Name
Attribute 1

Object Name
Attribute 1

Attribute 2

Attribute 2

Operation 1

Attribute N
Operation 1

Attribute N

Operation 2

Operation 2
|
|

Operation N

Operation N

Operation 2

Operation 1

Attribute 1
|
|
Attribute N

|
|

Operation N

Account
AccountNumber
AccountType
Name
Balance
Deposit()
Withdraw()
Enquire()

|
|

Account
AccountNumber
AccountType

Deposit()

Different ways of representing an object

Name

Balance

Withdraw()

Enquire()

Deposit()

Withdraw()

Accountnumber
Accounttype
Name
Balance

Enquire()

Different ways of representing the account object

Classes
The objects with the same data structure (attributes) and
behavior (operations) are grouped into a class. All those objects
possessing similar properties are grouped into the same unit.
Person Objects Abstract
Boy
Girl

Into

Person Class
Attributes: Name, Age, Gender
Operations: Speak( ), Listen( ),

Walk( ).

Vehicle Objects

Abstract

Car

Into

Vehicle Class
Attributes: Name, Model, Color
Operations: Start ( ), Stop ( ),
Accelerate ( ).

Polygon Objects
Triangle

Abstract
Into

Polygon Class
Attributes: Vertices, Border,

Hexagon

Color, Fillcolor.
Operations: Draw(), Erase(),
Move().

In the case of Person class, all objects have similar attributes


like Name, Age, Gender and similar operations like Speak,
Listen, Walk. So boy and girl objects are grouped into the
Person class. Similarly, other related objects such as triangle,
hexagon, and so on, are grouped into the Polygon class.
Every object is associated with data and functions which
define meaningful operations on that object. For instance, in
C++, related objects exhibiting the same behavior are grouped
and represented by a class in the given way:
class account

{
private: char Name[20];

//data members

int AccountType;
int AccountNumber;
float Balance;
public: Deposit( );

//member functions

Withdraw( );
Enquire( );
};
This declaration is similar to the structure declaration in C. It
enables the creation of the class variables called objects.
For E.g. the following statements,
account savings_account;
account current_account;
account fd_account;
create

instances

of

the

class

account.

They

define

savings_account, current_account and fd_account as the


objects of the class account.
Each class describes a possibly infinite set of individual
objects; each object is said to be an instance of its class and
each instance of the class has its own value for each attribute
but shares the attribute name and operations with other

instances of the class. The following points on classes can be


noted:
A class is a template that unites data and operations.
A class is an abstraction of the real world entities with
similar properties.
A class identifies a set of similar objects.
Ideally, the class is an implementation of abstract data
type.
Encapsulation and Data Abstraction
Encapsulation is a mechanism that associates the code and the
data it manipulates and keeps them safe from external
interference and misuse.
Creating new data types using encapsulated-items, that are
well suited to an application to be programmed, is known as
data abstraction. The data types created by the data
abstraction process are known as Abstract Data Types (ADTs).
Data abstraction is a powerful technique, and its proper usage
will result in optimal, more readable, and flexible programs.
Data Structure

Operations
(Functions)

An abstract data type

//Printing Hello World message in C


#include<stdio.h>
void main()
{
printf(Hello World);
}
Output
Hello World
The Hello World program will also work in C++, since it
supports the ANSI-C function library. However, the program
could be rewritten using C++ streams. The C++ equivalent of
the Hello World program is listed in the program.
#include<iostream.h>
void main()
{
cout<<Hello World;
}
Output

Hello World
The header file iostream.h supports streams programming
features by including predefined stream objects. The C++s
stream insertion operator << sends the message Hello World
to the predefined console object, cout, which in turn prints on
the console. The Hello World program in C++ is shown for the
purpose of comparative analysis.
1. //hello.cpp: printing hello world msg
2. #include<iostream.h>

Comment

Preprocessor Directive

3. void main( )

Function declarator

4. {

Function begin

5.

cout<<Hello World;

6. }

Body of the main function


Function end.

Preprocessor Directive
The preprocessor directive includes all the statements of the
header file iostream.h. It contains instructions and predefined
constants that will be used in the program. It plays a role
similar to that of the header file stdio.h of C. The header file
iostream.h contains declarations that are needed by the cout
and cin stream objects. There are a number of such
preprocessor directive provided by the C++ library, and they

have to be included depending on the build-in functions used in


the program. In addition, the users can also write preprocessor
directives and declare them in the beginning of the program
(usually, but they can be declared anywhere in the program).
In effect, these directives are processed before any other
executable statements in the source file of the program by the
compiler.
Streams Based I/O
C++ supports a rich set of functions for performing input and
output operations. The syntax of using these I/O functions is
totally consistent, irrespective of the device with which I/O
operations are performed. C++s new features for handling I/O
operations are called streams. Streams are abstractions that
refer to data flow. Streams in C++ are classified into
Output Streams
Input Streams
Output Streams
The output streams allow to perform write operations on
output devices such as screen, disk, etc. Output on the
standard stream is performed using the cout object. C++ uses
the bit-wise left-shift operator for performing console output

operation. The syntax for the standard output stream


operation is as follows:
cout<<variable;
The word cout is followed by the symbol <<, called the
insertion or put-to-operator, and then with the items
(variables/constants/expressions) that are to be output.
Object cout
Insertion or put-to-operator
Variable of standard or user-defined data type
cout<<variable;
More than one item can be displayed using a single cout output
stream object. Such output operations in C++ are called
cascaded output operations. For E.g. output of the age of a
person along with same message can be performed by cout as
follows:
cout<<Age=<<age;
The complete syntax of the standard output streams operation
is as follows:
Cout<<variable 1<<variable 2<<.<<variable N;
E.g.
//p3.cpp

The item endl in the statement


cout<<\n<<msg<<endl;
Serves the same purpose as \n and is known as manipulator.
Input Streams
The input streams allow to perform read operation with input
devices such as keyboard, disk, etc. Input from the standard
stream is performed using the cin object. C++ uses the bit-wise
right-shift operator for performing console input operation.
The syntax for standard input streams operation is as follows:
cin>>variable;
the word cin is followed by the symbol >> (extraction operator)
and then with the variable, into which the input data is to be
stored. The use of cin in performing an input operation is
shown as follows:
object cin
extraction or get operator
variable of standard or user-defined data type

cin>>variable;
Input of more than one item can also be performed using the
cin input stream object. Such input operations in C++ are
called cascaded input operations. The complete syntax of the
standard input streams operations is as follows:

cin>>variable 1>>variable 2>>.>>variable N;


E.g.
//p4.cpp
Performing I/O operations through the cout and cin are
analogous to the printf and scanf of the C language, but with
different

syntax

specifications.

The

following

are two

important points to be noted about the stream operations.


Streams do not require explicit data type specification in
I/O statement.
Streams do not require explicit address operator prior to
the variable in the input statement.
//p5.cpp

Literals-Constant Qualifiers
Literals are constants, to which symbolic names are
associated for the purpose of readability and ease of
handling standard constant values. C++ provides the
following 3 ways of defining constants:
#define preprocessor directive
Enumerated data types
const keyword

In C initialization with a constant value at the point of its


definition is allowed.
float PI=3.1452;
C++ overcomes the accidental change of the value of the
variable PI which is not restricted in C. C++ supports a new
constant qualifier for defining a variable, whose value cannot
be changed, once it is assigned with a value at the time of
variable definition.
Syntax: const [Datatype] Variablename=constantvalue;
Note: If Datatype is omitted, it is considered as integer by
default.
E.g. const float PI=3.1452;
const int TRUE=1;
const int FALSE=0;
const char *book_name=OOPS with C++;
//p6.cpp
In the above program, the use of the statement such as
PI=2.3;
to modify a constant type variable leads to the compilation
error: Cannot modify a const object.
Thus, the keyword const, can be used before a type to
indicate that the variable declared is constant and may
therefore not appear on the left side of the assignment(=)

operator. In C++, the const qualifier can be used to indicate the


parameters that are to be treated as read-only in the function
body.
E.g.
//p7.cpp
The function display() is suppose to output the input string
argument passed to it onto the console. But accidental use of a
statement such as
strcpy (msg, Misuse);
in display() modifies the input argument. This modification is
also reflected in the calling function; the string argument is a
pointer type and any modification in function will also be
reflected in the calling function. Such accidental errors can be
avoided by defining the input parameter with the const
qualifier. C++ overcomes the problem of modifying constant
variables.
//p8.cpp
The use of a statement such as,
strcpy(msg, Misuse);

in display() leads to a compilation

error. Thus, reminding the programmer regarding the


accidental modification of read-only type variables will protect
from common programming errors.

Scope Resolution Operator(::)


C++ supports a mechanism to access a global variable from a
function in which a local variable is defined with the same
name as a global variable. It is achieved using the scope
resolution operator.
Syntax:
::GlobalVariableName
The global variable to be accessed must be preceded by the
scope resolution operator. It directs the compiler to access a
global variable; instead of one defined as a local variable.
Thus, the scope resolution operator permits a program to
reference an identifier in the global scope that has been hidden
by another identifier with the same name in the local scope.
//p9.cpp
//p10.cpp

Variable Definition at the point of use


In C, local variables can only be defined at the top of a
function, or at the beginning of a nested block. In C++, local
variables can be created at any position in the code, even
between statements. Furthermore, local variables can be
defined in some statements, just prior to their usage.
//p11.cpp

//p12.cpp

Variable Aliases-Reference Variables


C++ supports one more type of variable called reference
variable, in addition to the value variable and pointer variables
of C. Value variables are used to hold some numeric values;
pointer variables are used to hold the address of (pointer to)
some other value variables. Reference variable behaves similar
to both, a value variable and a pointer variable. In the
program code, it is used similar to that of a value variable, but
has an action of a pointer variable. In other words, a reference
variable acts as an alias (alternative name) for the value
variables. The general format of declaring the reference
variable is as shown:
Standard or user defined datatype:char,short,int,float etc.
Reference Operator
C++ alias variable
C++ value variable
Data Type & ReferenceVariable=ValueVariable;
Syntax of reference variable declaration

The reference variable must be initialized to some variable


only at the point of its declaration. Initialization of reference

variable after its declaration causes compilation error. Hence,


reference variables allow to create alias (another name) of
existing variables.
E.g.
1) char &ch1=ch;

//ch1 is an alias of char ch.

2) int &a=b;

//a is an alias of int b.

3) float &x=y;
4) double &height=length;
5) int &x=y[100];

//x is an alias of y[100] element.

6) int n;
int *m=&n;
int &m=*p;
These declarations cause m to refer n ,which is pointed to by
the pointer variable p.
7) int &num=100;
This statement causes compilation error; constants cannot
be made to be pointed to by a reference variable. Hence the
rule, no alias for constant value.
Reference variables are not bounded to a new memory
location, but to the variables to which they are aliases.
//p13.cpp
In main(), the statements,
z=b;
z=c;

assign the value of variables b and c to the variable a since, the


reference variable z is its alias variable. It can be observed
that, the memory addresses of the variables a and z are same.
The reference variables are bound to memory locations at
compile time only.

Strict Type Checking


C++ is a strongly-typed language and it uses very strict type
checking. A prototype must be known for each function which
is called, and the call must match the prototype. The prototype
provides information of the type and number of arguments
passed and it also specifies the return type (if any) of the
function. In C++, function prototyping is compulsory if the
definition is not placed before the function call whereas, in C, it
is optional.
//p14.cpp
It produces error if there is a mismatch in argument types
and this can be overcome by placing the prototype of the
function max() before it is invoked.
//p15.cpp
//p16.cpp
Expressions &c and &d passed to swap() are not pointers to
integer data type. When a call to a function is made, the C++

compiler checks its parameters against the parameter types


declared in the function prototype. The compiler flags errors if
improper arguments are passed.

Parameters Passing by Reference


A function in C++ can take arguments passed by value, by
pointer, or by reference. The arguments passed by reference is
an enhancement over C. A copy of the actual parameters in the
function call is assigned to the formal parameters in the case of
pass-by-value, whereas the address of the actual parameters is
passed in the case of pass-by-pointer. In the case of pass-byreference, an alias (reference) of the actual parameters is
passed. Mechanism of parameter linkage is as shown:
Parameter passing Mechanism
Variable Name

Data Type

Actual
parameter

Type

Value

Formal
parameter

Type

Value

(a)

Actual
Formal
parameter
parameter

Storage Location

Call-by-value

Type
Type

Value

(b)

Call-by-pointer/reference

Consider an example of swapping 2 numbers to illustrate the


mechanism of parameter passing by reference. The function
definition with pointer type parameters is as shown:
void swap(int *p, int *q)

//by pointers

{
int t;
t=*p;
*p=*q;
*q=t;
}
A call to the function swap( )
swap(&x,&y) has effect on the values of x and y i.e. it
exchanges the contents of variables x and y. The above
swap( - - ) function can be redefined by using a new parameter
passing scheme, call by reference as follows:
void swap(int &x, int &y)
{
int t;

//by reference

t=x;
x=y;
y=t;
}
Program having swap( - - ) function with call-by-reference
mechanism for parameter passing is as shown:
//p17.cpp
In main( ), the statement
swap(a,b);
is translated into
swap(&a,&b);
internally during compilation; the prototype of the function
void swap(int &x, int &y)

//by reference

indicates that the formal parameters are of reference type and


hence, they must be bound to the memory location of the actual
parameter. Thus, any access made to reference formal
parameters in swap( ) refers to the actual parameters. The
statements,
t=x;
x=y;
y=t;
in the body of swap( ) function, internally (as treated by the
compiler) have the following meaning.

t=*x;

//store the value pointed by x into t.

*x=*y; //store the value pointed by y into location pointed by x


*y=t;

//store the value stored by t into location pointed by y.

because, the formal parameters are of reference type and


therefore, the compiler treats them similar to pointers, but does
not allow the modification of the address stored in them.

S-ar putea să vă placă și