Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
77 views28 pages

C++ Text

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 28

C++ is an object-oriented programming language.

It
was developed by Bjarne Stroustrup, AT&T Bell
Laboratories in Murray Hill, New Jersey, USA, in the
early 1980’s. Stroustrup, an admirer of Simuala67
and a strong supporter of C, wanted to combine the
best of both the languages and create a more
powerful language that could support object-
oriented programming features and still retain the
power and elegance of C. the result was C++.
Therefore, C++ is an extension of C with a major
addition of the class construct feature of Simual67.
Since the class was a major addition to the original
C language, Stroustrup initially called the new
language ‘C with classes’. However, later in 1983,
the name was changed to C++. The idea of C++
comes from the C increment operator ++, thereby
suggesting that C++ is an augmented (incremented)
version of C.
During the early 1990’s the language underwent a
number of improvements and changes. In
November 1997, the ANSI/ISO standards committee
standardized these changes and added several new
features to the language specifications.
C++ is a superset of C. Most of what we already
know about C applies to C++ also. Therefore, almost
all C programs are also C++ programs. However,
there are a few minor differences that will prevent
a C program to run under C++ compiler. We shall
see these differences later and when they are
encountered . a comprehensive list of major
differences between ANSI and ANSI C++ is given in
Appendix A.
The most important facilities that C++ adds on to C
are classes, inheritance , function overloading, and
operator overloading. These features enable
creating of abstract data type inherit properties
from existing data types and support
polymorphism, thereby making C++ truly object-
oriented language.
The object-oriented features in C++ allow
programmers to build large programs with clarity,
extensibility and ease of maintenance,
incorporating the spirit and efficiency of C. the
addition of new features has transformed C from a
language that currently facilitate top-down,
structured design, to one that provides bottom-up,
object-oriented design.
Applications of C++ :- C++ is a versatile language for
handling very large programs. It is suitable for
virtually programming task including development
of editors, compilers, databases, communication
systems and any complex real-life application
systems.
 Since C++ allows us to create hierarchy-related
objects, we can build special object oriented
libraries which can be used later by many
programmers.
 While C++ is able to map the real-would
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 need 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 the near future.
A Simple C++ Program:- Let us begin with a simple
example of a C++ program that prints a string on
the screen.
#include<iostream>//include header file
Using namespace std;
int main()
{
cout<<”C++ is better than C.”;//C++ statement
return 0;
}// End of example
This simple program demonstrates several C++
features.
Program Features:- Like C, the C++ program is a
collection of functions. The above example contains
only one function, main(). As usual, execution
begins at main(). Every C++ program must have a
main(). C++ is a free-form language. With a few
exceptions, the compiler ignores carriage returns
and white spaces. Like C, the C++ statements
terminate with semicolons.
Commets:- C++ introduces a new comment symbol
//(double slash). Commets start with a double slash
symbol and terminate at the end of the line. 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.
The double slash comment is basically a single line
comment. Multiline comments can be written as
follows;
//this is an example of
//C++ program to illustrate
//some of its features
The C comment symbols /*,*/ are still valid and are
more suitable for multiline comments. He following
comment is allowed:
/* this is an example of C++ program to illustrate
some of its features*/
We can use either or both styles in our programs.
Since this is a book on C++, we will use only the C++
style. However, remember that we can not insert a
// style comment within the text of a program line.
For example, the double slash comment cannot be
used in the manner as shown below:
For(j=0;j<n;/*loops n times*/j++)
Output Operator:- the only statement in Program is
an output statement. The statement
cout<<”C++ is better than C”;
causes the string in quotation marks to be displayed
on he screen. This statement introduces two new
C++ features, cout and <<. The identifier cout
(pronounced as ‘C out’) is a predefined object that
represents the standard output stream in C++.
Here, the standard output stream represents the
screen. It is also possible to redirect the output to
other output devices. We shall later discuss streams
in detail.
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.
keyboard

cout “C++”

Object insertion operator variable

The object cout has a simple interface. If string


represents a string variable, then the following
statement will display its contents:
cout<<string;
you may recall that the operator << is the bit-wise
left-shift operator and it can still be used for this
purpose. This is an example of how one operator
can be used for different purposes, depending on
the context. This concept is known as operator
overloading, an important aspect of polymorphism.
Operator overloading is discussed in detail in
Chapter7.
It is important to note we can still use printf() for
displaying an output. C++ accepts this notation.
However, we will use cout << to maintain the spirit
of C++.
The iostream File:- We have used the following #
include directive in the program:
#include <iostream>
This directive causes the preprocessor to add the
contents of the iostream file to the program. It
contains declarations for the identifier cout and the
operator <<. Some old versions of C++ use a header
file called iostream. This is one of the changes
introduced by ANSI C++.(We should use iostream.h
if the compiler does not support ANSI C++ features.)
The header file iostream should be included at the
beginning of all programs that use input/output
statements Note that the naming comversions for
header files may very. Some implementations use
iostream.hpp; yet others iostream.hxx. we must
include appropriate header files depending on the
contents of the program and implementation.
Tables 2.1 and 2.2 provide lists of C++ standard
library header files that may be needed in C++
programs. The header files with .h extension are
“old style” files which should be used with old
compilers. Table 2.1 also gives the version of these
files that should be used with the ANSI standard
compilers.
Header file Contents and purpose New
version
<assert.h> Contains macros and <cassert>
information for adding
diagnostics that aid
program debugging.

