|
Like C, C++ began its life at Bell Labs, where
Bjarne Stroustrup developed the language in the early 1980s. In his own words,
"C++ was designed primarily so that my friends and I would not have to program
in assembler, C,or various modern high-level languages.Its main purpose was to
make writing good programs easier and more pleasant for the individual
programmer".
A computer simulation language called Simula67
inspired C++'s OOP aspect.Stroustrup added OOP featuresto C without
significantly changing the C component. Thus, C++ is a superset of C,meaning
that any valid C program is a valid C++ program,too.There are some minor
discrepancies,but nothing crucial. C++ programs can use existing C software
libraries. Libraries are collections of programming modules that you can call up
from a program. They provide proven solutions to many common - programming
problems, thus saving you much time and effort. This has helped the spread of
C++.
The name C++ comes from the C increment
operator ++, which adds 1 to the value of a variable.The name C++ correctly
suggests an augmented version of C. While the OOP aspect of C++ gives the
language the ability to relate concepts involved in the problem,the C part of
C++ gives the language the ability to get close to the hardware. This
combination of abilities has helped the spread of C++. It may also involve a
mental shift of gears as you turn from one aspect of a program to another. Also,
because C++ grafts OOP onto C, you can ignore C++'s object oriented features.
The three most important facilities that C++
adds on to C are classes, function overloading and operator overloading. These
features enable us to create abstract data types, inherit properties from
existing data types and support polymorphism, thus making C++ a 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
facilitates top down, structured design, to one that provides bottom-up,
object-oriented design.
Simple program.
#include < iostream.h> / / include header file
void main( )
{
cout
<< "C+ + is better c."; / / C++ statement
}
Program Features:
Like C, the C++ program is a collection of functions. The 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.
Comments:
C++ introduces a new comment symbol // (double slash). Comments 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. The 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.However,remember that we
cannot 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++)
The only statement in example Program is an output statement. The statement
cout << "C++ is better C.";
causes the string in quotation marks to be displayed on the 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.
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. 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.
We have used the following #include directive in the program:
#
include <iostream.h>
This directive causes the preprocessor to add the contents of the iostream.h
file to the program. It contains declarations for the identifier cout and the
operator <<.Some old versions of C++ use a header file called stream.h instead
of iostream.h. The header file iostream.h should be included at the beginning of
all programs that use input/output statements.
We must include appropriate header files depending on the contents of the
program. For example if we want to use the very familiar printf( ) and scanf( )
functions, the header file stdio.h should be included.
Saving Your Program:
Once you've typed in your program, you should save it to the disk by selecting
Save from the File menu,or by pressing F2. It's good to do this before compiling
and running your program, so that if a bug crashes the system, you won't lose
the changes to your source file.
Compiling And Linking:
The program that you type into the Edit window constitutes the source file. When
it is saved to disk, it is an ASCII file similar to that generated by a word
processor. It has the .CPP file extension. Remember that a source file is not an
executable program; it is only the instructions on how to create a program.
Transforming your source file into an executable program requires two steps.
First, you must compile the source file into an object tile. The object file,
which has an .OBJ extension, contains machine-language instructions that can be
executed by the computer. However, these instructions are not complete. A second
step, called linking, is required. The linking step is necessary because an
executable program almost always consists of more than one object file. Linking
combines the object files into a single executable program.
Why does a program consist of more than one object file? There are two major
reasons. First, the programmer may have divided the program into several source
files. Each of these source files is then compiled into a separate object file,
and these object files must be1inked together. Thus turning your source file
into an executable file is a two-step process. First you compile your source
file into an object file, and then you link it with the necessary library
routines.
Compiling:
To compile the source file, select Compile to OBJ from the File menu. A window
called Compiling will appear. An entry called Lines compiled will change as
compiling progresses. When the process is finished, the window will display
Success: Press any key. The entries for Warnings and Errors will be 0.
As we noted, compilation creates all object file, which has the OBJ file
extension. The object file in our case is FIRST. OBJ
Linking:
To link your object file, select Link EXE file from the Compile menu. The FIRST
OBJ file will be combined with the one or more library files. The result is an
executable file.
Functions:
Functions are one of the fundamental building blocks of C++. The FIRST program
consists almost entirely of a single function called main ( ). Functions have
undergone major changes in C++. While some of these changes are simple, others
require a new way of thinking when organizing our programs. Many of these
modifications and improvements were driven by the requirements of the
object-oriented concept of C++. Some of these were introduced to make the C++
program more reliable and readable. The only part of this program that is not
part of the function is the first line - the one that starts with #include. A
function can be part of a class, in which case it is called a member function.
However, functions can also exist independent of classes.
Function Name:
The parentheses following the word main are the distinguishing feature of a
function. Without the parentheses the compiler would think that main referred to
a variable or to some other program element. The parentheses aren't always
empty. They're used to hold function arguments: value passed from the calling
program to the function.
The word void preceding the function name indicates that this particular
function does not have a return value.
Braces and the Function Body:
Braces (sometimes called curly brackets) surround the body of a function. They
surround or delimit a block of program statements. Every function must use this
pair of braces. In this example there is only one statement within the braces:
the line starting with cout. However, a function body can consist of many
statements.
Always Start with main( ) : When you run a c++ program, the first
statement executed will be at the beginning of a function called main ( ) .The
program may consist of many functions, classes, and other program elements, but
on start-up control always goes to main( ). If there is no function called main
( ) in your program, the linker will signal an error.
White Space:
Actually, the C++ compiler ignores white space almost completely. White space is
defined as spaces, carriage returns, linefeeds, tabs, vertical tabs, and form
feeds. These characters are invisible to the compiler. You can put several
statements on one line, separated by any number of spaces or tabs, or you can
run a statement over two or more lines. It's all the same to the compiler.
Keywords:
The keywords implement specific C++ language features. They are explicitly
reserved identifiers and cannot be used as names for the program variables or
other user-defined program elements.
Identifiers:
Identifiers refer to the names of variables, functions, arrays, classes, etc.
created by the programmer. They are the fundamental requirement of any language.
Each language has its own rules for naming these identifiers.
Table of C+ + keywords
|
asm |
double |
new |
switch |
|
auto |
else |
operator |
template |
|
break |
enum |
private |
this |
|
case |
extern |
protected |
throw |
|
catch |
float |
public |
try |
|
char |
for |
register |
typedef |
|
class |
friend |
return |
union |
|
const |
goto |
short |
unsigned |
|
continue |
if |
signed |
virtual |
|
default |
inline |
sizeof |
void |
|
delete |
int |
static |
volatile |
|
do |
long |
struct |
while |
- Only alphabetic characters, digits and underscores are
permitted.
- The name cannot start with a digit.
- Uppercase and lowercase letters are distinct.
- A declared keyword cannot be used as a variable name.
major difference between C and C++ is the limit of a name. While ANSI C
recognizes the first 32 characters in a name, C++ laces no limit on its length
and, therefore all the characters in a name are significant. Care should be
taken while exercising a variable that is being shared by more than one file
containing C and C++ programs. Some operating systems impose a restriction on
the length of such a variable name.
Basic Data Types:
Data types in C++ can be classified under various categories. 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, long, and short may be applied to character and integer basic
data types. However, the modifier long may also be applied to double.
Hierarchy of C++ data types: volatile
Table showing Size and range of C++ basic data types
|
Type |
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 int |
2 |
0 to 65535 |
|
signed int |
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 + 308 |
|
long double |
10 |
3.4E -4932 to 1.1 E + 4932 |
User-Defined Data Types:
Structures and Classes: We have used user-defined data types such as
struct and union in C. While these data types are legal in C++, some more
features have been added to make them suitable for object-oriented programming.
C++ also permits us to define another user-defined data type known as class,
which can be used, just like any other basic data type, to declare variables.
The class variables are known as objects.
Enumerated Data Type: An enumerated data type is another user-defined
type, which provides a way for attaching names to numbers, thereby increasing
comprehensibility of the code. The enum keyword (from C) automatically
enumerates a list of words by assigning them values O,1, 2, and so on.This
facility provides an alternative means for creating symbolic constants. The
syntax of an enum statement is similar to that of the struct statement.
Examples:
enum shape {circle, square, triangle};
enum colour {red, blue, green, yellow};
enum position {off, on};
The enumerated types differ slightly in C++ when compared with those in ANSI
C. In C++, the tag name shape, colour, and position become new type names. That
means we can declare new variables using these tag names.
Examples:
shape ellipse; // ellipse is of type shape
colour background; // background is of type colour
ANSI C defines the types of enums to be int's. In C++, each enumerated data
type retains its own separate type. This means that C++ does not permit an int
value to be automatically converted to an enum value.
Examples:
colour background = blue; // allowed
colour background = 7; // Error in C++
colour background = (colour) 7; //OK
Derived Data Types:
Arrays: The application of arrays in C++ is similar to that in C. The
only exception is the way character arrays are initialized. When initializing a
character array in ANSI C, the compiler will allow us to declare the array size
as the exact length of the string constant. For instance,
char string[3] = "xyz";
is valid in ANSI C. It assumes that the programmer intends to leave out the
null character \0 in the definition. But in C++, the size should be one larger
than the number of characters in the string.
char string[4] = "xyz"; II O.K. for C++
Pointers: Pointers are declared and initialized as in C.
Examples:
int
* ip; // Int pointer
ip = &x; // address of x assigned to ip
*ip = 10; // 50 assigned to x through indirection
C++ adds the concept of constant pointer and pointer to a
constant
Char *const ptr1="GOOD"; //constant pointer
We cannot modify the address that ptr1 is initialized to.
int
const *ptr2 = &m; // pointer to a constant
ptr2 is declared as pointer to a constant. It can point to any variable of
correct type, but the contents of what it points to cannot be changed. We can
also declare both the pointer and the variable as constants in the following
way:
const char *const cp="xyz";
The statement declares cp as a constant pointer to the string, which has been
declared as a constant. In this case, neither the address assigned to the
pointer cp nor the contents it points to can be changed. Pointers are
extensively used in C++ for memory management and achieving polymorphism.
Declaration Of Variables:
We know that, in C, all variables must be declared before they are used in
executable statements. This is true with C++ as well. However, there is a
significant difference between C and C++ with regard to the place of their
declaration in the program. C requires all the variables to be defined at the
beginning of a scope. When we read a C program, we usually come across a group
of variable declarations at the beginning of each scope level. Their actual use
appears elsewhere in the scope, sometimes far away from the place of
declaration. Before using a variable, we should go back to the beginning of the
program to see whether it has been declared and, if so, of what type it is.
C++ allows the declaration of a variable anywhere in the scope. This means
that a variable can be declared right at the place of its first use. This makes
the program much easier to write and reduces the errors that may be caused by
having to scan back and forth. It also makes the program easier to understand
because the variables are declared in the context of their use. The example
below illustrates this point.
#include<iostream.h>
void main ( )
{
float
x; // declaration
float sum = a;
for(int i = 1; i<5; i++) // declaration
{
cin
>>x;
sum = sum+x;
}
float average; // declaration
average = sum / i;
cout << average;
getch();
}
The only disadvantage of this style of declaration is that we cannot see at a
glance all the variables used in a scope.
Dynamic Initialization Of Variables:
One additional feature of C++ is that it permits initialisation of the variables
at run time. This is referred to as dynamic initialisation. Remember that, in C,
a variable must be initialised using a constant expression and the C compiler
would fix the initialisation code at the time of compilation: However, in C++, a
variable can be initialised at run time using expressions at the place of
declaration. For example, the following are valid initialisation statements:
..
..
int n = strlen(string);
float area = 3.14159 * rad * rad;
This means that both the declaration and initialisation of a variable can be
done simultaneously at the place where the variable is used for first time. The
example program illustrates this.
//
program to convert temperature from Fahrenheit to Celsius
#include<iostream.h>
void main( )
{
int ftemp;
cout<<"Enter temperature in Fahrenheit" ;
cin>> ftemp;
int ctemp = (ftemp-32) * 5/9;
cout<<"Equivalent in Celsius is: " <<ctemp<<'\n';
getch();
}
The statement cin >> ftemp; causes the program to wait for the user to
type in a number. The resulting number is placed in the variable ftemp. The
keyword cin (pronounced "C in") is an object, predefined in C++ to correspond to
the standard input stream, This stream represents data coming from the keyboard
(unless it has been redirected). The " is the extraction or get from operator.
It takes the value from the stream object on its left and places it in the
variable on its right.
Cascading <<:
The extraction operator << is used repeatedly in the second cout statement in
FAHREN This is perfectly legal. The program first sends the phrase Equivalent in
centigrade is to cout, then it sends the value of ctemp, and finally the newline
character '\n'.
The insertion operator >> can be cascaded with cin in the same way, allowing the
user to enter a series of values. However,this capability is not used so
often,since it eliminates the opportunity to prompt the user between inputs
Manipulators:
Manipulators are operators used with the insertion operator << to modify -- or
manipulate -- the way data is displayed. We'll look at two of the most common
here: endl and setw.
The endl Manipulator:This is a manipulator that causes a linefeed to be
inserted into the stream. It has the same effect as sending the single '/n'
character.
The setw Manipulator: You can think of each value displayed by cout as
occupying a field: an imaginary box with a certain width. The default field is
just wide enough to hold the value. That is, the integer 567 will occupy a field
three characters wide, and the string "pajamas" will occupy a field seven
characters wide. However, in certain situations this may not lead to optimal
results.
// demonstrates setw maniputator
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
void main()
{
long
pop1=2425785, pop2=47, pop3=9761;
cout << setw(8) << "LOCATION" << setw(12) << "POPULATION" << endl
<< setw(8) << "Porttity" << setw(12) << pop1 << endl
<< setw(8) << "Hightown" << setw(12) << pop2 << endl
<< setw(8) << "Lowville" << setw(12) << pop3 << endl;
getch();
}
The setw manipulator causes the number (or string) that follows it in the
stream to be printed within a field n characters wide, where n is the argument
to setw (n). The value is right justified within the field.
Type Conversion:
C++ like C, is more forgiving than some languages in the way it treats
expression involving sever al different data types. As an example, consider the
program below.
//shows mixed expression
#include <iostream.h>
#include <conio.h>
void main( )
{
int
count = 7;
float avgWeight = 155.5;
double totalWeight = count * avgWeight;
cout<< "TotalWeight ="<< totalWeight << endl;
getch();
}
Here a variable of type int is multiplied by a variable of type float to
yield a result of type double. This program compiles without error, the compiler
considers it normal that you want to multiply numbers of different types. Not
all languages are this relaxed. Some don't permit mixed, expressions,and would
flag as an error the line that performs the arithmetic in the above program.
Casts: the term applies to data conversions specified by the
programmer, as opposed to the automatic data conversions.Sometimes a programmer
needs to convert a value from one type to another in a situation where the
compiler will not do it automatically, resulting in an erroneous result. In such
case we might be able to solve the problem by using a cast. Here's an example:
//
Program to illustrate the effect of casts
#include < iostream.h>
void main( )
{
int
intvar = 25000;
intvar = (intvar * 10) / 10; // result too large
cout << "intvar = " << intvar << endl; // wrong answer
int intvar = 25000;
intvar =((long)intvar) * 10 / 10; // cast to long
cout << "intvar = " << intvar << endl; // right answer
}
When we multiply the variable intvar by 10, the result -250,000 is far too
large to fit in a variable of type int, or unsigned int. This leads to the wrong
answer, as shown in the first part of the program. We could redefine the data
type of the variables to be long; this provides plenty of room, since this type
holds numbers up to 2,14,74,83,647 . But suppose that for some reason, such as
keeping the program small, we don't want to change the variables to type long.
We can cast intvar to type long before multiplying. This is sometimes called
coercion;the data is coerced into becoming another type. The expression
long(intVar)
casts intVar to type long. It generates a temporary variable of type long
with the same value as intVar. It is this temporary variable that is multiplied
by 10. Since it is type long, the result fits. This result is then divided by 10
and assigned to the normal int variable intVar. Here's the program's output:
intVar = -1214
intVar = 25000
The first answer, without the cast, is wrong; but in the second answer, the
cast produces the correct result. You can use another syntax for casts. You can
say
(long)intvar
with the parentheses around the type rather than around the variable. This is
the only syntax acceptable in C, but in C++ the first approach (called
"functional notation") is preferred, because it is similar to the way to
functions.
Operators:
Arithmetic operators: C++ uses operators to do arithmetic. It provides
operators for five basic arithmetic calculations: addition, subtraction,
multiplication, division and taking the modulus. Each of these operators uses
two values (called operands) to calculate a final answer. Together, the operator
and its operands constitute an expression. For example, consider the following
statement:
int
wheels = 4 + 2;
The values 4 & 2 are operands, the + symbol is the addition operator, and 4 +
2 is an expression whose value is 6. Some of the basic arithmetic operators are
+, -, *, / and %.
Logical Operators: These operators allow you to logically combine
Boolean (true/ false) values. For example, today is a weekday has a Boolean
value, since it's either true or false.
Some of the logical operators are:
Logical AND -&&
Logical OR - ||
Logical NOT - !
Relational Operators: A relational operator compares two values. The
values can be any built-in C+ + data type, such as char, int or float or they
can be user-defined class.
Some of the relational operators are:
|
Greater than |
> |
|
Less than |
< |
|
Equal to |
= = |
|
Not equal to |
! = |
|
Greater than or equal to |
> = |
|
Less than or equal to |
< = |
Decision Statements:
Programs also need to make these one-time decisions. In a program a decision
causes a one-time jump to a different part of the program, depending on the
value of an expression. The most important is with if
else statement,
which chooses between two alternatives. This statement can be used without the
else, as a simple if statement. Another decision statement, switch,
creates branches for multiple alternative sections of code, depending on the
value of a single variable. Finally the conditional operator is used in
specialized situations. if construct: The if statement is the
simplest of the decision statements. The programs below illustrate this.
#include<iostream.h>
#include<conio.h>
void main ( )
{
> int
x;
cout<< "Enter a number";
cin>> x;
if(x >100)
cout<<"The number is greater than 100 \n";
getch();
}
The if keyword is followed by a test expression in parentheses. The
statements following the if are executed only once if the test expression is
true.
if...else construct: The if statement lets you do something if a
condition is true. If it isn't true, nothing happens. But suppose we want to do
one thing if a condition is true, and do something else if it's false. That's
where the if ...else statement comes in. It consists of an if statement,
followed by a statement or block of statements, followed by the keyword else,
followed by another statement or block of statements.
if(
condition)
statement; // if true
else
statement; // if false
if the test expression in the if statement is true, the program prints
one message; if it isn't, it prints the other.
else...if construct: The nested if
else statements can look
clumsy and can be hard to interpret, especially if they are nested more deeply.
However there's another approach to writing the same statements.
if(
first condition)
statement; // if true
else if( second condition )
statement; // if false
else
statement; // default
The compiler sees this as identical to if
else, but rearranged the
if's so that they directly follow the else's. The program goes down the ladder
of else
if's until one of the test expressions is true. It then executes the
following statement and exits from the ladder.
switch construct: If you have a large decision tree, and all the
decisions depend on the value of the same variable, you can probably consider a
switch statement instead of a series of if ...else or else if constructions.
Here's a simple example.
//
program to demonstrates SWITCH statement
#include <iostream.h>
#include<conio.h>
void main( )
{
int
speed;
cout << "\nEnter 33,45, or 78: "; cin >> speed;
switch(speed) {
case
33:
cout << "Green\n"; break;
case 45:
cout << "Yellow\n"; break;
case 78:
cout << "Red\n"; break;
}
getch();
}
This program prints one of three possible messages depending on whether the
user inputs the number 33,45 or 78 The keyword switch is followed by a switch
variable in parentheses
switch(speed)
Braces then delimit a number of case statements. Each case keyword is
followed by a constant, which is not in parentheses but is followed by a colon
case 33:
The data type of the case constants should match that of the switch variable.
Before entering the switch, the program should assign a value to the switch
variable. This value will usually match a constant in one of the case
statements. When this is the case, the statements immediately following the
keyword case will be executed, until a break is reached.
break construct: The break keyword causes the entire switch statement to
exit. Control goes to the first statement following the end of the switch.
The Conditional operator: This operator consists two symbols, which
operate on three operands. It's the only such operator in C+ +; other operators
operate on two or one operands. For example:
X =
(a>b) ? a : b
The part of this statement to the right of the equals sign is called
conditional expression. The question mark and the colon make up the conditional
operator. The expression before the question mark is the test expression. If the
test expression is true, then the entire conditional expression takes on the
value of the operand following the question mark. If it is false, the
conditional expression takes on the value of the operand following the colon.
Iteration statements:
do
while statement: The do
while is an exit - controlled loop. Based
on a condition, the control is transferred back to a particular point in the
program.
do
{
statement 1;
statement N;
} while(condition is true);
while statement: This is also a loop structure, but it an entry -
controlled one.
while( condition is true)
{
statement 1;
statement N;
}
for statement: The for is an entry - controlled loop and is used when
an action is to be repeated for a predetermined number of times.
for( initial value; test condition; update expression) {
statement 1;
statement N;
}
Methods to Include '#include':
We can use the #include directive in two ways in your programs. In the first
method the angle brackets < and > surrounding the filenames, for example
#include < iostream.h>
Angle brackets indicate that the compiler should begin searching for these
files in the standard INCLUDE directory. This directory holds the header files
supplied by Borland for the system. You can see what Turbo C++ thinks this
directory is (and change it if you want) by selecting Directory from the Options
menu.
In the second method you can also use quotation marks around the filename, for
example
#include "myheader.h"
Quotation marks instruct the compiler to begin its search for the header file
in the current directory; this is usually the directory that contains the source
file. You normally use quotation marks for header files you write yourself.
Either quotation marks or angle brackets work in anywise, but making the
appropriate choice speeds up the compilation process slightly by giving the
compiler a hint about where to find the file.
HOME
<<PREVIOUS
NEXT>> |