Monday, August 31, 2015

Complete c++ basic notes

The Origins of C++
C++ began as an expanded version of C. The C++ extensions were first invented by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with Classes." However, in 1983 the name was changed to C++.
To support the principles of object-oriented programming, all OOP languages have three traits in common: encapsulation, polymorphism, and inheritance. Let's examine each.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates,and keeps both safe from outside interference and misuse. When code and data are linked together in this fashion, an object is created. Within an object, code, data, or both may be private to that object or public. Private
code or data is known to and accessible only by another part of the object. That is,private code or data may not be accessed by a piece of the program that exists outside the object. When code or data is public, other parts of your program may access it even though it is defined within an object. Typically, the public parts of an object are used to provide a controlled interface to the private elements of the object.An object is a variable of a user-defined type.
Polymorphism
Object-oriented programming languages support polymorphism, which is characterized
by the phrase "one interface, multiple methods." Polymorphism helps reduce complexity by allowing the same interface to be used to access a general class of actions. It is the compiler's job to select the specific action (i.e., method) as it applies to each situation. In C++, both run-time and compile-time polymorphism are supported.
Inheritance
Inheritance is the process by which one object can acquire the properties of another object. This is important because it supports the concept of classification.
 A Sample C++ Program#include <iostream>using namespace std;int main(){int i;cout << "This is output.\n"; // this is a single line comment/* you can still use C style comments */// input a number using >>cout << "Enter a number: ";cin >> i;// now, output a number using <<cout << i << " squared is " << i*i << "\n";return 0;}2.#include <iostream>using namespace std;int main(){float f;char str[80];double d;cout << "Enter two floating point numbers: ";cin >> f >> d;cout << "Enter a string: ";cin >> str;cout << f << " " << d << " " << str;return 0;}Declaring Local Variables/* Incorrect in C. OK in C++. */int f(){int i;i = 10;int j; /* won't compile as a C program */j = i*2;return j;}In C++ you may declare local variables at any point within a block—not just at the beginning. #include <iostream>using namespace std;int main(){float f;264 C + + : T h e C o m p l e t e R e f e r e n c e
double d;cout << "Enter two floating point numbers: ";cin >> f >> d;cout << "Enter a string: ";char str[80]; // str declared here, just before 1st usecin >> str;cout << f << " " << d << " " << str;return 0;}The bool Data TypeC++ defines a built-in Boolean type called bool. Objects of type bool can store only the values true or false, which are keywords defined by C++.
Introducing C++ ClassesIn C++, to create an object, you first must define its general form by using the keyword class. A class is
similar syntactically to a structure. Here is an example. The following class defines a type called stack, which will be used to create a stack:
 #define SIZE 100// This creates the class stack.class stack {int stck[SIZE];int tos;public:void init();void push(int i);int pop();}; A class may contain private as well as public parts. By default, all items defined in a class are private. For example, the variables stck and tos are private. This means that they cannot be accessed by any function that is not a member of the class.
To make parts of a class public (that is, accessible to other parts of your program),you must declare them after the public keyword. All variables or functions defined after public can be accessed by all other functions in the program. Notice that the public keyword is followed by a colon.
The functions init(), push(), and pop() are called member functions because they are part of the class stack. The variables stck and tos are called member variables (or data members). Remember, an object forms a bond between code and data.
Once you have defined a class, you can create an object of that type by using the class name.
                         
                             stack mystack;When you declare an object of a class, you are creating an instance of that class. In this case, mystack is an instance of stack. A class is a logical abstraction, while an object is real. (That is, an object exists inside the memory of the computer.) The general form of a simple class declaration is
 class class-name {
private data and functionspublic:public data and functions} object name list;
 void stack::push(int i){if(tos==SIZE) {cout << "Stack is full.\n";return;}stck[tos] = i;tos++;}The :: is called the scope resolution operator. Essentially, it tells the compiler that this version of push() belongs to the stack class.
