You are on page 1of 19

Every C++ program contains certain basic elements Comments, header file, namespace, parentheses, braces In both C and

C++, header files are included using the #include statement. In C, the name of the header file is specified after the #include statement. C++ uses new style headers that are not file names, hence they do not have the .h extension. The header name is enclosed within angle brackets. A namespace is a defined collection of symbols and variable names within an application. Every C++ application has at least one namespace, called std, short for standard. The complete standard C++ library is declared in the std namespace. The using statement is used to include a namespace in the program. The using statement is followed by the keyword namespace and then the name of the namespace. In C++, data communication with a program is established through a flow of data called a stream. Streams in a program allow sequential travel of data in one direction. The I/O stream in C++ allows the input and output of data through the use of the objects cin and cout. The input stream object cin is followed by the extraction operator ( >> ) to receive the input from the keyboard. Similarly, the output stream object cout is followed by the insertion operator ( << ) to display the output on the monitor. The endl is a special function that is used in an I/O expression to output a newline character. The compiler determines the type of program it is compiling based on its file extension. If the program has a .c file extension, then it is treated as a C program; if it has a .cpp file extension, then the program is treated as a C++ program. A compiler is a software that converts the code written in a programming language into machine language. Program code is written using a syntactic language that the computer cannot execute. The compiler bridges this difference by converting the code into machine language, which is in the form of 0s and 1s, that is understood by the computer. The compiler converts the source code into an output called object code. The output from a compiler is usually an executable file. Different compliers are used for compiling code written in different programming languages. You cannot use the same compiler to compile programs written in different programming languages. Some C and older C++ compilers consider only the first 32 characters of the variables. Modern C++ compilers that support the ANSI Standard handle character variable names that are longer than 32 easily. Variables are memory locations that store data that is to be manipulated in your application. Variables in C++ are defined much like variables in C. To declare a variable, the data type should be specified followed by the variable names and separated by commas. All variables should be declared before you use them. In C, variables should be declared only at the beginning of a function, whereas in C++, you can declare them anywhere in a function.

The scope of a variable determines what functions can access the variable. Variables may be global or local in a C++ application. A global variable is defined outside any function that exists for the life of the program, and can be accessed by any function within the program. A local variable is defined inside any function. Local variables have block scope, and are defined within a set of curly braces. They cannot be accessed outside the function in which they are declared. A hidden global variable is a global variable that lacks visibility. If you declare 'x' as a global variable and you declare another variable with the same name 'x' as a local variable, the global variable 'x' is hidden and cannot be accessed inside that particular function in which the local variable 'x' is declared. You can access hidden global variables by placing the global scope resolution operator (::) before the global variable. All C++ compilers support the C implementation of a string as an array of characters terminated by a null byte. However, newer C++ compilers that conform to the ANSI Standard also support a predefined string class that supports more natural implementation and usage of string objects. You can declare a string by prefixing the variable name with the string keyword. To use the string class in your programs, you need to include the string header file. In C, you use the #define keyword to define a constant value. However in C++, the keyword const is used in data declarations to indicate a constant, unchanging value. The keyword const generally precedes the data type when defining a constant value. A function declaration, or prototype, is a programming statement that causes the name of the function to be known to the compiler. The function declaration also specifies the data types of the arguments and the data type of any value returned from the function. The arguments in a function prototype are also known as its formal parameters. Functions should be declared before they are used. A function declaration is a simple C++ statement, and as such, must end with a semicolon. It does not cause space to be allocated by the compiler. When the keyword void is placed between the parentheses of a function declaration or definition, it means that the function does not take any arguments. When the keyword void is placed in front of a function declaration or definition, it means that the function does not return a value. A function definition includes the actual code of the function. When you define a function, space is allocated for the function. A function definition consists of a function name, followed by arguments separated by commas enclosed within parentheses. This is followed by the body of the function that is enclosed within curly braces. Unlike a function declaration, the function definition does not end with a semicolon. Pointers are variables that contain addresses of other variables. To declare a variable as a pointer variable, you must place an asterisk in front of the variable's name. A pointer variable can only hold addresses of variables of the specified data type. The keyword new returns the address of a newly