<ctype.h> Contains function <cctype>


prototypes for fuctions
that test charactes for
certain properties, and
function prototypes for
functions that can be
used to convert
lowercase letters to
uppercase letters and
vice versa.

<float.h> Contains the floating- <cfloat>


point size limits of the
system.

<limits.h> Contains the integral <climits>


size limits of the
system.

<math.h> Contains function <cmath>


prototypes for math
library functions.

<stdio.h> Contains function <cstdio>


prototypes for the
standard input/output
library functions and
information used by
them.

<stdlib.h> Contains function <cstdlib>


prototypes for
conversion of numbers
to text, text to
numbers, memory
allocation, random
numbers, and various
other utility functions.

<string.h> Contains function <cstring>


prototypes for C-style
string processing
functions.

<time.h> Contains function


prototypes and types
for manipulating the
time and date.
<iostream.h> Contains function <iostream>
prototypes for the
standard input and
standard output
functions.

<iomanip.h> Contains function <iomanip>


prototypes for the
stream manipulators
that enable formatting
of streams of data.
<fstream.h> Contains function <fstream>
prototypes for functions
tat perform input from
files on disk and output
to files on disk.

Namespace : Namespace is a new concept


introduced by the ANSI C++ standards committee.
This defines a scope for the identifiers that are
used in a program. For using the identifiers defined
in the namespace scope we must include the using
directive, like
Using namespace std;
Here, std is the namespace where ANSI C++
standard class libraries are defined. All ANSI C++
programs must include this directive. This will
bring all the identifiers defined in std to the
current global scope. Using and namespace are the
new keywords of C++. Namespaces are discussed
in detail in Chapter 18.
Return Type of main()- In C++ , main() returns an
integer type value to the operating system.
Therefore, every main() in C++ should end with a
return(0) statement; otherwise a warning or an
error might occur. Since main() returns an integer
type value, return type for main() is explicitly
specified as int. note that the default return type
for all functions in C++ is int. the following main
without type and return will run with a warning:
main()
{
………..
…………
}
More C++ Statement- Let us consider a slightly
more complex C++ program. Assume that we
would like to read two numbers from the
keyboard and display their average on the screen.
C++ statements to accomplish this is shown in
program
#include<iostream>
using namespace std;
int main()
{
float number1,number2,sum,average;
cout<<”enter two numbers:”
cin<<number1<<number2;
sum=number1+number2;
average=sum/2;
cout<<”sum=”<<sum<<”\n”;
cout<<”average=”<<average<<”\n”;
return 0;
}
The output of Program is
Enter two numbers: 6.5 7.5
Sum=14
Average=7
Variables – the program uses four variables
number1,number2, sum and average. They are
declared as type float by the statement.
Float number1,number2,sum, average;
All variables must be declare before they are used
in the program
Input operator – the statemet
cin<<number1;
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 number1. The
identifier cin(pronounced c in) 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 .
this corresponds to the familiar scanf() operation.
Like<<, the operator >> can also be overloaded.

Object extraction operator variable

cin 45.5

keyboard

Fig:- Input using extraction operator

Cascading of I/O Operator: We have insertion


operator << repeatedly in the last two statements
for printing results.
The statement
cout<<”sub=”<<sum<<”\n”;
first sends the string “Sum=” to cout and then send
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<< one statement is called
cascading. When cascading an output operator, we
should ensure necessary blank spaces between
different items. Using the cascading technique, the
last two statements can be combined as follows:
cout<<”sum=”<<sum<<”\n”<<”average=”<<average
<<”\n”;
this is one statement but provides two lines of
output. If you want only one line of output, the will
statement will be.
cout<<”sum=”<<sum<<”\n”<<”average=”<<average
<<”\n”;
the output will be:
sum=14 average=7
we cam also cascade input operator>>as shown
below:
cin>>number1>>number2;
the values are assigned from left to right. That is, if
we key in two valued, say, 10 and 20 , then 10 will
be assigned to number1 and 20 number2.
An example with class:
One of the major features of C++ is classes. They
provide a method of binding together data and
functions which operate on them. Like structures
in C, classes are user-defined data types.
Program shows the use of class in a C++ program.
#include<iostream>
using namespace std;
class person
{
char name[30];
int age;
public:
void getdata();
void display();
};
void person:: getdata()
{
cout<<”enter name:”;
cin>>name;
cout<<”enter age”;
cin>>age;
}
void person:: display()
{
cout<<”\n name:”<<name;
cout<<”\n age”<<age;
}
int main()
{
person p;
p.getdata();
p.display();
return 0;
}
The output of program
Enter name: ravinder
Enter age: 30
Name: ravinder
Age: 30
cin can read only one word and therefore we
cannot use names with blank spaces.
The program defines person as a new data of type
class. The class person includes two basic data type
items and two functions to operate on that data.
These functions are called member functions. The
main program uses person to declare variables of
its type. As pointed out earlier, class variables are
known as objects. Here, p is an object of type
person. Class objects are used to invoke the
functions defined in that class. More about classes
and objects is discussed in chapter 5.
Structure of C++ Program:
As it can be seen from the Program , a typical C++
program would contain four sections as shown in
Fig. these sections may be placed in separate code
files and then compiled independently or jointly.

