OpenGurukul : Language : C++ Programming


Published on

C++ Programming By OpenGurukul

Published in: Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

OpenGurukul : Language : C++ Programming

  1. 1. C++ By OpenGurukul.comFree/Open Source Software Laboratory
  2. 2. C++Beginning with C++ 2
  3. 3. Steps to write C++ Program in Net BeansFirst open "Net Beans"Open file and Click on "New Project"Select C/C++ From Catagories.Select C/C++ Application From Projects.Then simplyclick on NextName your Project and Give the PathClick On FinishWrite the code in the Content Page.Then Go the menu bar and Click on RUN and Click onthen run Project. 3
  4. 4. Hello World program// my first program in C++#include <iostream>using namespace std;int main (){cout << "Hello World!";return 0;} 4
  5. 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. 5
  6. 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++. 6
  7. 7. Hello World programusing namespace std; All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name main () The main function is the point by where all C++ programs start their execution, independently of its location within the source code. 7
  8. 8. Hello World programcout << "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). 8
  9. 9. Hello World programreturn 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. 9
  10. 10. Object Oriented ConceptsEncapsulation 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. 10
  11. 11. Object Oriented ConceptsPolymorphism 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 11 using the concept of virtual functions.
  12. 12. C++Control Structures 12
  13. 13. Conditional StatementsConditional 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 13
  14. 14. if and elseSyntax :if( boolean_expression ) else{ {statement1; statement3;statement2; statement4;... ...} } 14
  15. 15. If and else-Example#include<iostream> elseusing namespace std; {int main() cout<<"Sorry you failed";{ }int grade = 58; return 0;if( grade > 60 ) }{cout<<”Congratulations!"; Output :cout<<"You passed!"; Sorry you failed} 15
  16. 16. switch StatementSyntax :switch( switch_expression ){ default:case case_selector1: statement1;// statement1;// } break;case case_selector2: statement1;// break; 16
  17. 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; Australiacase 2: cout<<"USA";break; 17
  18. 18. LoopingA 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 18
  19. 19. while loopStatement or block of statements that is repeated as long as some condition is satisfied.Syntax :while( boolean_expression ){statement1;statement2;...} 19
  20. 20. while-loop Example#include<iostream> return 0;using namespace std; }int main(){ Output :int x; Enter the Numbercout<<”Enter the Number”<<”n”; 5cin>>x; 6789while (x<10) { cout<<x; x++; } 20
  21. 21. do-while-loopExecuted 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 ); 21
  22. 22. do-while-loop Example#include<iostream> Output :using namespace std; 0int main() 1{ 2int x = 0; 3do 4 { cout<<x; x++; }while (x<5);return 0;} 22
  23. 23. for loopAllows execution of the same code a number of times.Synatx :for(InitializationExpression;Condition;StepExpression){statement1;statement2;...} 23
  24. 24. for-loop Example#include<iostream> Output :using namespace std; 0int main(String[] arg) 1{ 2int i; 3for( i = 0; i < 6; i++ ) 4{ 5cout<<i;}return 0;} 24
  25. 25. Lab Exercises1 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 ? 25
  26. 26. 26
  27. 27. FunctionIt is a group of statements that is executed when it is called from some point of the programSyntax: -return_type function_name(parameter list){body of the function}return_type is the data type specifier of the data returned by the function. 27
  28. 28. Functionfunction_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. 28
  29. 29. User-defined FunctionsFunctions those are defined by user according to user requirements.#include <iostream.h>void skipthree() // Function to skip three lines{cout << endl << endl << endl;} 29
  30. 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. 30
  31. 31. Parameter passing mechanis: pass by valueCopies 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. 31
  32. 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; 32
  33. 33. Pass by value:ExampleOutput:-The initial value of number : 5The final value of number : 5The result is : 105The 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. 33
  34. 34. Pass by referenceThe 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. 34
  35. 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; 35 }result=add(&number);
  36. 36. Pass by reference:ExampleOutput:-The value before calling the function : 5The value after the function is returned : 105Result : 105The 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 changed to 105.
  37. 37. Function return valuesWhen 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 30In this example, the return statement initializes a variable of the returned type. The variable 37
  38. 38. Lab Exercise1. 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. 38
  39. 39. C++Classes & Objects 39
  40. 40. StructuresThe 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. 40
  41. 41. Class and ObjectThe 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. 41
  42. 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=0cout << "e_id = " << e_id << ", e_age = " << e_age} 42
  43. 43. Access SpecifiersThe 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. 43
  44. 44. Static VariablesIt has only one copy per class. It is shared by all the objects of the class.Visiblity - within the class.Lifetime - entire program. 44
  45. 45. Static FunctionsA static function has access to only static members (functions or variables).A static member function can be called using class name. It doesnt require object.CLASS-NAME :: FUNCTION-NAME; 45
  46. 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}; 46 Counter :2
  47. 47. Constant FunctionsIf 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. 47
  48. 48. FriendsA 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 48
  49. 49. Friend FunctionsA 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. 49
  50. 50. Example: External friend functioninclude <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 50{
  51. 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; 51public:
  52. 52. Example : A function friendly to two classes.void main() Output :{ average :55High high;Low low;high.set(100);low.set(10);cout << "average : " << average(high, low) << endl;} 52
  53. 53. Example: friend function member of another classIf 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(); }; 53
  54. 54. Friend ClassesYou 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. 54
  55. 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 2void print(X& x) { 55cout << "a is " << x.a << endl;
  56. 56. C++Constructors & Destructors 56
  57. 57. ConstructorsEvery time an instance of a class is created the constructor is called.The constructor has the same name as the class and it doesnt return any type, while the destructors name its 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 sectionWhen constructor is declared for a class, it is mandatory to initialize it. 57
  58. 58. Default ConstructorThis 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. 58
  59. 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 59};
  60. 60. Parametrized ConstructorIn such a constructor, argument are passed to constructor for initialization purpose 60
  61. 61. Copy ConstructorThis 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);orTest t2 = t1; 61
  62. 62. Copy Constructor:Example#include <iostream> Test(Test & t) // copy constructorusing 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 62
  63. 63. Copy Constructor:ExampleTest t2(t1); // copy t2 from t1 using Output : copy constructor a=10Test t3=t2; // copy t3 from t2 using copy constructorTest t4;t4 = t3; // this uses overloaded assignment operatort4.print();} 63
  64. 64. Shallow Copy & Deep CopyIf 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. 64
  65. 65. Shallow Copy & Deep CopyFor 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; 65a=b; //deep copy
  66. 66. Shallow Copy & Deep CopyWhen 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. 66
  67. 67. DestructorsThey 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(); 67
  68. 68. DestructorsExample :class X {public:// Constructor for class XX();// Destructor for class X~X();}; 68
  69. 69. 69
  70. 70. InheritanceAn 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. 70
  71. 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; } 71
  72. 72. Inheritance :Examplevoid main() Output :{ b_protected =10D d_obj; b_public =20d_obj.setb();//d_obj.b_protected = 20;d_obj.b_public = 20;d_obj.getb();} 72
  73. 73. Virtual Inheritance - Multiple InheritanceVirtual 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). 73
  74. 74. Multiple Inheritance:ExampleLet 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. 74
  75. 75. Multiple Inheritance:Exampleclass 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} } 75
  76. 76. Static Function & Inheritance#include <iostream> class SomeDerivedClass: public SomeClassusing namespace std; {class SomeClass public:{ SomeDerivedClass(){public: cout << "SomeDerivedClas " <<static int total; endl;SomeClass(){ total++;cout << "SomeClass" << endl; }total++; };} int SomeClass::total;}; 76
  77. 77. Static Function & Inheritanceint main(){SomeClass A;SomeClass B;SomeDerivedClass C;cout << SomeClass::total << endl;return 0;} 77
  78. 78. C++Pointers, Virtual Functions 78
  79. 79. this PointerIt is available to non-static member functions.It is an address of the object handle that has invoked the method. 79
  80. 80. PointersIt 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. 80
  81. 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; 81
  82. 82. pointers to objects:Example/b_ptr = &b_obj; Output :B *b_ptr = &b_obj; b =5b_ptr->setb(10); b =10b_ptr->display();return 0;} 82
  83. 83. Virtual FunctionIt 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. 83
  84. 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; }} */}; }; 84
  85. 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(); //* Exceptionb.print_normal(); b_ptr->print_virtual();b.print_virtual(); return 0;d.print_normal(); }d.print_virtual();B *b_ptr;b_ptr = &b; 85
  86. 86. Pure Virtual Function & Abstract ClassThis 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 doesnt implement the pure virtual function, then you cannot create an object of a derived object also. 86
  87. 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; 87
  88. 88. C++Console Input/Output 88
  89. 89. getline():Used to read the whole line of text that ends with a newline character.cin object can invoke this function ascin.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. 89
  90. 90. getline(): Examplemain() Output :{ City Name :Bangalorechar city[50]; City Name :Bangalorecout << "City Name : ";// cin >> city ;cin.getline(city, 50);cout << "City Name : " << city << endl;} 90
  91. 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 cout.width(10);cout<<231;The output prints the number 231 within a field whose width is set to 10. 91
  92. 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 ascout.precision(no);- no is the number of digits to the right of the decimal; 92cout<<5.43564; output: 5.43.
  93. 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); 93
  94. 94. fill(): Example#include <iostream> Output :using namespace std; ###12main(){cout.fill(#);cout.width(5);cout << 12 << endl;} 94
  95. 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; 95c=cin.get();
  96. 96. get():syntax for the get(char *):char c;cin.get(c); 96
  97. 97. put():Used to display a character at a time.It is a member of ostram class.syntax:cout.put(a);orchar c;cout.put(c); 97
  98. 98. get() and put() :Example#include <iostream> Output :using namespace std; Input a character :amain() a{char c;cout << "Input a character : " ;cin.get(c);cout.put(c);cout << endl;} 98
  99. 99. ManipulatorsUsed 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 ascout<< manipulator 1 << manipulator 2 << manipulator 3 << parameter;There are lots of Manipulators for c++.Some of them are as follows : 99
  100. 100. Manipulatorssetw(int w)- It sets the field width to << setw(5) << 55;- This program code prints the value 55 right justified in a field width of 5. 100
  101. 101. ManipulatorsendlThis manipulator has the same functionality as the ‘n’ newline << "Matsya Technoloy" << endl;cout << "Hello world";- output: Matsya Technology Hello wold 101
  102. 102. Manipulatorssetfill ( 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 .cout<<width(5) << setfill ( * ) << 34;- output : ***34 102
  103. 103. C++Files Input/Output 103
  104. 104. Files I/O Using Constructor#include <iostream> char name[20];#include <fstream> ifstream infile("data.txt");using namespace std; infile >> name;void main() infile.close();{ cout << name << endl;ofstream outfile("data.txt"); }outfile << "Ritu" ;outfile << endl ;outfile.close(); 104
  105. 105. File Open & CloseOpen :fstream classfstream is a standard C++ library that handles reading from and writing to files either in text or in binary formats.Header file – fstream.hUse class ofstream to create output stream object.Use class ifstream to create input stream object. 105
  106. 106. File Open & CloseConstructors :fstream( const char *filename, openmode mode );ifstream( const char *filename, openmode mode );ofstream( const char *filename, openmode mode );Open a file using file stream constructorfile-stream-class stream-object(“filename”);ofstream out_obj(“output.dat”); // output file streamifstream in_obj(“input.dat”); // input file stream 106
  107. 107. File Open & CloseClose :close() functionclose() is used with file streams.It closes current stream.void close();Close a filefile-stream-class file-stream-object;“filename”, mode);file-stream-object.close(); 107
  108. 108. File Open & Close ExampleThe 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.txt");file << "Hello world!n";file.close(); 108return 0; }
  109. 109. File PositioningInput & Output Streams can be manipulated independently.Each file has two pointers associated with it called get pointer(read pointer) & put pointer (write pointer)Get Pointeris used for input (read) operations.Put Pointeris used for output (write) operations. 109
  110. 110. File Positioning : InputInput 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 directiontellg()-Get position of the get pointer-streampos tellg( ); 110
  111. 111. File Positioning : OutputOutput 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( ); 111
  112. 112. SEEKP/TELLP ExampleIt 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 "; 112
  113. 113. PUT & GET Functionput()-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() 113
  114. 114. PUT & GET Function:ExampleFollowing 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"); 114
  115. 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 ); 115
  116. 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 116 Your first name is : matsya
  117. 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. 117
  118. 118. gcount() :Example#include <iostream> Output :using namespace std; Enter your full name :Matsya You have typed 6 charsint main () {char name[1024];cout << "Enter your full name :";cin.getline(name, 1024);cout << "You have typed "<< cin.gcount() - 1<< " charsn";return 0; 118}
  119. 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. 119
  120. 120. File Read & WriteRead & Write function are similar to C “Language”.They are associated with a stream in read ( char* s, streamsize n );write()ostream& write ( char* s, streamsize n ); 120
  121. 121. Read & write Example#include <fstream> ifstream ifs("marks.txt");#include <iostream> *)&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; 121}
  122. 122. Error Handling :EOF()// Example: files_eof.cpp ifstream ifs( "eof_test.txt" );// display contents of eof_test.txt while(1) {// echo “Hello World” >> ifs >> ch; eof_test.txt if (ifs.eof()) break; cout << ch;#include <iostream> }#include <fstream> ifs.close();using namespace std; }main(){char ch; 122
  123. 123. 123
  124. 124. Template functionFunctions 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. 124
  125. 125. Template Function - Example:#include <iostream> template <class type1, class type2>using namespace std; type1 subtract(type1 in1, type2template <class type> in2)type add(type in1, type in2) {{ type1 local;type local; local = in1 - in2;local = in1 + in2; return local;return local; }} 125
  126. 126. Template Function - Example:main(){cout << add<int>(1,2);cout << endl;cout << subtract<long, int>(100L,2);cout << endl;} 126
  127. 127. Template ClassA 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 127}
  128. 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 doesnt work - has some garbage values//number(type n1, type n2) { n1 = n1; n2 = n2;} 128
  129. 129. Template Class - Exampletemplate <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(); 129
  130. 130. C++Standard Template Library 130
  131. 131. InroductionStandard 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 TemplateSTL 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. 131
  132. 132. InroductionIn 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. 132
  133. 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. 133
  134. 134. InroductionIterators :– 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. 134
  135. 135. Vector ClassIt 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 dynamicallyMemory management is automatic.Vector is the simplest of the STL container classes, and in many cases the most efficient. 135
  136. 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) { 123456coll.push_back(i);} 136
  137. 137. List ClassIt 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. 137
  138. 138. List Class:Example#include <iostream> /* print all elements#include <list> * - while there are elementsusing 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 : 138 a b c d ........ z
  139. 139. Map ClassIt 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. 139
  140. 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 elementstypedef map<string,float> * - element member first is the keyStringFloatMap; * - element member second is theStringFloatMap coll; value// insert some elements into the */ collection StringFloatMap::iterator pos; 140coll["VAT"] = 0.15;
  141. 141. Map Class:Examplefor (pos = coll.begin(); pos != Output : coll.end(); ++pos) { key: VAT value: 0.15cout << "key: "" << pos->first << "" " key: PI value: 3.145<< "value: " << pos->second << key: an arbitrary number value: endl; 4983.223} key: Null value: 0} 141
  142. 142. Set ClassIt 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. 142
  143. 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); 143
  144. 144. Set Class:Examplefor (pos = coll.begin(); pos != Output : coll.end(); ++pos) { 123456std::cout << *pos << ;}std::cout << std::endl;} 144
  145. 145. C++Namespaces 145
  146. 146. How Namespace comesMotivation :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? 146
  147. 147. Namespace-Solution// vendor1.h // vendor2.hnamespace vendor1 { namespacevendor2 {... Some code ... ... Some code ...class String { class String {... ...}; };} } 147
  148. 148. Namespace-Solution// My Application#include "vendor1.h"#include "vendor2.h“...Some Code ....vendor1::String s1,s2; // NO Ambiguity 148
  149. 149. Namespace-DefinitionA 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). 149
  150. 150. The Std NamespaceThe 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: 150std :: cout<<“hello, this is a sample”;