created variable. This address can then be assigned to a pointer variable. For example, once the pointer variable p has been initialized to point to another variable, you can refer to the pointed variable directly by using the syntax *p. Accessing a variable through a pointer in this fashion is referred to as dereferencing the pointer. A dynamically allocated variable can be deleted using the keyword delete followed by the name of the pointer variable.

*- pointer & address of pointer []- array ()- return type A reference variable is a special type of variable. It is always initialized by using another variable that may be of any type. On initialization, this reference becomes an alias for the actual variable, and can be used in any context where the actual variable is needed. References provide a useful method of ensuring that C++ modifies the actual variable, rather than a copy of the actual variable. Int x=22; Int& reftox=x; Reftox=25; In C, the malloc() method allocates a portion of memory and returns a pointer to that memory. The free() method accepts a pointer that was generated by malloc() and deallocates the pointed-to memory. In C++, you use the new and delete operators for allocating and deallocating dynamic memory. The new operator accepts the name of a primitive data type or an object, allocates memory for the data type or object, and returns a pointer to that primitive data type or object. The delete operator accepts a pointer generated by new and deallocates memory being pointed to. Stack memory is the portion of memory where local variables are stored. The stack stores instructions for the function currently being carried out, as well as the local variables being manipulated by the function. When a new function is called, the instruction pointer, which stores the address of the beginning of the function and any local variable, is pushed or stored on the stack for the function to be manipulated. When the function's execution is completed, the result of the function is returned to the calling function and the instructions and local variables are popped out or removed from the stack. Heap memory is a portion of memory that stores dynamically allocated variables that are created using the new operator. Unlike stack, memory allocation for heap grows only when a variable is marked for deletion. The operating system's memory management routine simply marks the space as being available for reuse. Heap memory increases, when necessary, by growing downward from the top of the application's address space.

Stack variables grow from the bottom of the address space and heap variables grow downward. So there is every probability that they will meet each other. When this happens, the stack overflow message is displayed and your application terminates abnormally. Object-oriented programming (OOP) is a methodology where all entities are treated as objects. These objects are modeled like real-time objects, which have two characteristics: attributes and behaviors. For example, a person's bank account can be treated as an object, where his name, account number, and balance can be the attributes of the object. Transactions such as deposits and withdrawals that control the bank account can be treated as behaviors. This idea of real-time objects is implemented in objectoriented programming. Object-oriented programming works by assembling various objects, their features, and their interactions to create an application.

A class is a template used to create objects and an object is an instance of a class. A class contains the attributes and behaviors that are common to similar objects. A message is a specific behavior that may be undertaken by an object. Objects interact by sending messages to other objects or to themselves. By sending a message, the sender requests the receiver to perform a behavior with which the receiver is associated. During compilation, most object-oriented languages will warn you if you are trying to send a message to an object that will not understand the message. A method defines how a message is to be implemented. It does this by specifying the actions to be performed in response to a receipt of the message. Encapsulation, one of the fundamental principles of an object-oriented language, is a mechanism through which details about the attributes and behaviors described in a class are kept hidden from other objects that send messages to it. In an object-oriented language, the attributes and the behavior that manipulates it are grouped into an object. This object that is defined becomes the device which supports encapsulation. Inheritance is the ability of a class to inherit or derive attributes and behaviors from another class. The new class which derives its properties from a pre-existing class is called a child class, while the preexisting class is known as parent class. Apart from inheriting the attributes and behaviors of the parent class, the child class can have its own attributes and behaviors. Inheritance helps you in identifying and organizing your classes into some hierarchical classification. Inheritance is one of the fundamental principles of object-oriented programming. It considerably reduces development time, promotes reuse and also improves maintainability of the code. Polymorphism is the ability to assign different usages to an entity under different contexts. In objectoriented programming, this ability allows you to create a grouping of the objects, send the same message to different objects in the hierarchy, and have the objects determine which behavior can be used to respond to the message in the hierarchy. Polymorphism can be categorized as compile time

