• Save
OpenGurukul : Language : C++ Programming
Upcoming SlideShare
Loading in...5
×
 

OpenGurukul : Language : C++ Programming

on

  • 2,223 views

C++ Programming By OpenGurukul

C++ Programming By OpenGurukul

Statistics

Views

Total Views
2,223
Views on SlideShare
1,820
Embed Views
403

Actions

Likes
2
Downloads
0
Comments
0

2 Embeds 403

http://www.opengurukul.com 402
http://translate.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

OpenGurukul : Language : C++ Programming OpenGurukul : Language : C++ Programming Presentation Transcript

  • C++ By OpenGurukul.comFree/Open Source Software Laboratory
  • C++Beginning with C++ www.opengurukul.com 2
  • 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. www.opengurukul.com 3
  • Hello World program// my first program in C++#include <iostream>using namespace std;int main (){cout << "Hello World!";return 0;} www.opengurukul.com 4
  • 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
  • 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
  • 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 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
  • 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). www.opengurukul.com 8
  • 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. www.opengurukul.com 9
  • 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. www.opengurukul.com 10
  • 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 www.opengurukul.com 11 using the concept of virtual functions.
  • C++Control Structures www.opengurukul.com 12
  • 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 www.opengurukul.com 13
  • if and elseSyntax :if( boolean_expression ) else{ {statement1; statement3;statement2; statement4;... ...} } www.opengurukul.com 14
  • 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} www.opengurukul.com 15
  • switch StatementSyntax :switch( switch_expression ){ default:case case_selector1: statement1;// statement1;// } break;case case_selector2: statement1;// break; www.opengurukul.com 16
  • 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; www.opengurukul.com 17
  • 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 www.opengurukul.com 18
  • while loopStatement or block of statements that is repeated as long as some condition is satisfied.Syntax :while( boolean_expression ){statement1;statement2;...} www.opengurukul.com 19
  • 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++; } www.opengurukul.com 20
  • 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 ); www.opengurukul.com 21
  • 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;} www.opengurukul.com 22
  • for loopAllows execution of the same code a number of times.Synatx :for(InitializationExpression;Condition;StepExpression){statement1;statement2;...} www.opengurukul.com 23
  • 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;} www.opengurukul.com 24
  • 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 ? www.opengurukul.com 25
  • C++Functionwww.opengurukul.com 26
  • 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. www.opengurukul.com 27
  • 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. www.opengurukul.com 28
  • 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;} www.opengurukul.com 29
  • 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
  • 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. www.opengurukul.com 31
  • 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
  • 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. www.opengurukul.com 33
  • 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. www.opengurukul.com 34
  • 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);
  • 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 www.opengurukul.com changed to 105.
  • 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 www.opengurukul.com 37
  • 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. www.opengurukul.com 38
  • C++Classes & Objects www.opengurukul.com 39
  • 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. www.opengurukul.com 40
  • 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. www.opengurukul.com 41
  • 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} www.opengurukul.com 42
  • 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. www.opengurukul.com 43
  • 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. www.opengurukul.com 44
  • 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; www.opengurukul.com 45
  • 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
  • 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. www.opengurukul.com 47
  • 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 www.opengurukul.com 48
  • 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. www.opengurukul.com 49
  • 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 www.opengurukul.com 50{
  • 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 51public:
  • 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;} www.opengurukul.com 52
  • 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(); }; www.opengurukul.com 53
  • 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. www.opengurukul.com 54
  • 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) { www.opengurukul.com 55cout << "a is " << x.a << endl;
  • C++Constructors & Destructors www.opengurukul.com 56
  • 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. www.opengurukul.com 57
  • 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. www.opengurukul.com 58
  • 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};
  • Parametrized ConstructorIn such a constructor, argument are passed to constructor for initialization purpose www.opengurukul.com 60
  • 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; www.opengurukul.com 61
  • 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 www.opengurukul.com 62
  • 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();} www.opengurukul.com 63
  • 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. www.opengurukul.com 64
  • 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; www.opengurukul.com 65a=b; //deep copy
  • 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. www.opengurukul.com 66
  • 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(); www.opengurukul.com 67
  • DestructorsExample :class X {public:// Constructor for class XX();// Destructor for class X~X();}; www.opengurukul.com 68
  • C++Inheritancewww.opengurukul.com 69
  • 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. www.opengurukul.com 70
  • 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
  • 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();} www.opengurukul.com 72
  • 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). www.opengurukul.com 73
  • 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. www.opengurukul.com 74
  • 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} } www.opengurukul.com 75
  • 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;}; www.opengurukul.com 76
  • Static Function & Inheritanceint main(){SomeClass A;SomeClass B;SomeDerivedClass C;cout << SomeClass::total << endl;return 0;} www.opengurukul.com 77
  • C++Pointers, Virtual Functions www.opengurukul.com 78
  • this PointerIt is available to non-static member functions.It is an address of the object handle that has invoked the method. www.opengurukul.com 79
  • 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. www.opengurukul.com 80
  • 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
  • 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;} www.opengurukul.com 82
  • 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. www.opengurukul.com 83
  • 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
  • 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; www.opengurukul.com 85
  • 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. www.opengurukul.com 86
  • 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
  • C++Console Input/Output www.opengurukul.com 88
  • 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. www.opengurukul.com 89
  • getline(): Examplemain() Output :{ City Name :Bangalorechar city[50]; City Name :Bangalorecout << "City Name : ";// cin >> city ;cin.getline(city, 50);cout << "City Name : " << city << endl;} www.opengurukul.com 90
  • 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
  • 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 point.eg.cout.precision(2); www.opengurukul.com 92cout<<5.43564; output: 5.43.
  • 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
  • fill(): Example#include <iostream> Output :using namespace std; ###12main(){cout.fill(#);cout.width(5);cout << 12 << endl;} www.opengurukul.com 94
  • 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 95c=cin.get();
  • get():syntax for the get(char *):char c;cin.get(c); www.opengurukul.com 96
  • 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); www.opengurukul.com 97
  • 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;} www.opengurukul.com 98
  • 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 : www.opengurukul.com 99
  • Manipulatorssetw(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
  • ManipulatorsendlThis 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
  • 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 fields.eg .cout<<width(5) << setfill ( * ) << 34;- output : ***34 www.opengurukul.com 102
  • C++Files Input/Output www.opengurukul.com 103
  • 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(); www.opengurukul.com 104
  • 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. www.opengurukul.com 105
  • 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 www.opengurukul.com 106
  • File Open & CloseClose :close() functionclose() is used with file streams.It closes current stream.void close();Close a filefile-stream-class file-stream-object;file-stream-object.open(“filename”, mode);file-stream-object.close(); www.opengurukul.com 107
  • 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.open("file.txt");file << "Hello world!n";file.close(); www.opengurukul.com 108return 0; }
  • 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. www.opengurukul.com 109
  • 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( ); www.opengurukul.com 110
  • 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( ); www.opengurukul.com 111
  • 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 "; www.opengurukul.com 112
  • 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() www.opengurukul.com 113
  • 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"); www.opengurukul.com 114
  • 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
  • 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
  • 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
  • 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; www.opengurukul.com 118}
  • 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
  • File Read & WriteRead & 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
  • 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}
  • 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; www.opengurukul.com 122
  • C++Templateswww.opengurukul.com 123
  • 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. www.opengurukul.com 124
  • 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; }} www.opengurukul.com 125
  • Template Function - Example:main(){cout << add<int>(1,2);cout << endl;cout << subtract<long, int>(100L,2);cout << endl;} www.opengurukul.com 126
  • 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 www.opengurukul.com 127}
  • 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;} www.opengurukul.com 128
  • 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(); www.opengurukul.com 129
  • C++Standard Template Library www.opengurukul.com 130
  • 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. www.opengurukul.com 131
  • 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. www.opengurukul.com 132
  • 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
  • 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. www.opengurukul.com 134
  • 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. www.opengurukul.com 135
  • 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);} www.opengurukul.com 136
  • 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. www.opengurukul.com 137
  • 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 : www.opengurukul.com 138 a b c d ........ z
  • 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. www.opengurukul.com 139
  • 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 www.opengurukul.com pos; 140coll["VAT"] = 0.15;
  • 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} www.opengurukul.com 141
  • 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. www.opengurukul.com 142
  • 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
  • Set Class:Examplefor (pos = coll.begin(); pos != Output : coll.end(); ++pos) { 123456std::cout << *pos << ;}std::cout << std::endl;} www.opengurukul.com 144
  • C++Namespaces www.opengurukul.com 145
  • 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? www.opengurukul.com 146
  • Namespace-Solution// vendor1.h // vendor2.hnamespace vendor1 { namespacevendor2 {... Some code ... ... Some code ...class String { class String {... ...}; };} } www.opengurukul.com 147
  • Namespace-Solution// My Application#include "vendor1.h"#include "vendor2.h“...Some Code ....vendor1::String s1,s2; // NO Ambiguity www.opengurukul.com 148
  • 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). www.opengurukul.com 149
  • 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: www.opengurukul.com 150std :: cout<<“hello, this is a sample”;