C++ Chapter2
C++ Chapter2
Typical c++ program would contain four sections as shown in figure below. These sections may be placed
in separate code files and then compiled independently or jointly.
Include Files
Class declaration
It is a common practice to organize a program into three separate files. The class declarations are placed
in 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 definition). Finally, the main program that uses the class is
placed in a third files as well as any other files required.
This approach is based on the concept of client-server model. 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.
The smallest individual units in a program are known as tokens. C++ has following tokens:
Keywords
Identifiers
Constants
Strings
Operators
A C++ program is written using these tokens, white spaces and the syntax of the language. Most of the
C++ tokens are basically similar to the C tokens with the exception of some additions and minor
modifications.
1
Data Type
Data types in C++ can be classified under various categories as shown in figure below:
Type Conversion
C++ permits explicit type conversion of variables or expression using the type cast operator. Traditional
C casts are augmented in C++ by a function-call notation as syntactic alternative. The following two
versions are equivalent:
Examples:
2
A type-name behaves as if it is a function for converting values to a designated type:
Eg: p = ( int * ) q;
Alternatively, we can use “ typedef “ to create an identifier of the required type and use it in the
functional notation.
P = int_pt(q);
const_cast
static_cast
dynamic_cast
reinterpret_cast
m = 5 + 2.75;
is a valid statement. Wherever data types are mixed in an expression, C++ performs the conversions
automatically. This process is known as implicit or automatic conversion.
Preprocessor Directives
Preprocessors are programs that process our source code before compilation. Preprocessor programs
provide preprocessors directives which tell the compiler to preprocess the source code before
compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates
that, whatever statement starts with #, is going to the preprocessor program, and preprocessor program
will execute this statement. Examples of some preprocessor directives are: #include, #define etc.
Remember that # symbol only provides a path that it will go to the preprocessor, and command such as
include is processed by preprocessor program. For example, include will include extra code to your
program.
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 directives, like
3
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++.
Manipulators are operators that are used to format the data display. The most commonly used
manipulators are endl and setw.
The endl manipulators, when used in an output statement, causes a linefeed to be inserted. It
has the same effect as using the newline character “\n”.
setw(5) specifies width 5 for printing the value of the variable sum. This value is right-justified within the
field as shown below:
3 4 5
Function Overloading
Overloading refers to the use of the same thing for different purposes. C++ also permits overloading of
functions. It means, we can use the same function name to create functions that perform a variety of
different tasks. This is known as function polymorphism in OOP.
Example:
#include <iostream>
using namespace std;
void print(int i)
{
cout << " \nThis is int " << i << endl;
}
void print(double f)
{
cout << " \nThis is float " << f << endl;
}
void print(char c)
4
{
cout << " \nThis is character " << c << endl;
}
int main()
{
print(10);
print(10.10);
print('t');
return 0;
}
Inline Function
To eliminate the cost of call of small function, C++ proposes a new feature called inline function
An inline function is expanded in a line when the function is called or invoked. i.e. the compiler
replaces the function call with the corresponding function code.
All inline function must be defined before they are called.
Syntax:
Function body
Some of the situation where inlined espressin may not work are;
For function returning value, if a loop ‘switch’ or ‘goto’ statement.
For the function not returning the value if a return statement exist
If the function consiss static variable
If the inline function are recursive
Default Argument
Argument is the data passed in the function. Default argument is useful in situation where some
argument have same value. For e.g. the bank interest for all customers is same.
5
Unlike C, C++ allows us to call a function without specifying all its arguments. IN such cases, the
function assigns a default value to the parameter which doesn’t has the matching argment in
the function call.
Default values are specified when the function is declared.
Example:
#include<iostream>
using namespace std;
class weight
{
float w;
public:
void process(float m, float g=9.8) //here g = 9.8 is used as default argument
{
w= m*g;
cout<<"weight="<<w;
}
};
int main()
{
weight ob;
ob.process(10,1.6);
return 0;
}
Call by Reference
Reference Variable
C++ introduces a new kind of variable known as the reference variable. A reference variable provides an
alias (alternative name) for a previously defined variable. Provision of reference variables in C++ permits
us to pass parameters to the functions by reference. We can pass arguments by reference, the ‘formal’
arguments in the called function become aliases to the ‘actual’ arguments in the calling function. This
means that when the function is working with its own arguments, it is actually working on the original
data.
6
void swap ( int &a, int &b)
{ Int t = a;
a = b;
b = t;
Here the function call swap( m, n) will exchange the values of m and n using their aliases a and b. In
traditional C, this is accomplished using pointers and indirection as follows:
{ Int t;
t = *a;
*a = *b;
*b = t;
int main()
{ int m = 10;
int n = 20;
cout<<"\nBefore swap "<<"m= "<<m<<"n= "<<n;
swap(m, n);
cout<<"\nAfter swap "<<"m= "<<m<<"n= "<<n;
return 0;
}
7
Example of reference Variable
#include<iostream>
using namespace std;
int main()
{
int m=5;
int &n=m;
cout<<"m="<<m<<" n="<<n<<endl;
n++;
//n is reference of m so m and n have now same value
cout<<"m="<<m<<" n="<<n<<endl;
}
Output
#include<iostream>
m++;
int main()
int a=100;
get(a);
8
Output:
Return by reference
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. The general form of a pointer variable declaration is
type *variable_name;
There are few important operations, which we will do with the pointers very frequently. a) We define a
pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the
address available in the pointer variable. This is done by using unary operator * that returns the value of
the variable located at the address specified by its operand.
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ptr_var; // pointer variable
9
cout << "Value of *ptr_var variable: ";
cout << *ptr_var << endl;
return 0;
}
10