3. Steps to write C++ Program in
Net Beans
First open "Net Beans"
Open file and Click on "New Project"
Select C/C++ From Catagories.
Select C/C++ Application From Projects.Then simply
click on Next
Name your Project and Give the Path
Click On Finish
Write the code in the Content Page.
Then Go the menu bar and Click on RUN and Click on
then run Project. www.opengurukul.com 3
4. Hello World program
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
www.opengurukul.com 4
5. Hello World program
// my first program in C++
- This is a comment line.
- All lines beginning with two slash signs (//) are
considered comments and do not have any effect on
the behavior of the program.
- The programmer can use them to include short
explanations or observations within the source code
itself.
www.opengurukul.com 5
6. Hello World program
#include <iostream>
- Hash sign (#) are directives for the
preprocessor.
- In this case the directive #include <iostream> tells
the preprocessor to include the iostream standard file.
- This specific file (iostream) includes the declarations
of the basic standard input-output library in C++.
www.opengurukul.com 6
7. Hello World program
using namespace std;
All the elements of the standard C++ library are
declared within what is called a namespace, the
namespace with the name std.
int main ()
The main function is the point by where all C++
programs start their execution, independently of its
location within the source code.
www.opengurukul.com 7
8. Hello World program
cout << "Hello World!";
- cout is the name of the standard output stream in C+
+,
- It will insert a sequence of characters (in this case
the Hello World sequence of characters) into the
standard output stream (cout, which usually
corresponds to the screen).
www.opengurukul.com 8
9. Hello World program
return 0;
- The return statement causes the main function to
finish.
- A return code of 0 for the main function is generally
interpreted as the program worked as expected
without any errors during its execution.
- This is the most usual way to end a C++ console
program.
www.opengurukul.com 9
10. Object Oriented Concepts
Encapsulation
Encapsulation is bundling together the attributes and
behaviours of an entity
Data toegether with operations that can manipulate it
are encapsulation into a Class.
Inheritance
A class (called derived-class) inherit the already well-
developed methods from another class (called base-
class); thereby saving lot of time and money.
www.opengurukul.com 10
11. Object Oriented Concepts
Polymorphism
polymorphisim is the ability of different objects to
respond in their own unique way to the same
message.
In C++, polymorphism can be of 3 types:
- sFunction overloading: Functions of a class with same
name but either different number of arguments or
different types of arguments.
- Operator Overloading: It gives new meaning for the
operands of a specific class.
- Dynamic/Late Binding: It works in case of inheritance
www.opengurukul.com 11
using the concept of virtual functions.
13. Conditional Statements
Conditional statements are used to perform different actions
based on different conditions.
In C++ we have the following conditional statements:
- if statement : use this statement to execute some code
only if a specified condition is true
- if...else statement : use this statement to execute some
code if a condition is true and another code if the condition
is false
- if...elseif....else statement : use this statement to select
one of several blocks of code to be executed
- switch statement : use this statement to select one of
many blocks of code to be executed
www.opengurukul.com 13
17. switch statement-Example
#include<iostream> Case 3: cout<<"Australia";
using namespace std; break;
int main() default: cout<<"Invalid option";
{ }
int option=3; return 0;
switch (option) }
{
case 1: cout<<"India"; Output :
break; Australia
case 2: cout<<"USA";
break;
www.opengurukul.com 17
18. Looping
A loop is simply a block of code that executes multiple times.
The following loops are available in C++
- while statement
- do while statement
- for statement
www.opengurukul.com 18
19. while loop
Statement or block of statements that is repeated as
long as some condition is satisfied.
Syntax :
while( boolean_expression )
{
statement1;
statement2;
...
}
www.opengurukul.com 19
20. while-loop Example
#include<iostream> return 0;
using namespace std; }
int main()
{ Output :
int x; Enter the Number
cout<<”Enter the Number”<<”n”; 5
cin>>x; 6789
while (x<10)
{
cout<<x;
x++;
} www.opengurukul.com 20
21. do-while-loop
Executed several times as long as the condition is satisfied.
The main difference between a while and do-while loop:
The statements inside a do-while loop are executed at least
once.
Syntax :
do
{
statement1;
...
}while( boolean_expression );
www.opengurukul.com 21
22. do-while-loop Example
#include<iostream> Output :
using namespace std; 0
int main() 1
{ 2
int x = 0; 3
do 4
{
cout<<x;
x++;
}while (x<5);
return 0;
} www.opengurukul.com 22
23. for loop
Allows execution of the same code a number of times.
Synatx :
for(InitializationExpression;Condition;StepExpression)
{
statement1;
statement2;
...
}
www.opengurukul.com 23
24. for-loop Example
#include<iostream> Output :
using namespace std; 0
int main(String[] arg) 1
{ 2
int i; 3
for( i = 0; i < 6; i++ ) 4
{ 5
cout<<i;
}
return 0;
}
www.opengurukul.com 24
25. Lab Exercises
1 Find the factorial of a no using for loop ?
2 Find greater between two numbers ?
3 How to find the factorial of a number using
while loop ?
www.opengurukul.com 25
27. Function
It is a group of statements that is executed when it is
called from some point of the program
Syntax: -
return_type function_name(parameter list)
{
body of the function
}
return_type is the data type specifier of the data returned
by the function. www.opengurukul.com 27
28. Function
function_name is the identifier by which it will be
possible to call the function.
Parameter list : Each parameter consists of a data type
specifier followed by an identifier, like any regular
variable declaration (for example: int x) and which acts
within the function as a regular local variable.
- They allow to pass arguments to the function when it is
called.
- The different parameters are separated by commas.
www.opengurukul.com 28
29. User-defined Functions
Functions those are defined by user according to user
requirements.
#include <iostream.h>
void skipthree() // Function to skip three lines
{
cout << endl << endl << endl;
}
www.opengurukul.com 29
30. Function Declaration:
It is made by declaring the return type of the function,
name of the function and the data types of the
parameters of the function.
The function declaration is always terminated by the
semicolon.
A call to the function cannot be made unless it is
declared.
Syntax :
return_type function_name(parameter list);
The variables in the function declaration can be optional
but data types are necessary.
www.opengurukul.com 30
31. Parameter passing mechanis:
pass by value
Copies of the arguments are created and which are
stored in the temporary locations of the memory.
The parameters are mapped to the copies of the
arguments created.
The changes made to the parameter do not affect the
arguments.
Pass by value mechanism provides security to the
calling program.
www.opengurukul.com 31
32. Pass by value:Example
#include<iostream> cout << " The result is : " << result
<< endl;
using namespace std;
return 0;
int add(int n);
}
int main()
{
int add(int number)
int number,result;
{
number=5;
number=number+100;
cout << " The initial value of
number : " << number << endl; return number;
result=add(number); }
cout << " The final value of
number : " << number << endl;
www.opengurukul.com 32
33. Pass by value:Example
Output:-
The initial value of number : 5
The final value of number : 5
The result is : 105
The value of the variable number before calling the function is 5.
The function call is made and function adds 100 to the
parameter number. When the function is returned the result
contains the added value. The final value of the number
remains same as 5.
This shows that operation on parameter does not produce effect
on arguments.
www.opengurukul.com 33
34. Pass by reference
The address of the argument is copied into the
parameter.
The changes made to the parameter affect the
arguments.
The address of the argument is passed to the function
and function modifies the values of the arguments in
the calling function.
www.opengurukul.com 34
35. Pass by reference:Example
#include<iostream> cout << "The value after the
function is returned : " <<
using namespace std;
number << endl;
int add(int *number);
cout << "Result : " << result <<
int main () endl;
{ return 0;
int number; }
int result; int add(int *p)
number=5; {
cout << "The value before *p=*p+100;
calling the function : " <<
return *p;
number << endl;
www.opengurukul.com 35
}
result=add(&number);
36. Pass by reference:Example
Output:-
The value before calling the function : 5
The value after the function is returned : 105
Result : 105
The address of the variable is passed to the function.
The variable p points to the memory address of the
variable number.
The value is incremented by 100. It changes the actual
contents of the variable number. The value of variable
number before calling the function is 100 and after the
function is returned the value of variable number is 36
www.opengurukul.com
changed to 105.
37. Function return values
When a function returns a value, the value is returned via a
return statement to the caller of the function.
Example :
int add(int i, int j)
{
return i + j; // return statement
}
int answer = add(10, 20); // answer is 30
In this example, the return statement initializes a variable of
the returned type. The variable
www.opengurukul.com 37
38. Lab Exercise
1. Write a program of function passing a two
values and subtract the two values in the
function.
2. Write a program of function showing with
return value.
www.opengurukul.com 38
40. Structures
The C++ Structures have some additional features then C.
It can have functions also as members.
It supports the concept of data hiding. The member of the
structures can be declared private so that they cannot be
accessed directly from outside.
A structure names can be treated as any other data type.
The keyword "struct" is not required. In C, it is mandatory
to have "struct" while declaring/defining.
By default members of structures are public.
www.opengurukul.com 40
41. Class and Object
The class is also like a structure.
The class is defined/declared by using keyword "class".
By default, members of class are private.
Object : It is an instance of a class.
www.opengurukul.com 41
42. Class and Object:Example
#include <iostream> int main()
using namespace std; {
class Employee { Employee ed;
private: ed.display();
int e_id; return 0;
int e_age; }
public: Output :
void display(){ e_id=0,e_age=0
cout << "e_id = " << e_id << ",
e_age = " << e_age
} www.opengurukul.com 42
43. Access Specifiers
The members of a class can be declared public, private
or protected.
The public members are accessible from anywhere
where the object is visible.
The private members of a class are accessible only from
within other members of the same class.
The protected embers are accessible from members of
their same class and also from members of their
derived classes.
www.opengurukul.com 43
44. Static Variables
It has only one copy per class. It is shared by all
the objects of the class.
Visiblity - within the class.
Lifetime - entire program.
www.opengurukul.com 44
45. Static Functions
A static function has access to only static
members (functions or variables).
A static member function can be called using
class name. It doesn't require object.
CLASS-NAME :: FUNCTION-NAME;
www.opengurukul.com 45
46. Static Example
#include <iostream> main()
class Test {
{ Test a, b;
static int count=0; a.increment();
public: Test :: display();
void increment() { count++; } b.increment();
static void display() { Test :: display();
cout << "Counter : " << count }
<< endl;
Output :
}
Counter :1
}; www.opengurukul.com 46
Counter :2
47. Constant Functions
If a member function does not alter any members
in the class, we can declare it as a "const".
To declare a class method constant, put the
keyword const after the parentheses but before
the semicolon.
Example : void SomeFunction() const;
The compiler will generate an error message if
such functions try to alter the data values.
www.opengurukul.com 47
48. Friends
A friend of a class X is a function or class that is
not a member of X, but is granted the same
access to X as the members of X.
Functions declared with the friend specifier in a
class member list are called friend functions of
that class.
Classes declared with the friend specifier in the
member list of another class are called friend
classes of that class
www.opengurukul.com 48
49. Friend Functions
A friend function is used for accessing the non-public
members of a class.
We can allow an external function access to the private and
protected members of the class by declaring it as a friend
to a class.
The keyword friend is placed only in the function declaration
of the friend function and not in the function definition.
It is possible to declare a function as friend in any number of
classes.
It can be declared in private or public part of the class.
www.opengurukul.com 49
50. Example: External friend function
include <iostream> return (t.a+t.b)/2;
class test }
{ void main()
int a; {
int b; test T;
public: T.set();
void set() {a=10; b=20;} cout << "Average : " <<
average(T) << endl;
friend int average(test t);
/*FRIEND function */ }
}; Output :
int average(test t) Average :15
www.opengurukul.com 50
{
51. Example : A function friendly to
two classes.
#include <iostream> void set(int i) { l = i;}
Class High friend int average(High, Low);
{ };
int h;
public: int average(High high, Low low)
void set(int i) { h = i;} {
friend int average(High, Low); return (high.h+low.l)/2 ;
}; }
Class Low
{
int l; www.opengurukul.com 51
public:
52. Example : A function friendly to
two classes.
void main() Output :
{ average :55
High high;
Low low;
high.set(100);
low.set(10);
cout << "average : " <<
average(high, low) << endl;
}
www.opengurukul.com 52
53. Example: friend function member
of another class
If the friend function is a member of another class, you
need to use the scope resolution operator (::).
For example:
class A { public: int f() { } };
class B { friend int A::f(); };
www.opengurukul.com 53
54. Friend Classes
You can declare an entire class as a friend.
Suppose class F is a friend of class X.
This means that every member function and
static data member definition of class F has
access to class X.
www.opengurukul.com 54
55. Example: Friend Class
#include <iostream> cout << "b is " << x.b << endl;
using namespace std; }
class X { };
int a, b; int main() {
friend class F; X xobj;
public: F fobj;
X() : a(1), b(2) { } fobj.print(xobj);
}; }
class F { Output :
public: a is 1 b is 2
void print(X& x) { www.opengurukul.com 55
cout << "a is " << x.a << endl;
57. Constructors
Every time an instance of a class is created the
constructor is called.
The constructor has the same name as the class and it
doesn't return any type, while the destructor's name
it's defined in the same way, but with a '~' in front:
A constructor is a special member function of the class
that is used to initialize the objects of a class.
Should be declared in public section
When constructor is declared for a class, it is mandatory
to initialize it.
www.opengurukul.com 57
58. Default Constructor
This constructor has no arguments in it.
Default Constructor is also called as no argument
constructor.
Even if a class is not equipped with a constructor,
the compiler will generate code for one, called
the implicit default constructor.
The implicit default constructor is a one with no
arguments and empty body.
www.opengurukul.com 58
59. Default Constructor:Example
#include <iostream> Test :: Test()
using namespace std; {
class Test a=10;
{ }
private: main()
int a; {
Test(); // declaration of default Test t;
constructor
t.print();
print() {
}
cout<< "a = "<< a <<endl;
Output :
}
a =10
www.opengurukul.com 59
};
60. Parametrized Constructor
In such a constructor, argument are passed to
constructor for initialization purpose
www.opengurukul.com 60
61. Copy Constructor
This constructor takes one argument. Also called one
argument constructor.
The main use of copy constructor is to initialize the
objects while in creation, also used to copy an object.
The copy constructor allows the programmer to create a
new object from an existing one by initialization.
For example to invoke a copy constructor the
programmer writes:
Test t2(t1);
or
Test t2 = t1; www.opengurukul.com 61
62. Copy Constructor:Example
#include <iostream> Test(Test & t) // copy constructor
using namespace std; {
class Test a = t.a;
{ }
private: print() { cout<< "a = "<< a
<<endl; }
int a;
};
public:
void main()
Test() {} // default constructor
{
Test(int arg) {a = arg;} //
parameterized constructor Test t1(2); // initialize a to 2
www.opengurukul.com 62
63. Copy Constructor:Example
Test t2(t1); // copy t2 from t1 using Output :
copy constructor
a=10
Test t3=t2; // copy t3 from t2 using
copy constructor
Test t4;
t4 = t3; // this uses overloaded
assignment operator
t4.print();
}
www.opengurukul.com 63
64. Shallow Copy & Deep Copy
If there is no copy constructor defined for the class, C++
uses the default copy constructor which copies each
field.
The terms "deep copy" and "shallow copy" refer to the
way objects are copied.
For example, during the invocation of a copy constructor
or assignment operator.
In a deep copy (also called "memberwise copy"), the
copy operation respects object semantics.
www.opengurukul.com 64
65. Shallow Copy & Deep Copy
For example, copying an object that has a member of
type std::string ensures that the corresponding
std::string in the target object is copy-constructed by
the copy constructor of class std::string.
class A
{
string s;
};
A a;
A b;
www.opengurukul.com 65
a=b; //deep copy
66. Shallow Copy & Deep Copy
When assigning b to a, the compiler-generated
assignment operator of class A first invokes the
assignment operator of class std::string.
Thus, a.s and b.s are well-defined, and they are
probably not binary-identical.
a shallow copy (also called "bitwise copy") simply copies
chunks of memory from one location to another.
A memcpy() operation is an example of a shallow copy.
Because will not invoke the copy constructor of an
object.
Therefore, you should never use memcpy() to copy
objects. www.opengurukul.com 66
67. Destructors
They are used to destroy the objects.
The main use of destructors is to release dynamic
allocated memory and perform cleanup.
Destructors are automatically called when an object is
destroyed.
A destructor takes no arguments and has no return type.
Its address cannot be taken.
Destructors also take the same name as that of the
class name but it is preceded by tilde.
~ classname();
www.opengurukul.com 67
68. Destructors
Example :
class X {
public:
// Constructor for class X
X();
// Destructor for class X
~X();
};
www.opengurukul.com 68
70. Inheritance
An inheritance type can be public, protected, private.
class D: inheritance_type class B {
};
For public inheritance, nothing changes.
For protected inheritance, public members becomes
protected in Derived Class.
For private inheritance, public & protected members
becomes privated in Derived Class.
www.opengurukul.com 70
71. Inheritance :Example
#include <iostream> class D : public B {
using namespace std; public :
class B { void setb() {
private: b_protected = 10;
int b_private; b_public = 10;
protected: }
int b_protected; void getb() {
public: cout << " b_protected = " <<
b_protected << endl;
int b_public;
cout << " b_public = " << b_public
}; << endl;
}
www.opengurukul.com 71
73. Virtual Inheritance - Multiple
Inheritance
Virtual inheritance is a kind of inheritance in which the
part of the object that belongs to the virtual base class
becomes common direct base for the derived class
and any next class that derives from it.
In other words, if we have a class V that is virtually
derived by class A, and then we have a class B that
derives A (directly), then V becomes a direct base
class of class B and any other class that derives A
(even indirectly).
This is most useful for multiple inheritance, as it causes
that subobject of the virtual base will be always a
common subobject for all classes that are derived in
the deriving class (as well as this class itself).
www.opengurukul.com 73
74. Multiple Inheritance:Example
Let us consider a situation-there is a base class A and two
derived class B and C of A.And again we also have
another class D that inherits from B and C. Here D inherits
the traits of A via two different ways B and C.
The class A is sometimes referred to as indirect base class.
So all the public and private members of the base class A
are inherited into derived class D two times first from Base
class B and again from base class C. This leads to
ambiguity and is better to avoid.
To avoid this ambiguity, we must declare the base class A as
virtual base class while declaring the direct or intermediate
base classes.
www.opengurukul.com 74
75. Multiple Inheritance:Example
class A class C : virtual public A
{ {
// code for the class A // code for the class C
} }
class B : virtual public A class D : public C, public B
{ {
// code for the class B // code for the class D
} }
www.opengurukul.com 75
76. Static Function & Inheritance
#include <iostream> class SomeDerivedClass: public
SomeClass
using namespace std;
{
class SomeClass
public:
{
SomeDerivedClass(){
public:
cout << "SomeDerivedClas " <<
static int total; endl;
SomeClass(){ total++;
cout << "SomeClass" << endl; }
total++; };
} int SomeClass::total;
}; www.opengurukul.com 76
79. 'this' Pointer
It is available to non-static member functions.
It is an address of the object handle that has
invoked the method.
www.opengurukul.com 79
80. Pointers
It is a variable that stores a memory address.
The address of operator or Reference operator is
denoted by the notation &.
The declaration of a pointer variable is as follows:-
datatype * pointer_variable;
- datatype is the valid data type of C++
- pointer_variable is the name of the pointer.
- The character * tells the compiler that this variable is a
pointer variable.
www.opengurukul.com 80
81. pointers to objects:Example
#include <iostream> void display()
using namespace std; {
class B { cout << " b = " << this->b << endl;
int b; }
public : };
B() {}
B(int b) { this->b = b;} int main()
void setb(int b) {
{ B b_obj(5);
this->b = b; b_obj.display();
} //B *b_ptr;
www.opengurukul.com 81
82. pointers to objects:Example
/b_ptr = &b_obj; Output :
B *b_ptr = &b_obj; b =5
b_ptr->setb(10); b =10
b_ptr->display();
return 0;
}
www.opengurukul.com 82
83. Virtual Function
It is a member function of a base class which is used to
over-ridden in the derievd class.
The function name and signature of the base function is
same as that of the derived class.
To use the same function name in both the base class
and derived class, we must declare virtual by using the
keyword "virtual" to function of the base class and
pointer to the base class is used to access the virtual
function.
www.opengurukul.com 83
84. Virtual Function:Example
#include <iostream> class D : public B {
using namespace std; public :
class B { void print_normal() {
public : cout << "D::print_normal" << endl;
void print_normal() { }
cout << "B::print_normal" << endl; /*
} void print_virtual() {
virtual void print_virtual() { cout << "D::print_virtual" << endl;
cout << "B::print_virtual" << endl; }
} */
}; };
www.opengurukul.com 84
85. Virtual Function : Example ...
Int main() b_ptr->print_normal();
{ b_ptr->print_virtual();
B b; b_ptr = &d;
D d; b_ptr->print_normal(); //*
Exception
b.print_normal();
b_ptr->print_virtual();
b.print_virtual();
return 0;
d.print_normal();
}
d.print_virtual();
B *b_ptr;
b_ptr = &b;
www.opengurukul.com 85
86. Pure Virtual Function & Abstract
Class
This is a function with empty function body.
The pure virtual function must be overridden to the
derived class.
The class which has pure virtual function cannot be used
to create an object of its own. Such class is known as
abstract class.
If a derived class also doesn't implement the pure virtual
function, then you cannot create an object of a derived
object also.
www.opengurukul.com 86
87. Example
#include <iostream> }
using namespace std; };
class B int main()
{ {
public: D d;
virtual void display() = 0; B *b_ptr = &d;
}; b_ptr->display();
class D: public B return 0;
{ }
void display() {
cout << " Hello d" << endl; www.opengurukul.com 87
89. getline():
Used to read the whole line of text that ends with a
newline character.
cin object can invoke this function as
cin.getline(char line[],length);
- getline() function is invoked for reading character input
into the variable line.
- When we type /n, the reading is terminated or size-1
characters are read.
- The newline is accepted but converted to null
character.
www.opengurukul.com 89
90. getline(): Example
main() Output :
{ City Name :Bangalore
char city[50]; City Name :Bangalore
cout << "City Name : ";
// cin >> city ;
cin.getline(city, 50);
cout << "City Name : " << city
<< endl;
}
www.opengurukul.com 90
91. width():
It determines the minimum number of characters to be
written in some output representations.
width() is a member function, it must be invoked with a
cout object.
The output of using width() is right justified.
eg cout.width(10);
cout<<231;
The output prints the number 231 within a field whose
width is set to 10.
www.opengurukul.com 91
92. precision():
Floating point numbers are printed with six digits after
the decimal point.
Number of the decimal points can be specified by using
a function know as precision().
This function is called by an object cout as
cout.precision(no);
- no is the number of digits to the right of the decimal
point.
eg.
cout.precision(2);
www.opengurukul.com 92
cout<<5.43564; output: 5.43.
93. fill():
when we use width() the cout fills the empty field with
spaces.
if we want to fill the area with other characters, such as
asterisks(*) or some other character.
we can use fill() and pass a parameter which we want
used as a fill character.
Syntax:
cout.fill(character);
www.opengurukul.com 93
95. get():
Used to get a character from a keyboard by using cin
class.
It is also a member of istream class.
There are two types of get() and get(char *).
get() simply gets a character from keyboard and
assigned to an argument.
get(char *) gets a character from a keyboard and
assigned to the character argument passing through it.
syntax for get():
char c;
www.opengurukul.com 95
c=cin.get();
97. put():
Used to display a character at a time.
It is a member of ostram class.
syntax:
cout.put('a');
or
char c;
cout.put(c);
www.opengurukul.com 97
98. get() and put() :Example
#include <iostream> Output :
using namespace std; Input a character :a
main() a
{
char c;
cout << "Input a character : " ;
cin.get(c);
cout.put(c);
cout << endl;
}
www.opengurukul.com 98
99. Manipulators
Used to manipulate the output formats.
Having same feature as that of ios member of
setf().
We can use more than one manipulators at a
time as
cout<< manipulator 1 << manipulator 2 <<
manipulator 3 << parameter;
There are lots of Manipulators for c++.
Some of them are as follows :
www.opengurukul.com 99
100. Manipulators
setw(int w)
- It sets the field width to w.
eg.
cout << setw(5) << 55;
- This program code prints the value 55 right
justified in a field width of 5.
www.opengurukul.com 100
101. Manipulators
endl
This manipulator has the same functionality as
the ‘n’ newline character.
eg.
cout << "Matsya Technoloy" << endl;
cout << "Hello world";
- output:
Matsya Technology
Hello wold www.opengurukul.com 101
102. Manipulators
setfill ( char c):
- setw manipulator is used before setfill.
- If a value does not entirely fill a field, then the
character specified in the setfill argument of
the manipulator is used for filling the fields.
eg .
cout<<width(5) << setfill ( ' * ' ) << 34;
- output :
***34 www.opengurukul.com 102
105. File Open & Close
Open :
fstream class
fstream is a standard C++ library that handles reading
from and writing to files either in text or in binary
formats.
Header file – fstream.h
Use class ofstream to create output stream object.
Use class ifstream to create input stream object.
www.opengurukul.com 105
107. File Open & Close
Close :
close() function
close() is used with file streams.
It closes current stream.
void close();
Close a file
file-stream-class file-stream-object;
file-stream-object.open(“filename”, mode);
file-stream-object.close();
www.opengurukul.com 107
108. File Open & Close Example
The following example creates a file called 'file.txt' and puts
the text 'Hello World' followed by a newline into it.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("file.txt");
file << "Hello world!n";
file.close();
www.opengurukul.com 108
return 0; }
109. File Positioning
Input & Output Streams can be manipulated
independently.
Each file has two pointers associated with it called get
pointer(read pointer) & put pointer (write pointer)
Get Pointer
is used for input (read) operations.
Put Pointer
is used for output (write) operations.
www.opengurukul.com 109
110. File Positioning : Input
Input File Streams (ifstream)
seekg()
-Set position of get pointer.
-istream & seekg ( streampos pos );
A new position
-istream & seekg ( streamoff off, ios_base::seekdir dir );
An offset relative to direction
tellg()
-Get position of the get pointer
-streampos tellg( ); www.opengurukul.com 110
111. File Positioning : Output
Output File Streams (ofstream)
seekp()
-Set position of put pointer.
-ostream & seekp ( streampos pos );
A new position
-ostream & seekp ( streamoff off, ios_base::seekdir dir );
An offset relative to direction.
tellp()
-Get position of the put pointer
-streampos tellp( ); www.opengurukul.com 111
112. SEEKP/TELLP Example
It shows one use of the output ofstream::pos_type p =
file positioning functions, ofs.tellp();
tellp() & seekp().
ofs << "Filesn";
ofs.seekp(p);
#include <fstream>
ofs << "Worldn";
using namespace std;
ofs.close();
main()
}
{
ofstream
ofs("files_tellp_seekp.out");
ofs << "Hello ";
www.opengurukul.com 112
113. PUT & GET Function
put()
-Writes a single character to the stream.
-ostream & put ( char c );
get()
-Reads a single character from the stream
-int get();
-istream & get ( char & c );
-istream & get ( char* s, streamsize n ); // getline()
www.opengurukul.com 113
114. PUT & GET Function:Example
Following example writes to a file do {
anything typed by user until '!' is
typed. c = cin.get();
ofs.put (c);
#include <iostream> } while (c != '!');
#include <fstream> ofs.close();
using namespace std; return 0;
int main () { }
char c;
ofstream ofs("files_put_get.txt");
www.opengurukul.com 114
115. getline()
Reads a line from the stream.
It is useful to read string that contain spaces.
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char
delim );
www.opengurukul.com 115
116. getline():Exmaple
#include <iostream> cout << "Enter your full name
again : ";
using namespace std;
cin >> name;
cout << "Your first name is : " <<
int main () { name << endl;
char name[1024]; return 0;
cout << "Enter your full name :"; }
cin.getline(name, 1024); Output :
cout << "Your full name is : " << Enter yiur full name :matsya
name << endl;
Your full name is : matsya
Enter your full name again :
matsya
www.opengurukul.com 116
Your first name is : matsya
117. gcount()
Used with input streams, and returns the number
of characters read by the last unformatted input
operation.
Functions such as peek, putback and unget do
not extract characters.
So gcount will always return zero after a call to
any of these.
www.opengurukul.com 117
118. gcount() :Example
#include <iostream> Output :
using namespace std; Enter your full name :Matsya
You have typed 6 chars
int main () {
char name[1024];
cout << "Enter your full name :";
cin.getline(name, 1024);
cout << "You have typed "
<< cin.gcount() - 1<< " charsn";
return 0; www.opengurukul.com 118
}
119. peek()
int peek ( );
- Peek next character
- Reads and returns the next character without
extracting it, i.e. leaving it as the next character
to be extracted from the stream.
www.opengurukul.com 119
120. File Read & Write
Read & Write function are similar to C “Language”.
They are associated with a stream in C++.
read()
istream& read ( char* s, streamsize n );
write()
ostream& write ( char* s, streamsize n );
www.opengurukul.com 120
121. Read & write Example
#include <fstream> ifstream ifs("marks.txt");
#include <iostream> ifs.read((char *)&marks,
sizeof(marks));
using namespace std;
ifs.close();
main() {
for (int i = 0; i < 5; i++) { cout <<
int marks[5] = {10, 20, 30, 40, 50}; "marks[" << i <<"] = " <<
ofstream ofs("marks.txt"); marks[i] << endl; }
ofs.write((char *)&marks, }
sizeof(marks));
ofs.close();
for (int i = 0; i < 5; i++) {
marks[i] = 0;
www.opengurukul.com 121
}
124. Template function
Functions which uses template for handling different
data types without separate code for each of them.
For similar operation on several kinds of data types,it is
not possible to write different version of by overloading
a function.
Without the function overloading, we can get the goal by
using function templates.
www.opengurukul.com 124
125. Template Function - Example:
#include <iostream> template <class type1, class
type2>
using namespace std;
type1 subtract(type1 in1, type2
template <class type> in2)
type add(type in1, type in2) {
{ type1 local;
type local; local = in1 - in2;
local = in1 + in2; return local;
return local; }
}
www.opengurukul.com 125
127. Template Class
A class created from a class template is called a
template class.
Actually the class template is used where multiple
copies of the code are there in the class with the same
logic.
Syntax :
template<class A>
class example
{
// code for the class
www.opengurukul.com 127
}
128. Template Class - Example
#include <iostream> number() { n1 = 2; n2 = 3;}
using namespace std; number(type t1, type t2) { n1 = t1;
n2 = t2;}
template <class type>
type add(void);
class number
void display(void) {
{
cout << n1 << " " << n2;
type n1;
cout << endl;
type n2;
}
public:
};
// this doesn't work - has some
garbage values
//number(type n1, type n2) { n1 =
n1; n2 = n2;} www.opengurukul.com 128
129. Template Class - Example
template <class type> cout << N.add();
type number<type> :: add() cout << endl;
{ }
return n1+n2;
}
main()
{
//class number<int> N;
class number<int> N(5,15);
N.display(); www.opengurukul.com 129
131. Inroduction
Standard Template Library is a C++ library of container
classes, algorithms and iterators.
STL is a generic library which provides many algorithms
and Data Structures used in Computer programming.
Almost every component in STL is a Template
STL contains many container classes, which contain the
other objects.
Examples: vector, list, deque, etc.
Each of these are template classes and can be
instantiated to contain any kind of objects.
www.opengurukul.com 131
132. Inroduction
In STL there are three foundational items namely
containers, algorithms and iterators.
Containers :
- objects that hold other objects and there are several
different types.
- Sequence container for example vector, list, queues ...
etc.
- Associative containers which allow efficient retrieval of
values based on keys.
- Each container class defines a set of functions that
may be applied to the container.
www.opengurukul.com 132
133. Inroduction
- For example, a list container includes functions that
insert, delete and merge elements.
- A stack includes functions that push and pop values.
Algorithms :
– Algorithms act on containers.
– They provide the means by which you will manipulate
the contents of containers including initialization,
sorting, searching and transforming the contents of the
containers.
www.opengurukul.com 133
134. Inroduction
Iterators :
– are objects that act more or less like pointers.
– They give you the ability to cycle through the contents
of a container in much the same way that you would
use a pointer to cycle through an array.
– You can increment and decrement iterators.
– The STL also supports reverse iterators. Reverse
iterators are either bidirectional or random-access
iterators.
www.opengurukul.com 134
135. Vector Class
It is a Sequence that supports random access to
elements, constant time insertion and removal of
elements at the end, and linear time insertion and
removal of elements at the beginning or in the middle.
The number of elements in a vector may vary
dynamically
Memory management is automatic.
Vector is the simplest of the STL container classes, and
in many cases the most efficient.
www.opengurukul.com 135
136. Vector Class:Example
#include <iostream> // print all elements followed by a
space
#include <vector>
for (int i=0; i<coll.size(); ++i) {
using namespace std;
cout << coll[i] << ' ';
int main()
}
{
cout << endl;
vector<int> coll; //vector
container for integer element }
// append elements with values 1
to 6
Output :
for (int i=1; i<=6; ++i) {
123456
coll.push_back(i);
} www.opengurukul.com 136
137. List Class
It is a doubly linked list.
That is, it is a Sequence that supports both forward and
backward traversal, and (amortized) constant time
insertion and removal of elements at the beginning or
the end, or in the middle.
Lists have the important property that insertion and
splicing do not invalidate iterators to list elements, and
that even removal invalidates only the iterators that
point to the elements that are removed.
www.opengurukul.com 137
138. List Class:Example
#include <iostream> /* print all elements
#include <list> * - while there are elements
using namespace std; * - print and remove the first
element */
int main()
while (! coll.empty()) {
{
cout << coll.front() << ' ';
list<char> coll; // list container for
character elements coll.pop_front();
// append elements from 'a' to 'z' }
for (char c='a'; c<='z'; ++c) { cout << endl;
coll.push_back(c); }
} Output :
www.opengurukul.com 138
a b c d ........ z
139. Map Class
It is a Sorted Associative Container that associates
objects of type Key with objects of type Data.
Map is a Pair Associative Container, meaning that its
value type is pair<const Key, Data>.
It is also a Unique Associative Container, meaning that
no two elements have the same key.
Map has the important property that inserting a new
element into a map does not invalidate iterators that
point to existing elements.
Erasing an element from a map also does not invalidate
any iterators, except, of course, for iterators that
actually point to the element that is being erased.
www.opengurukul.com 139
140. Map Class:Example
#include <iostream> coll["Pi"] = 3.1415;
#include <map> coll["an arbitrary number"] =
4983.223;
#include <string>
coll["Null"] = 0;
using namespace std;
int main()
/* print all elements
{
* - iterate over all elements
typedef map<string,float>
* - element member first is the key
StringFloatMap;
* - element member second is the
StringFloatMap coll; value
// insert some elements into the */
collection
StringFloatMap::iterator
www.opengurukul.com pos; 140
coll["VAT"] = 0.15;
142. Set Class
It is a Sorted Associative Container that stores objects of
type Key.
Set is a Simple Associative Container, meaning that its
value type, as well as its key type, is Key.
It is also a Unique Associative Container, meaning that
no two elements are the same.
www.opengurukul.com 142
143. Set Class:Example
#include <iostream> coll.insert(5);
#include <set> coll.insert(4);
int main() coll.insert(1);
{ coll.insert(6);
typedef std::set<int> IntSet; coll.insert(2);
IntSet coll; // set container for int
values
/* print all elements
/* insert elements from 1 to 6 in
arbitrary order * - iterate over all elements
* - value 1 gets inserted twice */ */
coll.insert(3); IntSet::const_iterator pos;
coll.insert(1); www.opengurukul.com 143
146. How Namespace comes
Motivation :
Consider you purchase two third-party headers namely
<vendor1.h> & <vendor2.h> for different purposes.
Consider both the header files contain class with the name
String but with different implementation.
If you include both the headers in an application, there will be
two classes with the same name String. Hence there will
be a name clash.
So Compiler will throw an error. Even if you resolve this
error, you will be ending up with using only one header file.
So, now How to include both the header files and make use
of both the String classes?
www.opengurukul.com 146
147. Namespace-Solution
// vendor1.h // vendor2.h
namespace vendor1 { namespacevendor2 {
... Some code ... ... Some code ...
class String { class String {
... ...
}; };
} }
www.opengurukul.com 147
149. Namespace-Definition
A namespace is a named area of scope in which
all identifiers created by programmer are
guaranteed to be unique .
The identifiers in a namespace may represent
variable names, constant names, function
names,structure names, class names or other
namespace.
A namespace can be defined either at the global
level or within another namespace using(nested
namespaces).
www.opengurukul.com 149
150. The Std Namespace
The standard C++ library defines it’s entire library in it’s
own namespace called std.
The std namespace has to be included in the beginning
of a program as using namespace std;
This causes the std namespace to be brought into the
current namespace.
The namespace std contains all the function and the
classes defined in any of these libraries.
If you don’t declare using namespace std; at the
beginning of the program, then you must use standard
objects as given below:
www.opengurukul.com 150
std :: cout<<“hello, this is a sample”;