polymorphism and runtime polymorphism. If the call to a function is resolved at compile time, then it is called compile time polymorphism whereas if the call to a function is not resolved until execution, then it is called runtime polymorphism. In C++, compile time polymorphism is implemented by overloading operators and functions while runtime polymorphism is implemented by inheritance and virtual functions. Abstraction is the process of developing a simple representation of a complex object. It represents the vital properties of the object and hides the less important ones. An object-oriented solution to a programming task is developed in a different manner than a procedure-oriented solution. Object-oriented solutions involve five steps. The toughest and the first step is to define the objects in a solution. The objects in your solution are the things that you would manipulate in real life in order to accomplish the task. This is followed by defining the messages to which those objects should respond and then defining the properties of the objects. A sequence of expressions for a high-level solution to the problem are then developed. Finally, the design is implemented and refined. Object behavior analysis is a technique that helps in determining the requirements for an objectoriented application and serves as a useful reminder or checklist when developing prototypes. Object behavior analysis involves an iterative, four-step process. Understand the application, derive objects, categorize objects, model process flow

The Software Development Life Cycle (SDLC) is an iterative process of software development consisting of six phases: 1. During the analysis phase, you will study the feasibility and scope of the project. 2. In the design phase, you will plan the flow of work. 3. In the coding phase, you will write the program code based on the accepted design and build the required technical architecture and databases. 4. In the testing phase, you will check whether the developed software application is working as desired. 5. During the integration phase, you will make the developed software available in the market. 6. In the maintenance and extension phase, you will provide troubleshooting and help desk services to support the system users. A class is a container element that is declared, and it defines a template containing variables and functions. It begins with the keyword class and contains attributes and functions within braces to delimit

the start and end of the class. A class definition typically has a name indicative of its use, and it should end with a semicolon. A class consists of members, such as variables and functions. Variables define the properties or the characteristics of the class and are known as data members. The functions define the behavior of the class and are known as member functions. Class members can have modifiers, such as private, protected, or public to define their scope. It is general practice to interact with classes using their behaviors, so variables are set as private and functions as public. This ensures that the data members of a class are accessed only through their member functions, which is known as data encapsulation or data hiding. If the definition of your class functions is very long, you can define it outside the class. In order to associate a function defined outside the class with the class, you must use the scope resolution operator (::) in the function definition. To associate the member function with the class, place the class name and the scope resolution operator before the function name. You must have the prototype of the function declared within the class and the function definition outside the class. Because the prototype was declared within the class definition, it is already implicitly associated with the class. Void emp::setinfo() An object is a component of a program that is created from a class to hold unique data values. It is a self-contained item declared from a class as an instance of that class, and shares the members defined within that class. You can create an object by specifying the class name followed by the object name. Any member of a class can be accessed from outside the class using an object by specifying the object name, followed by the dot operator (.) and then by the member name. If a public member function needs to access a private data member of the object, the private member can be accessed directly by using the member name. The objectName.variableName syntax is not required in this scenario. Emp e1, e2; e1.display() The this pointer is a hidden pointer variable used by member functions to point to the current object. The address of the current object of a class is passed to the member functions as a hidden argument. Use the this pointer within any member function to reference the address of an object's member by specifying the this pointer followed by the arrow (->) operator, then by the member name. Return this->empname; This->setempname(name); The new operator returns as a pointer the address of the memory location of the newly created object. You can declare a variable of the type pointer to an object by inserting an asterisk between the class

name and the object name. If you have created an object dynamically using new, then you need to use the arrow operator to access the public members of the class through a pointer. Emp *j; j->dieplay(); A friend function is a function that can access the private and protected members of the class to which it is designated as a friend. A function can be declared as a friend function by including its function declaration within the class and prefixing the keyword friend to the function declaration. Both nonmember functions and member functions of other classes can be declared as friend functions. A function can be a friend to any number of classes. Friend double vik(){} A friend class is a class that can access the private and the protected members of the class to which it is designated as a friend. You can designate a class as a friend class within the class declaration by specifying the keyword friend, followed by the keyword class and then the class name. All the member functions of a friend class can have access to the private members of the class to which they are designated as a friend. Friend class localclass; Each time a function is called, the arguments are pushed onto the stack. After the function returns a value, the arguments from the stack are restored. This consumes more time and reduces the efficiency of programs.C++ allows you to define small functions as inline functions. The inline qualifier is used to define a function as inline. The qualifier directs the compiler to replace all calls to the function with the actual code of the function.This is most useful when the function to be made, inline, is only a few lines long.

