Advantages and disadvantages of C++ Advantages: More user control Manual memory management Incredible speed Widely Supported Disadvantages Requires more work Pointers and memory management Longer Development time //Input and output #include <iostream> #include <iomanip> Using namespace std //used with cin and cout //Formatting cout Output in C++ using iomanip int Main() { char ch = ‘a’; cin>> ch; cout << ch; //I/O manipulators stw() and setpercision() double f = 3.14159; cout<< setpercision (4) << f << endl; cout<< setpercision (9) << f << endl; cout <<fixed; cout<< setpercision (5) << f << endl; cout<< setpercision (9) << f << endl; //3.1416 //3.14159 //adds zeros //3.14159 //3.141590000 //This function should only be used as a stream manipulator //right justified by 10. --------77 cout << setw(10); cout << 77 << endl; //set the number you want to square and cube to. int x = 50; //loop through for(int i = 3; i<=x; i+=9) { //output the number, square and cube in fields of width x cout<<setw(10)<<i<<setw(10)<<pow(i,2)<<setw(10)<<pow(i,3)<<endl; // result: --------50------2500----125000 } return 0; } Overloading Functions C++ allows multiple functions to have the same name: void PrintMe (string s) { cout << "string s = \"" << s << "\"" << endl ; } void PrintMe (int i) { cout << "int i = " << i << endl ; } void PrintMe (string s, int i) { cout << s << " " << i << endl ; } Function Signature A function's signature includes the function's name and the number, order and type of its formal parameters. Two overloaded functions must not have the same signature. The return value is not part of a function's signature. These two functions have the same signature: int Divide (int n, int m) ; double Divide (int n, int m) ; //Classes Class Box { //member Variables //Private: accessible only by other members of the Box class Private: int width, length, height; //Public: accessible to other parts of your program //CONSTRUCTORS: //Constructor Box (int W, int L, int H){width = W; length=L; height=H ;} Box(int D){width = D; length=d; height=d;} //Default Constructor Public: Box (){width = 2;length=2; height=2;} //Methods //Overloading Functions: Same function name, different kind and/or number of parameters //unique signature: the number, types and order of a function. void setDimensions(int I){ width =I; length = I; height=I;} //Inline methods void setDimentions(int i, int j, int k){ width =i; length = j; height=k;} //Inline methods //inline method int calculateVolume ();{return width*length*height;} public int calculateArea (); //prototype of a member function }; //end of class definition //definition of a member methods int Box::calculateArea () { int area = (width*length+width*height+length*height)*2; return area; } int main () { //implicit Box b1; Box b2(5,6,7); //explicit allows call to constructor after object has been created Box b = Box(); //Dot operator cout <<b1.calculatArea(); cout << b2.calculateVolume(); return 0; } //Data encapsulation is a mechanism of bundling the data, and the functions that use them and data //abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. /* Has A Box class Has A width Box class Has A length Box class Has A height */ //Inheritance – Is A class House: public Box{ // (house Is A box) //Protected in base class is private member of derived class int roofHeight; int windowCount; //CONSTRUCTORS: //Default constructor House (){roofHeight=1;} //The above constructor executes Box’s default constructor which executes these statements //width = 2; length=2; height=2; //Constructor House(int W, int L, int H,int R):Box(W,L,H){ roofHeight=R;} //Methods calculateVolume (); int calculateVolume () {return width*length*(height+roofHeight/2);} }; int House:: calculateArea () { return width*length+ //(floor) 2*width*height+ // (sides) length*height+ //(sides) length*roofHeight + //(2 triangles) 2*length*(squ((roofHeight)^2 + (length/2)^2 )); //(rest of the roof area) } } //Polymorphism: having/assuming various forms - - calculatArea is defined differently in: //Box class : int calculateVolume () {return width*length*height;} //House class: int calculateVolume () {return width*length*(height+roofHeight/2);} Access Control: Private Class members declared as private can be used only by member functions and friends (classes or functions) of the class. Protected Class members declared as protected can be used by member functions and friends (classes or functions) of the class. Additionally, they can be used by classes derived from the class. Public Class members declared as public can be used by any function. //Random generator –libraries and range: The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable. We can seed the generator with the srand() function. This will start the generator from a point in the sequence that is dependent on the value we passed as an argument. If we seed the generator once with a variable value, for instance the system time, before our first call of rand() we can generate numbers that are random enough for simple use(though not for serious static purposes) #include <stdio.h> #include <stdlib.h> #include <time.h> /* printf, scanf, puts, NULL */ /* srand, rand */ /* time */ Main(){ srand (time(NULL)); // initialize random seed: int I = rand()%10; // A number between zero and nine int I = rand()%90 + 10 // a number between 10 and 99 } A Function and its components Function Prototype: Return_value name(type parameter); // When the prototype is provided, the compiler will catch the error // in main(). If it is omitted, then the error will go unnoticed. Example //takes an integer value and returns an integer as result int doubleit(int i); //Function definition is the function prototype plus the body of the function int main(){ int i = 10; int j = double(i); //calling a method } //defining a method int double(int i) { //function header //function body i = i *2; return i; } //Calling a function: int j = double(i); //Default arguments in a function //prototype int myFunc(int a, int b=6, int c=12); //Definition of the function int myFunc(int a, int b, int c) //no semicolon here { int x = a; int y = b; int z = c; } //Calling that function Result1 = myFunc(1,2,3); // x = a = 1; y = b = 2 z = c= 3 Result2 = myFunc(1,2); // x = a = 1; y = b = 2 z = c=12 Result3 = myFunc(1); // x = a = 1; y = b =6 z = c= 12 //passing array as a function parameter void arrayFunc(int arg[]); //declaring the array int myArray[40]; //calling the function with an array argument arrayFunc(myArray); //Reference variables int x = 5 ; int z = x; x x 5 5 z 5 z = 6; //now z=6 and x=5 x 5 z 6 int &y =x; x 5 y //y can only be used to refer to an existing integer y = 56 //now x=56 x 56 y Enumeration: The enum is declared as: enum enum-type-name enum-variable; By default, the first enumerator is assigned the integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator: enum Color { COLOR_BLACK, // assigned 0 COLOR_RED, // assigned 1 COLOR_BLUE, // assigned 2 COLOR_GREEN, // assigned 3 COLOR_WHITE, // assigned 4 COLOR_CYAN, // assigned 5 COLOR_YELLOW, // assigned 6 COLOR_MAGENTA // assigned 7 } enum e_acomany { Audi=4, BMW=5, Cadillac=11, Ford=44, Jaguar=45, Lexus, Maybach=55, RollsRoyce=65, Saab=111 }; enum Color { RED, GREEN, BLUE }; Color r = RED; switch(r) { case RED : cout << "red" ; break; case GREEN : cout << "green"; break; case BLUE : cout << "blue" ; break; } //Static members class MyClass { public: static int i; MyClass (){i++;} }; ~ MyClass (){i--;} int MyClass::i = 0; // definition outside class declaration int main(){ MyClass m1, m2; cout<<m1.i; cout<<m2.i; cout << MyClass::i; } Vectors size : empty: at: assign: push_back: pop_back: insert: erase: clear: Return size (public member function ) Test whether vector is empty (public member function ) Access data at any position Assign vector content (public member function ) Add element at the end (public member function ) Delete last element (public member function ) Insert elements (public member function ) Erase elements (public member function ) Clear content (public member function ) // constructing vectors #include <iostream> #include <vector> int main () { // constructors used in the same order as described above: vector<int> first; // empty vector of ints vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second vector<int> fourth (third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) ); cout << "The contents of fifth are:"; for (vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it) { cout << ' ' << *it; } vector<int> integers(7)//declaring a vector with 7 integer elements for(int i=0; I < integers.size();i++) cout<<integers[i] //declaring a vector of string vector<string> words; string str; //while there are more string to be read from standard input(keyboard) push the words read into the vector while( cin >> str ) words.push_back(str); //to go through the vector and access each member we need to use an iterator. vector<string>::iterator iter; for( iter = words.begin(); iter != words.end(); iter++ ) { cout << *iter << endl; { return 0; } Example of friend function class Box { private: double width; public: friend void printWidth( Box box ); //friend function void setWidth( double wid ); }; // Member function definition void Box::setWidth( double wid ) { width = wid; } // Note: printWidth() is not a member function of any class. void printWidth( Box box ) { /* Because printWidth() is a friend of Box, it can directly access any member of this class */ cout << "Width of box : " << box.width <<endl; } // Main function for the program int main( ) { Box box; // set box width without member function box.setWidth(10.0); // Use friend function to print the wdith. printWidth( box ); return 0; } Overloading Operator The following set of operators is commonly overloaded for user-defined classes: = (assignment operator) + - * (binary arithmetic operators) += -= *= (compound assignment operators) == != (comparison operators) class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } MyClass a, b; ... b = a; // Same as b.operator=(a); bool MyClass::operator==(const MyClass &other) const { ... // Compare the values, and return a bool result. } class Distance { private: int feet; // 0 to infinite int inches; // 0 to 11 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } friend ostream & operator<<( ostream &output, const Distance &D ) { output << "Feet : " << D.feet << " Inches : " << D.inches; return output; } friend istream &operator>>( istream &input, Distance &D ) { input >> D.feet >> D.inches; return input; } int main() { Distance D1(11, 10), D2(5, 11), D3; cout << "Enter the value of object : " << endl; //reading the value of members of D using overloading operator >> in main cin >> D3; //displaying the value of members of D using overloading operator << in main cout << "First Distance : " << D1 << endl; cout << "Second Distance :" << D2 << endl; cout << "Third Distance :" << D3 << endl; return 0; } //When the above code is compiled and executed, it produces following result: Enter the value of object : 70 10 First Distance: Feet: 11 Inches: 10 Second Distance: Feet: 5 Inches: 11 Third Distance: Feet: 70 Inches: 10