Include files
Class declaration
Member functions definitions
Main function program
It is a common practice to organize a program into
three separate files. The class declarations are
placed in a header file and the definitions of
member functions go into another file. This
approach enables the programmer to separate the
abstract specification of the interface (class
definition) from the implementation details
(member functions definitions). 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 files required.
This approach is based on the concept of client-
server model as shown in fig. the class definition
including the member functions constitute the
server that provides services to the main program
known as client. The client uses the server through
the public interface of the class.
Member functions

Class definition
Server
client
Main function program

fig:- The client-server model

Creating the source file:- Like C programs, C++


programs can be created using any text editor. For
example, on the UNIX, we can use vi or ed text
editor for creating and editing the source code. On
the DOS system, we can use edlin or any other
editor available or a word processor system under
non-document mode.
Some systems such as Turbo C++ provide an
integrated environment for developing and editing
programs. Appropriate manuals should be
consulted for complete details.
The file name should have a proper file extensions
to indicate that it is a C++ program file. C++
implementations use extensions such as .c, .c ,.cc,
.cpp and .cxx. Turbo C++ and Borland C++ use , c
for C programs and .cpp (C plus plus) for C++
programs. Zortech C++ system uses .cxx while
UNIX AT&T version uses .C (capital C) .cc. The
operating system manuals should be consulted to
determine the proper file name extensions to be
used.
Compiling and Linking: The process of compiling
and linking again depends upon the operating
system. A few popular systems are discussed in
this section.
Unix AT&T C++: The process of implementation of
a C++ program under UNIX is similar to that of a C
program. We should use the “CC” (uppercase)
command to compile the program. Remember we
use lowercase “cc” for compiling C programs. The
command
CC example.C
At the UNIX prompt would compile the C++
program source code contained in the file
example.C. The compiler would produce an object
file example.o and then automatically link with the
library functions to produce an executable file. The
default executable filename is a.out.
A program spread over multiple files can be
compiled as follows:
CC file1.C file2.o
The statement compiles only the file file1.C and
links it with the previously compiled file2.o file.
This is useful when only one of the files needs to
be modified. The files that are not modified need
not be compiled again.
Turbo C++ and Borland C++: Turbo C++ and Borland
C++ provide an integrated program development
environment under MS DOS. They provide a built-
in editor and a menu bar which includes options
such as File, Edit, Compile and Run.
We can create and save the source files under the
File option, and edit them under the Edit option.
We can then compile the program under the
Compile option and execute it under the Run
option. The Run option can be used without
compiling the source code. In this case, C++ being
the most popular compiler, creation and execution
of programs under Turbo C++ system are discussed
in detail in Appendix B.
Visual C++: It is a Microsoft application
development system for C++ that runs under
windows. Visual C++ is a visual programming
environment in which basic program components
can be selected through menu choices, buttons,
icons, and other predetermined methods.
Development and execution of C++ programs
under windows are briefly explained in Appendis
C.
Summary :
 C++ is a superset of C language.
 C++ adds a number of object-oriented features
such as objects, inheritance, function
overloading and operator overloading to C.
These features enable building of programs
with clarity, extensibility and ease of
maintenance.
 C++ can be used to build a variety of systems
such as editors, compilers, databases,
communication systems, and many more
complex real-life application systems.
 C++ supports interactive input and output
features and introduces a new comment
symbol // that can be used for single line
comments. It also supports C-style comments.
 Like C programs, execution of all C++ program
begins at main() function and ends at return()
statement. The header file iostream should be
included at the beginning of all programs that
use input/output operations.
 All ANSI C++ programs must include using
namespaces std directive.
 A typical C++ program would contain four basic
sections, namely, include files section, class
declaration section, member function section
and main function section.
 Like C programs, C++ programs can be created
using any text editor.
 Most compiler systems provide an integrated
environment for developing and executing
programs. Popular systems are UNIX AT&T
C++, Turbo C++ and Microsoft Visual C++.

You might also like