A static data member is a data member of a class that holds just one copy of the data shared by all the objects of a class. You can declare any data member as a static data member by using the modifier static. The static data member can exist even before an object of a class is created and hence is considered as part of the class and not as part of an object. Declaring a static data member in a class does not allocate space in the memory. You must define it somewhere outside the class using the scope resolution operator. By default, all static data members are initialized to zero by the compiler. Static int vik; Int person::vik=5; A static member function is a member function of a class that associates a function with the class and not with any particular object of that class. Similar to the declaration of any static data member, you can declare a member function static by using the modifier static. These static member functions can be

accessed even without declaring an object for the class. You cannot have the same name for the static member function and the non-static member function of the class. To access the static member function, use the class name followed by the scope resolution operator and the static member function name. The static member functions can access only other static member functions and static data members. Static int num(); A constructor is a special member function that is mainly used to initiate the instance of a class and allocate memory for the objects in that class. The name of a constructor should be the same as that of its class. A constructor doesn't have any return type. A class can have any number of constructors and they differ by the number of parameters or by the class type. A constructor is executed when an object is created for its class. If a constructor is not declared in a class, then the objects will have undefined contents without any allocated memory space.

A destructor is a special member function of a class that is used to deallocate memory to free the resources of that class. It is also used when all the references to the objects are removed or the objects are no longer in use. The name of a destructor should be the same as that of the class. A destructor doesn't have any return type and is prefixed by a tilde (~) symbol that can be defined inline or external to the class declaration. When the C++ runtime environment determines that an instance can be deleted, it will implicitly declare a destructor. This will assist in the cleanup of the instances and their members in a class. You can destroy an instance and its members by using an explicit destructor in a class. You can explicitly call the destructor by using the delete operator to destroy the objects that were created with the new operator. Operator overloading is a technique that allows you to overload the usual functional behavior of an operator with your own desired behavior. For example, the plus (+) operator's usual behavior is to add two numbers, but this behavior can be overloaded with a different behavior such as concatenation of two numbers. The main purpose of operator overloading is to make programs clearer by giving special meaning to the commonly used operators. Operators can be overloaded by declaring the function using the operator keyword followed by a symbol, such as +, =, or = =, and the arguments within braces. You can overload any of the unary, binary, arithmetic and assignment operators in a class. An operator function is any overloaded operator that can be either a member of a class or that takes at least one argument of a class type or its reference. An operator function is distinguished by the number and types of operands that are used with the operator. C++ allows you to define your own meaning to the standard operators when they are used with class types. The return data type for an operator function depends on the specific operation that is invoked. In C++, the right-shift (>>) and left-shift (<<) operators are used to perform arithmetic bit shifting of variables. In the runtime environment, the predefined output and input operators are overloaded and are called inserter (<<) and extractor (>>), respectively. They help to create the input and output

streams. The extractor operator applies the value to the input stream and returns a reference. Similarly, the inserter operator applies the value to the output stream and returns a reference. Function overloading is a technique that allows you to define two or more functions with the same name. But these functions should differ either by the number of arguments or by their data types. The compiler will identify the function that is to be called based on the number of arguments and the argument data types. The functions that have the same name and same arguments but different return types cannot be overloaded. C++ allows you to provide default values for the arguments of a function. When default argument values are available, you have the flexibility to call the function with or without parameters. When you make a function call without any argument values, the function takes up default argument values. But if you do specify argument values, the default values are ignored in favor of the specified values. Default arguments can be used when a function contains a lot of arguments and they take up the same values in most instances. The default values are provided with the argument list in the function definition. Constructor overloading is a process by which you can define more than one constructor for a class. But each of these constructors should have a different set of arguments or arguments of different data types. Constructor overloading provides you with the flexibility to initialize different objects using more than one constructor. When you create an object, the appropriate constructor will be called depending on the arguments the object passes. If you define an object without any arguments, then the constructor that does not take any arguments will be called. A copy constructor is a constructor used to create a new object and simultaneously initialize it with values from an existing object. It is mainly used to prevent problems from arising when one object is used to initialize another. Customer info Copydavid(david); Copydavid.display(); Suppose you initialize a new object, B, with values from an existing object, A, a bitwise copy of the object will be performed. In this case, objects A and B will both point to the same memory location in which the values are stored. Now, if you try to free space allocated to both objects, memory allocated to A will be first freed and the complier will then try to free memory allocated to B. Since both point to the same memory location, you may encounter errors.However, using the copy constructor helps you avoid this problem. It causes fresh space to be allocated for the newly created object and then copies the data values from the old object to the new object. process of identifying the proper function to be executed during compile time is called early binding.

