Migrating From C To C++
Migrating From C To C++
CSIT III
1 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
indicating the major steps carried out and explaining any particularly complex
piece of programming. This is essential if the program has to be extended or
corrected at a later date. This is a kind of documentation. Also C comment type
/*--------------*/ is also a valid comment type in C++.
2. The line
#include <iostream.h>
must start in column one. It causes the compiler to include the text of the named
file (in this case iostream.h) in the program at this point. The file iostream.h is a
system supplied file which has definitions in it which are required if the program
is going to use stream input or output. All programs will include this file. This
statement is a preprocessor directive -- that is it gives information to the
compiler but does not cause any executable code to be produced.
3. The actual program consists of the function main() which commences at the line
void main( ).
All programs must have a function main( ). Note that the opening brace ({) marks
the beginning of the body of the function, while the closing brace (}) indicates the
end of the body of the function. The word void indicates that main() does not return
a value. Running the program consists of obeying the statements in the body of
the function main().
4. The body of the function main contains the actual code which is executed by the
computer and is enclosed, as noted above, in braces {}.
5. Every statement which instructs the computer to do something is terminated by a
semi-colon. Symbols such as main(), { } etc. are not instructions to do something
and hence are not followed by a semi-colon. Preprocessor directives are
instruction to the compiler itself but program statements are instruction to the
computer.
6. Sequences of characters enclosed in double quotes are literal strings. Thus
instructions such as
cout << "Length = "
send the quoted characters to the output stream cout. The special identifier endl
when sent to an output stream will cause a newline to be taken on output.
7. All variables that are used in a program must be declared and given a type. In this
case all the variables are of type int, i.e. whole numbers. Thus the statement
int length, width;
declares to the compiler that integer variables length and width are going to be used
by the program. The compiler reserves space in memory for these variables.
2 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
int n;
cout<<"\nEnter Number";
cin>>n;
int sum=0;
8. Values can be given to variables by the assignment statement, e.g. the statement
area = length*width;
evaluates the expression on the right-hand side of the equals sign using the current
values of length and width and assigns the resulting value to the variable area.
9. Layout of the program is quite arbitrary, i.e. new lines, spaces etc. can be inserted
wherever desired and will be ignored by the compiler. The prime aim of
additional spaces, new lines, etc. is to make the program more readable. However
superfluous spaces or new lines must not be inserted in words like main, cout, in
variable names or in strings.
Output Stream:
The output stream allows us to 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. Variables can
e of any basic data types. The us of cout to perform an output operation is as shown :
Object cout
3 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
“Hello”
Hello cout <<
More than one item can be displayed using a single cout output stream object. Such out
put operations in C++ are called cascaded output operations. For example
cout<<”Age is: “<<age<<”years”;
This cout object will display all the items from left to right. If value of age is 30 then
this stream prints
Age is : 30 years
C++ does not restricts the maximum number of items to output. The complete syntax of
the standard output streams operation is as follows:
cout<<variable1<<vaariable2<<…………<<variableN;
The object cout must be associated with at least one argument. Like printf in C, A
constant value can be sent as an argument to the cout object.
e.g.
cout<<‟A‟; //prints a constant character A
cout<<10.99; //Prints constant 10.99
cout<<” “; //prints blanks
cout<<”\n”, //prints new line
Input Streams:
The input stream allows us to perform read operations 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 the standard output stream operation is as follows:
cin<<variable;
The word cin is followed by the symbol >> and then with variable, into which
input data is to be stored. The use of cin to perform an input operation is as shown :
Object cin
cin>> variable;
4 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
variable;
Hello cin >>
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.
In C printf and scanf functions, format strings ( %d,%s,%c etc) and address
operator (&) are necessary but in cin stream format specification is not necessary and in
the cout stream format specification is optional. Format-free I/O is special features of
C++ which make I/O operation comfortable.
Note: The operator << and >> are the bit-wise left-shift and right-shift operators that are
used in C and C++. In C++ the operator can be overloaded i.e. same operator can perform
different activities depending on the context.
Manipulators:
Manipulators are instructions to the output stream that modify the output in various
ways. For example endl , setw etc.
The endl Manipulator:
The endl manipulator causes a linefeed to be inserted into the stream, so that
subsequent text is displayed on the next line. It has same effect as sending the „\n‟
character but somewhat different. It is a manipulator that sends a newline to the stream
5 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
and flushes the stream (puts out all pending characters that have been stored in the
internal stream buffer but not yet output). Unlike „\n‟ it also causes the output buffer to be
flushed but this happens invisibly.
e.g.
cout << endl<< "Perimeter is " << perimeter;
cout << endl << "Area is " << area << endl;
Manipulators come in two flavors: those that take and arguments and those that
don‟t take arguments. Followings are the some important non-argument manipulators .
Table: No-argument Manipulators
Manipulators Purpose
Ws Turn on whitespace skipping on input
Dec convert to decimal
Oct Convert to octal
Hex convert to Hexadecimal
Endl insert newling and flush the output stream
Ends Insert null character to terminate an output string
Flush flush the output stream
Lock lock the file handle
Unlock Unlock the file handle
//demonstrates manipulators
6 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
#include<iostream.h>
#include<iomanip.h>
void main()
{
long pop1=2425678;
cout<<setw(8)<<"LOCATION"<<setw(12)<< "POPULATION"<<endl
<<setw(8)<< "Patan"<<setw(12)<<hex<<pop1<<endl
<<setw(8)<< "Khotang" <<setw(12)<<oct<<pop1<<endl
<<setw(8)<< "Butwal" <<setw(12) <<dec<<pop1<<endl;
}
Output:
LOCATION POPULATION
Patan 25034e
Khotang 11201516
Butwal 2425678
There are manipulators that take arguments for example setw(), setfill() setprecision() etc
e.g.
cout<<setw(12)<<setfill(64)<<”string”;
In this statement setw(12) describes the field width 12 and setfill(64) fills the blanks with
character specified with integer arguments. The output of this statement is :
@@@@@@string where @ is the character corresponding to int 64
cout<<setprecision(5)<<12.456789;
The output of this statement is : 12.456 i.e. setprecision() describes the no of
digits to be displayed.
Data Types:
Variables
A variable is the name used for the quantities which are manipulated by a computer
program. i.e. it is a named storage location in memory. For example a program that reads
a series of numbers and sums them will have to have a variable to represent each number
as it is entered and a variable to represent the sum of the numbers.
In order to distinguish between different variables, they must be given identifiers, names
which distinguish them from all other variables. The rules of C++ for valid identifiers
state that:
An identifier must:
start with a letter
consist only of letters, the digits 0-9, or the underscore symbol _
not be a reserved word
For the purposes of C++ identifiers, the underscore symbol, _, is considered to be a letter.
Its use as the first character in an identifier is not recommended though, because many
library functions in C++ use such identifiers.
The following are valid identifiers
length days_in_year DataSet1 Profit95
Int _Pressure first_one first_1
7 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
Some of these reserved words may not be treated as reserved by older compilers.
However it is better to avoid their use. Other compilers may add their own reserved
words. Typical are those used by Borland compilers for the PC, which add near, far, huge,
cdecl, and pascal.
Declaration of variables
In C++ (as in many other programming languages) all the variables that a program is
going to use must be declared prior to use. Declaration of a variable serves two purposes:
It associates a type and an identifier (or name) with the variable. The type allows
the compiler to interpret statements correctly. For example in the CPU the
instruction to add two integer values together is different from the instruction to
8 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
add two floating-point values together. Hence the compiler must know the type of
the variables so it can generate the correct add instruction.
It allows the compiler to decide how much storage space to allocate for storage of
the value associated with the identifier and to assign an address for each variable
which can be used in code generation.
:: GloabalVariableName
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.
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.
getch();
}
Reference Variables:
C++ introduces a new kind of variable known as reference variable. A reference variable
provides an alias (Alternative name) of the variable that is previously defined. For
example, if we make the variable sum a reference to the variable total, the sum and total
can be used interchangeably to represent that variable.
9 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
Example:
int total=100 ;
int &sum=total;
Here total is int variable already declared. Sum is the alias for variable total. Both the
variable refer to the same data 100 in the memory.
cout<<total; and cout<<sum; gives the same output 100.
And total= total+100;
Cout<<sum; //gives output 200
void main()
{
int x=5;
int &y=x;
//y is alias of x
cout<<"x="<<x<<"and y="<<y<<endl;
y++;
//y is reference of x;
cout<<"x="<<x<<"and y="<<y<<endl;
getch();
}
Passing by reference
We can pass parameters in function in C++ by reference .When we pass
arguments by reference, the formal arguments in the called function become
aliases to the actual arguments in the calling function i.e. when function is
working with its own arguments , it is actually working on the original data.
Example
10 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
int main()
{
int x=100;
fun(x); //CALL
cout<<x; //prints 110
}
Return by reference
A function can return a value by reference. This is a unique feature of C++.
Normally function is invoked only on the right hand side of the equal sign. But we
can use it on the left side of equal sign and the value returned is put on the right
side.
//returning by reference from a function as a parameter
#include<iostream.h>
#include<conio.h>
int x=5,y=15;//globel variable
int &setx();
void main()
{
setx()=y;
11 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
Inline Function:
A inline function is a short-code function written and placed before main
function and compiled as inline code. The prototyping is not required for inline
function. It starts with keyword inline . In ordinary functions, when function is
invoked the control is passed to the calling function and after executing the
function the control is passed back to the calling program.
But , when inline function is called, the inline code of the function is
inserted at the place of call and compiled with the other source code together. That
is the main feature of inline function and different from the ordinary function. So
using inline function executing time is reduced because there is no transfer and
return back to control. But if function has long code inline function is not suitable
because it increases the length of source code due to inline compilation.
// Inline Function
//saves memory, the call to function cause the same code to be
//executed;the function need not be duplicated in memory
#include<iostream.h>
#include<conio.h>
inline float lbstokg(float pound)
{
return (0.453592*pound);
}
void main()
{
float lbs1=50,lbs2=100;
cout<<"Weinght in Kg:"<<lbstokg(lbs1)<<endl;
cout<<"Weinght in Kg:"<<lbstokg(lbs2)<<endl;
getch();
}
12 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
Default Arguments
In C++ a function can be called without specifying all its arguments. In
such cases, the function assigns a default value to the parameter which does not
have a matching argument in the function call. The default value are specified
when function is declared.
The default value is specified similar to the variable initialization . The
prototype for the declaration of default value of an argument looks like
float amount(float p, int time, float rate=0.10);
// declares a default value of 0.10 to the argument rate.
The call of this function as
value = amount(4000,5);// one argument missing for rate
passes the value 4000 to p , 5 to time and the function looks the prototype for
missing argument that is declared as default value 0.10 the the function uses the
default value 0.10 for the third argument. But the call
value = amount(4000,5,0.15);
no argument is missing , in this case function uses this value 0.15 for rate.
Note : only the trailing arguments can have default value. We must add default
from right to left. E.g.
int add( int a, int b =9, int c= 10 ); // legal
int add(int a=8, int b, int c); // illegal
int add(int a, int b = 9, int c); //illegal
int add( int a=8, int b=9,int c=10) // legal
13 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
Const Arguments
When arguments are passed by reference to the function, the function can
modify the variables in the calling program. Using the constant arguments in the
function , the variables in the calling program can not be modified. const qualifier
is used for it.
e.g.
void func(int&,const int&);
void main()
{
int a=10, b=20;
func(a,b);
}
void func(int& x, int &y)
{
x=100;
y=200; // error since y is constant argument
}
Function overloading
Overloading refers to the use of same thing for different purpose.
When same function name is used for different tasks this is known as function
overloading. Function overloading is one of the important feature of C++ and any
other OO languages.
When an overloaded function is called the function with matching
arguments and return type is invoked.
e.g.
void border(); //function with no arguments
void border(int ); // function with one int argument
void border(float); //function with one float argument
void border(int, float);// function with one int and one float arguments
For overloading a function prototype for each and the definition for each function
that share same name is compulsory.
//function overloading
//multiple function with same name
#include<iostream.h>
#include<conio.h>
int max(int ,int);
long max(long, long);
float max(float,float);
char max(char,char);
void main()
{
int i1=15,i2=20;
cout<<"Greater is "<<max(i1,i2)<<endl;
14 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
Structure review
An structure is an user defined data type which contains the collection of
different types of data under the same name. A structure is compared with records
in other languages.
Syntax:
struct tag-name
{
data-type var-name;
data-type var-name;
…………………..
} ; //end of structure
e.g. struct currency
{
int rs;
float ps;
};
15 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
void main()
{
currency c1,c3;
currency c2 ={123,56.4};
cout<<"Enter Rupees:"; cin>> c1.rupees;
cout<<"Enter paises"; cin>> c1. paise;
c3.paise = c1.paise+ c2.paise;
if(c3.paise>=100.0)
{
c3.paise-=100.0 ;
c3.rupees++;
}
c3.rupees+=c2.rupees+c1.rupees;
cout<<"Rs." <<c1.rupees<<" Ps. " <<c1.paise<<" + ";
cout<<"Rs." <<c2.rupees<<" Ps. "<<c2.paise<<" = ";
cout<< "Rs."<<c3.rupees<<" Ps."<<c3.paise<<endl;
}
16 -By HGC
OOP Downloaded from: http://www.bsccsit.com/ BSc.CSIT III
17 -By HGC