stack stack1, stack2;stack1.init();This fragment creates two objects, stack1 and stack2, and initializes stack1.
2.#include <iostream>using namespace std;#define SIZE 100// This creates the class stack.class stack {int stck[SIZE];int tos;public:void init();void push(int i);int pop();};void stack::init(){tos = 0;}void stack::push(int i){if(tos==SIZE) {cout << "Stack is full.\n";return;}stck[tos] = i;tos++;}int stack::pop(){if(tos==0) {cout << "Stack underflow.\n";return 0;}tos--;C h a p t e r 1 1 : A n O v e r v i e w o f C + + 273
return stck[tos];}int main(){stack stack1, stack2; // create two stack objectsstack1.init();stack2.init();stack1.push(1);stack2.push(2);stack1.push(3);stack2.push(4);cout << stack1.pop() << " ";cout << stack1.pop() << " ";cout << stack2.pop() << " ";cout << stack2.pop() << "\n";return 0;}The output from this program is shown here.3 1 4 2Function Overloadingthe functions that share the same name are said to be overloaded, and the process is referred to as function overloading.
#include <iostream>using namespace std;// abs is overloaded three waysint abs(int i);double abs(double d);long abs(long l);int main(){cout << abs(-10) << "\n";cout << abs(-11.0) << "\n";cout << abs(-9L) << "\n";return 0;}int abs(int i){cout << "Using integer abs()\n";return i<0 ? -i : i;}double abs(double d){cout << "Using double abs()\n";return d<0.0 ? -d : d;}C h a p t e r 1 1 : A n O v e r v i e w o f C + + 275
long abs(long l){cout << "Using long abs()\n";return l<0 ? -l : l;}The output from this program is shown here.Using integer abs()10Using double abs()11Using long abs()9This program creates three similar but different functions called abs(), each of which returns the absolute value of its argument. The compiler knows which function to call in each situation because of the type of the argument.Here is another example that uses overloaded functions:#include <iostream>#include <cstdio>#include <cstring>using namespace std;void stradd(char *s1, char *s2);void stradd(char *s1, int i);int main(){char str[80];strcpy(str, "Hello ");stradd(str, "there");cout << str << "\n";stradd(str, 100);cout << str << "\n";return 0;}// concatenate two stringsvoid stradd(char *s1, char *s2){strcat(s1, s2);}// concatenate a string with a "stringized" integervoid stradd(char *s1, int i){char temp[80];sprintf(temp, "%d", i);strcat(s1, temp);} InheritanceAderived class includes all features of the generic base class and then adds qualities specific to thederived class.class building {int rooms;int floors;int area;public:void set_rooms(int num);int get_rooms();void set_floors(int num);int get_floors();void set_area(int num);int get_area();}; // house is derived from buildingclass house : public building {int bedrooms;int baths;public:void set_bedrooms(int num);int get_bedrooms();void set_baths(int num);int get_baths();}; The general form for inheritance isclass derived-class : access base-class {
// body of new class
}Here, access is optional. However, if present, it must be public, private, or protected.
=>A derived class has direct access to both its own members and the public members of the base class.Here is a program illustrating inheritance. It creates two derived classes of building using inheritance; one is house, the other, school.
#include <iostream>using namespace std;class building {int rooms;int floors;int area;public:void set_rooms(int num);int get_rooms();void set_floors(int num);int get_floors();void set_area(int num);int get_area();};// house is derived from buildingclass house : public building {int bedrooms;int baths;public:void set_bedrooms(int num);int get_bedrooms();void set_baths(int num);int get_baths();};// school is also derived from buildingclass school : public building {int classrooms;int offices;public:void set_classrooms(int num);int get_classrooms();void set_offices(int num);int get_offices();};void building::set_rooms(int num){rooms = num;}void building::set_floors(int num){floors = num;}void building::set_area(int num){area = num;}int building::get_rooms(){return rooms;}int building::get_floors(){return floors;}int building::get_area(){return area;}void house::set_bedrooms(int num){bedrooms = num;}void house::set_baths(int num){baths = num;}int house::get_bedrooms(){return bedrooms;}int house::get_baths(){return baths;}void school::set_classrooms(int num){classrooms = num;}void school::set_offices(int num){offices = num;}int school::get_classrooms(){return classrooms;}int school::get_offices(){return offices;}int main(){house h;school s;h.set_rooms(12);h.set_floors(3);h.set_area(4500);h.set_bedrooms(5);h.set_baths(3);cout << "house has " << h.get_bedrooms();cout << " bedrooms\n";s.set_rooms(200);s.set_classrooms(180);s.set_offices(5);s.set_area(25000);cout << "school has " << s.get_classrooms();cout << " classrooms\n";cout << "Its area is " << s.get_area();return 0;}The output produced by this program is shown here.house has 5 bedroomsschool has 180 classroomsIts area is 25000Constructors and Destructors:A constructor function is a special function that is a member of a class and has
the same name as that class.// This creates the class stack.class stack {int stck[SIZE];int tos;public:stack(); // constructorvoid push(int i);int pop();};Notice that the constructor stack() has no return type specified. In C++, constructor functions cannot return values and, thus, have no return type.The stack() function is coded like this:
// stack's constructor functionstack::stack(){tos = 0;cout << "Stack Initialized\n";}An object's constructor is automatically called when the object is created. An object's constructor is called once for global or static local objects. For local objects, the constructor is called each time the object declaration is encountered.
The complement of the constructor is the destructor. Local objects are created when their block is entered, and destroyed when the block is left. Global objects are destroyed when the program terminates. When an object is destroyed, its destructor (if it has one) is automatically called. There are many reasons why a destructor function may be needed. For example, an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened. In C++, it is the destructor function that handles deactivation events. The destructor has the same name as the constructor, but it is preceded by a ~.
// This creates the class stack.class stack {int stck[SIZE];int tos;public:stack(); // constructor~stack(); // destructorvoid push(int i);int pop();};// stack's constructor functionstack::stack(){tos = 0;cout << "Stack Initialized\n";}// stack's destructor functionstack::~stack(){cout << "Stack Destroyed\n";}To see how constructors and destructors work, here is a new version of the stack
// Using a constructor and destructor.#include <iostream>using namespace std;#define SIZE 100// This creates the class stack.class stack {int stck[SIZE];int tos;public:stack(); // constructor~stack(); // destructorvoid push(int i);int pop();};// stack's constructor functionstack::stack(){tos = 0;cout << "Stack Initialized\n";}// stack's destructor functionstack::~stack(){cout << "Stack Destroyed\n";}void stack::push(int i){if(tos==SIZE) {cout << "Stack is full.\n";return;}stck[tos] = i;tos++;}int stack::pop(){if(tos==0) {cout << "Stack underflow.\n";return 0;}tos--;return stck[tos];}int main(){stack a, b; // create two stack objectsa.push(1);b.push(2);a.push(3);b.push(4);cout << a.pop() << " ";cout << a.pop() << " ";cout << b.pop() << " ";cout << b.pop() << "\n";return 0;}This program displays the following:Stack InitializedStack Initialized3 1 4 2Stack DestroyedStack DestroyedThe C++ KeywordsThere are 63 keywords currently defined for Standard C++.asm auto bool break case catch char class const const_cast continue default delete do double dynamic_cast ealse enum explicit export extern false float for friend goto if inline int long mutable namespace new operator private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while          ClassesClasses are created using the keyword class. A class declaration defines a new type that links code and data. This new type is then used to declare objects of that class.Thus, a class is a logical abstraction, but an object has physical existence. In other words, an object is an instance of a class. class class-name {
private data and functionsaccess-specifier:data and functionsaccess-specifier:data and functions// ...access-specifier:data and functions} object-list; The object-list is optional. If present, it declares objects of the class.
#include <iostream>#include <cstring>using namespace std;class employee {char name[80]; // private by defaultpublic:void putname(char *n); // these are publicvoid getname(char *n);private:double wage; // now, private againpublic:void putwage(double w); // back to publicdouble getwage();};void employee::putname(char *n){strcpy(name, n);}void employee::getname(char *n){strcpy(n, name);}void employee::putwage(double w){wage = w;}double employee::getwage(){return wage;}int main(){employee ted;char name[80];ted.putname("Ted Jones");ted.putwage(75000);ted.getname(name);cout << name << " makes $";cout << ted.getwage() << " per year.";return 0;}Here, employee is a simple class that is used to store an employee's name and wage.
most programmers would code theemployee class as shown here, with all private elements grouped together and all
public elements grouped together:class employee {char name[80];double wage;public:void putname(char *n);void getname(char *n);void putwage(double w);double getwage();}; Functions that are declared within a class are called member functions. Member functions may access any element of the class of which they are a part. Variables that are elements of a class are called member variables or data members. Collectively, any element of a class can be referred to as a member
of that class.#include <iostream>using namespace std;class myclass {public:int i, j, k; // accessible to entire program};int main(){myclass a, b;a.i = 100; // access to i, j, and k is OKa.j = 4;a.k = a.i * a.j;b.k = 12; // remember, a.k and b.k are differentcout << a.k << " " << b.k;return 0;}  // Using a structure to define a class.#include <iostream>#include <cstring>using namespace std;struct mystr {void buildstr(char *s); // publicvoid showstr();private: // now go privatechar str[255];} ;void mystr::buildstr(char *s){if(!*s) *str = '\0'; // initialize stringelse strcat(str, s);}void mystr::showstr(){cout << str << "\n";}int main(){mystr s;s.buildstr(""); // inits.buildstr("Hello ");s.buildstr("there!");s.showstr();return 0;} This program displays the string Hello there!.
The class mystr could be rewritten by using class as shown here:
class mystr {char str[255];public:void buildstr(char *s); // publicvoid showstr();} ; Unions and Classes Are RelatedLike a structure, a union may also be used to define a class. In C++, unions may contain both member functions and variables. They may also include constructor and destructor functions. A union in C++ retains all of its C-like features, the most important being that all data elements share the same location in memory. Like the structure, union members are public by default and are fully compatible with C.
#include <iostream>using namespace std;union swap_byte {void swap();void set_byte(unsigned short i);void show_word();unsigned short u;unsigned char c[2];};void swap_byte::swap(){unsigned char t;t = c[0];c[0] = c[1];c[1] = t;}void swap_byte::show_word(){cout << u;}void swap_byte::set_byte(unsigned short i){u = i;}int main(){swap_byte b;b.set_byte(49034);b.swap();b.show_word();return 0;}There are several restrictions that must be observed when you use C++ unions.First, a union cannot inherit any other classes of any type. Further, a union cannot be a base class. A union cannot have virtual member functions. No static variables can be members of a union. A reference member cannot be used. A union cannot have as a member any object that overloads the = operator. Finally, no object can be a member of a union if the object has an explicit constructor or destructor function.
Friend FunctionsIt is possible to grant a nonmember function access to the private members of a class by using a friend. A friend function has access to all private and protected members of the class for which it is a friend. To declare a friend function, include its prototype within the class, preceding it with the keyword friend. Consider this program:
#include <iostream>using namespace std;class myclass {int a, b;public:friend int sum(myclass x);void set_ab(int i, int j);};void myclass::set_ab(int i, int j){a = i;b = j;}// Note: sum() is not a member function of any class.int sum(myclass x){/* Because sum() is a friend of myclass, it candirectly access a and b. */return x.a + x.b;}int main(){myclass n;n.set_ab(3, 4);cout << sum(n);return 0;}In this example, the sum() function is not a member of myclass. However, it still has full access to its private members. Also, notice that sum() is called without the use of the dot operator. Because it is not a member function, it does not need to be (indeed,it may not be) qualified with an object's name.
Friend ClassesIt is possible for one class to be a friend of another class. When this is the case, the friend class and all of its member functions have access to the private members defined within the other class. For example,
 // Using a friend class.#include <iostream>using namespace std;class TwoValues {int a;int b;public:TwoValues(int i, int j) { a = i; b = j; }friend class Min;};class Min {public:int min(TwoValues x);};int Min::min(TwoValues x){return x.a < x.b ? x.a : x.b;}int main(){TwoValues ob(10, 20);Min m;cout << m.min(ob);return 0;}In this example, class Min has access to the private variables a and b declared within the TwoValues class.
 




IF ANY PROBLEM THEN CONTACT ON ankitpundir623@gmail.com

No comments:

Post a Comment