Simple inheritance is the ability of a class to inherit or derive the attributes and behaviors of a single parent class. A child class can not only inherit the members of the parent class, but it can also have its

own unique members. The parent class is also known as the base class or superclass and the child class is known as the derived class or subclass. You can declare a base class either as private, public, or protected. If the access specifier for the base class is not declared explicitly, then the access specifier is considered private. The access specifier used for deriving a class provides a clue to the behavior of the members of the base class in the child class. Class checking: ( private or public or protected) newclassname The purpose of using an access specifier for the base class is to restrict access control for the base class members in the derived class. Private: Private to private Public to private Protected to private Public: Private to private Public to public Protected to protected Protected: Private to private Public to protected Protected to protected To initialize an object of the derived class, you must initialize its base class members followed by the derived class members. You can initialize the base class members by calling the base class constructor from the derived class. After initializing the base class members, you can initialize the unique members of the derived class in the derived class constructor. The destructor for a derived class will implicitly call its parent class' destructor to deallocate any members whose definitions reside in the parent class. Thus, your derived class' destructor need only concern itself with cleaning up its own members. Multiple inheritance is the ability to derive a child class from more than one parent class. Having more than one parent class implies that the child class inherits the attributes and behaviors of all its parents. To inherit multiple classes, you need to use not only a comma to separate the list of classes, but also an

access specifier for each of the base classes. The child class may face problems in accessing the members of its parents if they share the same name. The compiler doesn't know which member to call, so it will throw an error message. To avoid this, explicitly call the member of the desired parent using the scope resolution operator. Class manager:public vik,public ram The second and the most serious problem in implementing multiple inheritance is known as the diamond problem where, you have classes B and C inheriting from a common class A. On top of that, add another class, D, which is a child class of both B and C. In this case, in an indirect way, class D would actually contain two copies of the members of class A because classes B and C are derived from A. Since, there are duplicate copies of the same members, class D would have difficulty accessing the members, and there would be compilation errors. You can avoid the diamond problem if you have just one copy of your base class in the farthest derived class. You can achieve this by declaring your base class as virtual when it is inherited by the derived classes. In this case, even though classes B and C are derived from A, they both have only one copy of A and hence duplication is avoided. During initialization, regardless of its position, a virtual base class object gets initialized first followed by nonvirtual class objects. You can initialize a virtual base class object not necessarily by its immediate derived class. It can even be initialized by a derived class object which is farthest down in the class hierarchy. f you have a derived class that inherits all the protected and public members of its base class, you may have to redefine a public member function of the base class in the derived class. In such circumstances, you need to give the derived class permission to re-implement, or override the public member function of the base class without changing the original definition present in the base class. To override a base class member function in the derived class, you must use the same signature as that of the base class member function. When an object of the derived class calls the overridden function, the function in the derived class is executed by overriding the base class function. When an object of the base class calls the same overridden function, the function in the base class is executed by overriding the derived class function. In object-oriented programming, function overriding is one of the features that facilitate polymorphism. A virtual function is a member function that is declared within a base class and re-implemented in the derived class. To declare a virtual function, you must place the virtual keyword in front of the definition of the member function in the base class. When the base class is inherited, the virtual keyword indicates to the compiler that derived classes can supply their own re-implementation of the public member function. The function in the derived class will then override the definition coming from the base class. The actual function call sent to the base and derived classes remains the same. If no specific definition is available in the derived class, the original definition in the base class is used. While re-implementing the member function in the derived class, there is no need to include the virtual keyword in front of the member function.

The behavior of a virtual function is like any other member function of the class, if the virtual function is accessed in the usual manner. However, when virtual functions are accessed through a pointer, their behavior is different. Declaring a base class pointer will enable you to point to an object of a derived class. If the base class contains a virtual function, and the pointer to the base class points to a derived class object, the C++ compiler at runtime will decide which version of the member function to call based on the object type being pointed. If you have more than one derived class, you can execute different versions of the virtual function using a pointer reference of the base class. This behavior of the virtual function supports runtime polymorphism. There may be instances where it is not possible for a base class object to explicitly create the virtual function for its class, or your derived classes must override the virtual function. In such cases, you need to have a special kind of virtual function known as a pure virtual function. A pure virtual function is a virtual function of the base class that typically has a declaration but no definition. That is, this member function acts as a prototype which must be redefined in the derived class. Virtual void show()=0; Late binding is a mechanism that is performed during the execution of a program. It determines the exact implementation of a member function based on its name and the way it is defined, either in the base class or in the derived class. Most often, late binding occurs when you call a member function of the derived class using a pointer reference of the base class. It is also known as dynamic binding. An abstract class is a class that contains at least one pure virtual function and cannot be used directly to create objects. When you implement a polymorphic hierarchy, you may not wish to create an actual instance of the base class of the hierarchy. You can create a class that acts as the base class containing common properties that provides a skeleton structure from which you can derive more than one derived class. In the derived class, you must then provide the definitions of the inherited pure virtual functions of the abstract base class. Only then can you create an object of the derived class. You can use pointers to access derived class objects from the abstract base class. Abstract classes help in implementing the object-oriented concepts of inheritance and polymorphism. An exception is an unexpected condition that can occur from an invalid input, or from an error in programming logic. These exceptions are thrown during program execution. When an exception is encountered, the program fails to execute and displays the errors to the user. Exceptions may be generated by the operating system when it either detects an invalid operation, such as division by zero, or encounters an invalid value. These unexpected conditions must be identified and must be handled by the developer during the development of the program. When an exception is generated, it is thrown to the function that caused the exception. Usually thrown are primitive values integers, strings, or floats or instances of classes. If the developer has not indicated his willingness to handle the exception, it will be passed to the operating system as an uncaught exception.

A developer can handle a runtime exception by enclosing the code that could cause the exception in a try block, which is a set of curly braces, preceded by the try keyword. If a runtime exception occurs within the try block, the control immediately passes to a catch block. The catch block consists of the catch keyword followed by a parenthesized argument that indicates the type of exception that was generated. It is followed by a set of curly braces that encloses the code that handles the exception. The catch block then handles the exception either by throwing the exception to the function that called the current function, or by cleaning up the error caused by the exception.

The throw statement is used to generate an exception and make it available to the catch block. The throw statement consists of the throw keyword followed by the exception that is thrown. The exception will be caught by the catch block only if you enclose the throw statement within the try block or within any function that is called in the try block. Exceptions that are not caught by the current function are handed up the line to the next function on the stack. For example, function A calls B, B calls C, and an error is generated in C. If function C fails to handle the error, the operating system will pass the error to function B, and then to function A, if necessary. Multiple catch blocks can be associated with a single try block, since it could generate multiple exceptions. But every catch block must be able to catch a different type of exception. When an exception is thrown by the try block, the catch blocks that follow the try block are checked in the order in which they appear. The catch block that matches the exception thrown is executed. While handling exceptions that involve both the base class and the derived class, you need to be cautious, since a derived class exception can also be caught by a catch block of the base class. Suppose you place the catch block of a base class above that of the derived class, then the derived class exception will be caught by the base class' catch block. To solve this problem, you need to create an exception hierarchy by placing the catch blocks of the derived classes first followed by that of the base class. The I/O system is designed to work with a variety of devices to interact with the programmer. Even though each device is different, the buffered file system transforms each device into an abstraction. This will facilitate the use of the same function for multiple devices. Also, by using some of the special functions, you can control the input and output and read and write files in a class. A stream is a sequence of bytes flowing between an application and an operating system entity, such as a keyboard, screen, file, or any other object. Streams provide a buffered mechanism for transporting data to, or from, operating system entities. They also provide type-safe input and output at the cost of perhaps having to write many functions to handle different data types. The stream object is predefined in the <stream.h> header file to contain the buffer through which data will move, and various flags will track and format the data going through the stream. The encapsulation features of C++ allow a

developer to hide many low-level data format and transport details behind a familiar object-oriented interface. The I/O streams allow for input and output of data through the use of streams cin and cout, respectively. These streams are automatically opened as soon as a program starts executing. The input stream object cin is followed by the extraction operator (>>) to receive the input from the keyboard. Similarly, the output stream object cout is followed by the insertion operator (<<) to display the output on the monitor. The object cin is an instance of the class _IO_istream_withassign that is associated with the keyboard input at runtime. The objects cout and cerr are instances of the class _IO_ostream_withassign that are associated with the screen output at runtime. Manipulators are functions and flags that are designed to be used in conjunction with the input (>>) and output (<<) operators in order to control the behavior and format of input and output values. The main advantage of using manipulators is that they can be inserted directly into the stream by the program rather than by a separate function call. C++ provides many general manipulators each of which is used for a specific purpose. Setw(int w) field width Right- turn on right flag Setfill(int ch)- set the fill char to ch Flush- flusha stream Flags are member variables of the iostream class and they control the formatting of the data passing through the stream. Flag values are represented by sets of bit patterns, controlled by the setf(), unsetf(), and flags() member functions of the istream and ostream classes. These stream formatting member functions can be used to set and clear individual bits in flags, thereby controlling the formatting of input and output values. Flags are declared as enumerated values within the ios class and they behave like constants. They may be accessed by prefixing the scope resolution operator for the class before the enumerated values. ios::fmtflags f=ios :: showbase | ios::left; C++ provides a list of stream format flags that can be used as arguments for the setf() and unsetf() functions. ios::left- left justified o/p ios::dec , ios::fixed (fixed decimail points) ios::hex, ios::oct, ios::showbase-(displaying base print leading zero for ocol)

Unformatted input and output involve characters, character arrays, or strings that can all be read or written without any interpretation and stored as text buffer. It may be necessary to have the application simply read the characters into an input or output buffer and then process the unfiltered data in the buffer directly. C++ provides three functions that help manage unformatted input and output. Cin.read(mybuffer,mchars)- reads nchars characters into the character buffer mybuffer Cin.gcount- the[integer] number of characters successfully read by the call to cin.read() Cout.write(mybufaddr,nchars)- writes out nchars chars from the buffer starting at the address mybufaddr The fstreambase class is a file stream base class that encapsulates a file's opening, manipulation, and closing behavior. It provides common functions for the fstream, ifstream, and ofstream classes that are derived from it. fstreambase class constructors take a mode argument, which specifies whether a file is going to be opened either for input or for output. Mode values determine how the file is opened. They are contained in a list defined by the ios class. Fstream fin( saved.txt ,ios::in); Fstream fout( call.txt ,ios::out); When the fstreambase class is combined with the input stream class through inheritance, a class called ifstream is generated, which provides stream-based input from a file. Using multiple inheritance, the ifstream class can be applied to a file so that you can open and read from the file just as if it were standard input. When the fstreambase class is combined with the output stream class, a class called ofstream is generated, which provides stream-based output. This stream-based output class can then be associated with a file for output. The fin and fout objects are arbitrary names assigned by a programmer that represent the objects of the ifstream and ofstream classes, respectively. Using fin or fout in conjunction with one or more member functions of the ifstream and ofstream classes, you can perform various functions that help read data in a file or write data to it, open and close a file, and also check whether a file is open or closed. Ifstream fin( saved.txt ,ios::in) Ofstream fout( call.txt ,ios::out); The sscanf() function is a general purpose input function that reads data from an array and stores the information in the variables pointed to by the function's argument list. The control string pointed to by one of the function's arguments consists of input format specifiers and white-space and non-whitespace characters. Input format specifiers begin with a % (percent) sign and tell the sscanf() function

what type of data is to be read next. The white-space character causes the function to skip one or more white-space characters, while the non-white-space character causes the function to read and discard a matching character in the input stream. Sscanf(Strings, %[^],%d%[^] ,name,phone,profession,&aincome); The getline() function is a member of the input stream class that performs the input operation by reading the characters into an array pointed to by the function's first argument until either the second argument minus one character is reached or the end of the file is encountered. Another form of this function is that it reads characters into an array pointed to by its first argument until either the second argument minus one character is reached, the character specified by the delimiter is found, or the end of the file is encountered. Fin.getline(Strings,80)) or fin.getline(Strings,80, : ); n C++, the I/O system manages the get and put pointers associated with a file. The get and put pointers specify where in the file the next input or output operation will occur. These input and output operations are usually performed sequentially. However, by using the seekg() and seekp() functions, you can enable random access to a file in a nonsequential manner. The seekg() function is used with input streams, while the seekp() function is used with output streams. You can determine the current position of the get and put pointers in a stream by using the tellg() and tellp() functions. The tellg() function is used with input streams to determine the position of the get pointer, while the tellp() function is used with output streams to determine the position of the put po Ifstream ifs; Len=ifs.tellg(); Ofstream ofs; Position=fileout.tellp(); The get() function, a member of the istream class, reads characters from an input stream and returns a reference to the stream. Similarly, the put() function, a member of the ostream class, writes characters to the associated output stream and returns a reference to the stream. A template function is a generic function that can perform the same set of tasks using different types of data passed as arguments. Suppose you define a template function for computing the sum of three numbers. This function can calculate the sum of the numbers no matter that they are of the integer data type or float data type. The data type that will be used by the function is passed as an argument to the function. The data type of the argument will be declared at compile time, not during the template function definition. A template class is a class containing a generic algorithm that enables you to use different types of data passed as arguments. The type of data that will be manipulated by the class is passed as an argument to

the class during object creation. Suppose you need to perform the same kind of manipulation on two different sets of data, each with a different data type. To do that, you might be required to create two separate classes to handle this. In such scenarios, you can create a template class which can handle both types of data and thereby avoid a lot of unnecessary code. template <class T> return type function name(T arg1, data type arg2, data type arg3.....); template <class T> class class name {

//body of the class Template overloading is a technique that allows you to define a specific version of the template function with the same name as that of the template function. This specialized version will override the template function during compilation. Suppose there exists a template function named customer with an argument of the placeholder data type, and you define another function with the same name as customer with an argument of the char data type. When the customer function is called by passing an argument of the char data type, then the specialized version of the customer function will be called, thereby overriding the template function. If the customer function is called by passing an argument of the int data type, then the template function will be called. 1) Identify the purpose for which you would like to create the specific version of the template function. 2) Declare the specialized function with the same name as the template function. Identify the arguments in the template function that are of the placeholder data type. Then specify a data type of your choice for the corresponding arguments in the specialized function. return type function name(data type arg1, data type arg2,..); 3) Define the specialized function that overloads the template function. return type function name(data type arg1, data type arg2, data type arg3.....) { // body of function } Templates enable you to create many blocks of reusable code. A library of templates provides you with general-purpose, templatized classes and functions that help implement commonly used algorithms and data structures. The Standard Template Library (STL) contains some foundational items, which work in conjunction with one another to offer solutions to a variety of programming problems.

The Standard Template Library, or STL, is a pre-written, debugged library of code, consisting of algorithms, containers, and iterators. The templates in the STL help implement common computing constructs, such as stacks, vectors, lists, and queues, in other classes. The STL is designed to be portable across operating systems, so code written using the STL can be compiled in any modern C++ compiler. Containers are classes, such as vectors, lists, and maps, that are designed to hold other objects. Each container class defines a set of functions that may be applied exclusively to the container. There are two categories of containers in STL, namely, sequence containers, designed for sequential access, and associative containers, designed for random access based on key values. Algorithms are function templates that work with container values of any type and provide the means by which you can manipulate the contents of a container. While containers provide support for their own basic operations, such as adding or removing elements, algorithms provide extended and complex actions such as initialization, sorting, searching, and transforming contents of a container. Most algorithms act either on a range of elements within a container or on any two containers at the same time. To use algorithms, you need to include the <algorithm> header file in your programs. Iterators are objects that give you the ability to cycle through the contents of a container, just as pointers that cycle through the contents of an array. They can be both incremented and decremented. Iterators are declared using the iterator type defined by various containers. To use them, you need to include the <iterator> header file in your programs. There are five types of iterators available in the STL. Random access stores and retrieves values randomly Bidirectional- stores and retrieves values fwd and bwd Forward- stores and retrieves values fwd Input-retrieves but no storing of values Output- store no retrieve A vector class is a container class that stores data in a dynamic array. A vector behaves the same way as an array, but is more powerful than the standard C++ array. The size of the standard array is fixed at the time of compilation, but a vector array can grow as needed because it can hold an infinite number of elements. This robustness is what makes it more desirable and safer to use than the standard C++ array. A list class is a container class that supports a bidirectional, linear list of elements. Lists can be accessed sequentially and since they are bidirectional, they can also be accessed front to back or back to front.

A map is an associative container class in which unique keys are mapped with values. The keys are the names you give to a value and, once the values are sorted, you can retrieve them by using their respective keys. The map template accepts two parameters, one for the key and one for the value.

You might also like