dsa assignment (2)

Upload: rajesh-kumar

Post on 03-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 DSA Assignment (2)

    1/51

    Basic concepts of OOPS and Structure of C++ program

    In this tutorial you will learn about Objects, Classes, Inheritance, Data Abstraction, DataEncapsulation, Polymorphism, Overloading, and Reusability.

    Before starting to learn C++ it is essential to have a basic knowledge of the concepts of Object

    oriented programming. Some of the important object oriented features are namely:

    Objects

    Classes

    Inheritance

    Data Abstraction

    Data Encapsulation

    Polymorphism

    Overloading

    Reusability

    In order to understand the basic concepts in C++, a programmer must have a good knowledge ofthe basic terminology in object-oriented programming. Below is a brief outline of the concepts of

    object-oriented programming languages :

    Objects:

    Object is the basic unit of object-oriented programming. Objects are identified by its unique

    name. An object represents a particular instance of a class. There can be more than one instanceof a class. Each instance of a class can hold its own relevant data.

  • 7/28/2019 DSA Assignment (2)

    2/51

    An Object is a collection of data members and associated member functions also known as

    methods.

    Classes:

    Classes are data types based on which objects are created. Objects with similar properties andmethods are grouped together to form a Class. Thus a Class represents a set of individual objects.

    Characteristics of an object are represented in a class as Properties. The actions that can be

    performed by objects become functions of the class and are referred to as Methods.

    For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR

    represents individual Objects. In this context each Car Object will have its own, Model, Year of

    Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class andthe associated actions i.e., object functions like Start, Move, and Stop form the Methods of Car

    Class.

    No memory is allocated when a class is created. Memory is allocated only when an object iscreated, i.e., when an instance of a class is created.

    Inheritance:

    Inheritance is the process of forming a new class from an existing class or base class. The baseclass is also known as parent class or super class. The new class that is formed is called derived

    class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the

    overall code size of the program, which is an important concept in object-oriented programming.

    Data Abstraction:

    Data Abstraction increases the power of programming language by creating user defined datatypes. Data Abstraction also represents the needed information in the program without presenting

    the details.

    Data Encapsulation:

    Data Encapsulation combines data and functions into a single unit called Class. When using Data

    Encapsulation, data is not accessed directly; it is only accessible through the functions presentinside the class. Data Encapsulation enables the important concept of data hiding possible.

    Polymorphism:

    Polymorphism allows routines to use variables of different types at different times. An operator

    or function can be given different meanings or functions. Polymorphism refers to a single

    function or multi-functioning operator performing in different ways.

    Overloading:

  • 7/28/2019 DSA Assignment (2)

    3/51

    Overloading is one type of Polymorphism. It allows an object to have different meanings,

    depending on its context. When an existing operator or function begins to operate on new data

    type, or class, it is understood to be overloaded.

    Reusability:

    This term refers to the ability for multiple programmers to use the same written and debugged

    existing class of data. This is a time saving device and adds code efficiency to the language.

    Additionally, the programmer can incorporate new features to the existing class, further

    developing the application and allowing users to achieve increased performance. This timesaving feature optimizes code, helps in gaining secured applications and facilitates easier

    maintenance on the application.

    The implementation of each of the above object-oriented programming features for C++ will be

    highlighted in later sections.

    A sample program to understand the basic structure of C++

    Sample Code

    1.2. //program to read employee details and to output the data3.4. ////////// code begins here /////////////////////////////5. #include < iostream > // Preprocessor directive6. using namespace std;7. class employee // Class Declaration8. {9. private:10. char empname[50];

    11. int empno;12.13.public:14. void getvalue()15. {16. coutempname; // waiting input

    from the Keyboard for the name18. coutempno; // waiting

    input from the Keyboard for the number20. }21. void displayvalue(){22. cout

  • 7/28/2019 DSA Assignment (2)

    4/51

    Copyright exforsys.com

    Output:

  • 7/28/2019 DSA Assignment (2)

    5/51

    C++ Comments

    A comment is text that the compiler ignores but that is useful for programmers. Comments

    are normally used to explain code for future reference. The compiler treats them as white

    space. You can use comments in testing to make certain lines of code inactive;

    A C++ comment is written in one of the following ways:

    The /* (slash, asterisk) characters, followed by any sequence of characters

    (including new lines), followed by the */ characters. This syntax is the same as ANSI

    C.

    The // (two slashes) characters, followed by any sequence of characters. A new line

    not immediately preceded by a backslash terminates this form of comment.Therefore, it is commonly called a "single-line comment."

    The comment characters (/*, */, and //) have no special meaning within a character

    constant, string literal, or comment. Comments using the first syntax, therefore, cannot be

    nested.

    Types of Comments

    C++ comments come in two flavors: the double-slash (//) comment, and the slash-star (/*)

    comment. The double-slash comment, which will be referred to as a C++-style comment,

    tells the compiler to ignore everything that follows this comment, until the end of the line.

    The slash-star comment mark tells the compiler to ignore everything that follows until it

    finds a star-slash (*/) comment mark. These marks will be referred to as C-style comments.

    Every /* must be matched with a closing */.

    HELP.CPP demonstrates comments.

    1: #include 2:3: int main()4: {

    5: /* this is a comment6: and it extends until the closing7: star-slash comment mark */8: cout

  • 7/28/2019 DSA Assignment (2)

    6/51

    15: }Hello World!That comment ended!

  • 7/28/2019 DSA Assignment (2)

    7/51

    Constants

    Constants are expressions with a fixed value.

    Literals

    Literals are the most obvious kind of constants. They are used to express particular values within the

    source code of a program. We have already used these previously to give concrete values to variables

    or to express messages we wanted our programs to print out, for example, when we wrote:

    a = 5;

    the 5 in this piece of code was a literal constant.

    Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and

    Boolean Values.

    Integer Numerals

    123

    1776707-273

    They are numerical constants that identify integer decimal values. Notice that to express a numerical

    constant we do not have to write quotes (") nor any special character. There is no doubt that it is a

    constant: whenever we write 1776 in a program, we will be referring to the value 1776.

    In addition to decimal numbers (those that all of us are used to using every day), C++ allows the use of

    octal numbers (base 8) and hexadecimal numbers (base 16) as literal constants. If we want to expressan octal number we have to precede it with a 0 (azero character). And in order to express a

    hexadecimal number we have to precede it with the characters 0x (zero,x). For example, the

    following literal constants are all equivalent to each other:

    123

    75 // decimal0113 // octal0x4b // hexadecimal

  • 7/28/2019 DSA Assignment (2)

    8/51

    All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal

    numeral and hexadecimal numeral, respectively.

    Literal constants, like variables, are considered to have a specific data type. By default, integer literals

    are of type int. However, we can force them to either be unsigned by appending the u character to it,

    or long by appending l:

    1234

    75 // int75u // unsigned int75l // long75ul // unsigned long

    In both cases, the suffix can be specified using either upper or lowercase letters.

    Floating Point Numbers

    They express numbers with decimals and/or exponents. They can include either a decimal point, an e

    character (that expresses "by ten at the Xth height", where X is an integer value that follows the e

    character), or both a decimal point and an e character:

    1234

    3.14159 // 3.141596.02e23 // 6.02 x 10^231.6e-19 // 1.6 x 10^-193.0 // 3.0

    These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is

    the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -

    all of them approximated- and the last one is the number three expressed as a floating-point numeric

    literal.

    The default type for floating point literals is double. If you explicitly want to express afloator a long

    double numerical literal, you can use the f or l suffixes respectively:

    1

    2

    3.14159L // long double

    6.02e23f // float

    Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using

    either lower or uppercase letters without any difference in their meanings.

    Character and string literals

    There also exist non-numerical constants, like:

  • 7/28/2019 DSA Assignment (2)

    9/51

    1234

    'z''p'"Hello world""How do you do?"

    The first two expressions represent single character constants, and the following two represent string

    literals composed of several characters. Notice that to represent a single character we enclose it

    between single quotes (') and to express a string (which generally consists of more than one

    character) we enclose it between double quotes (").

    When writing both single character and string literals, it is necessary to put the quotation marks

    surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice

    the difference between these two expressions:

    1

    2

    x

    'x'

    x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation

    marks) would refer to the character constant 'x'.

    Character and string literals have certain peculiarities, like the escape codes. These are special

    characters that are difficult or impossible to express otherwise in the source code of a program, like

    newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of

    such escape codes:

    \nNewline

    \rcarriage return

    \tTab

    \vvertical tab

    \bBackspace

    \fform feed (page feed)

    \aalert (beep)

    \'single quote (')

  • 7/28/2019 DSA Assignment (2)

    10/51

    \"double quote (")

    \?question mark (?)

    \\backslash (\)

    For example:

    1234

    '\n''\t'"Left \t Right""one\ntwo\nthree"

    Additionally, you can express any character by its numerical ASCII code by writing a backslash

    character (\) followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16)number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or

    \40), in the second case (hexadecimal), an x character must be written before the digits themselves

    (for example \x20 or \x4A).

    String literals can extend to more than a single line of code by putting a backslash sign (\) at the end

    of each unfinished line.

    12"string expressed in \two lines"

    You can also concatenate several string constants separating them by one or several blank spaces,

    tabulators, newline or any other valid blank character:

    "this forms" "a single" "string" "of characters"

    Finally, if we want the string literal to be explicitly made of wide characters (wchar_ttype), instead of

    narrow characters (chartype), we can precede the constant with the L prefix:

    L"This is a wide character string"

    Wide characters are used mainly to represent non-English or exotic character sets.

  • 7/28/2019 DSA Assignment (2)

    11/51

    Boolean literals

    There are only two valid Boolean values: true andfalse. These can be expressed in C++ as values of

    type boolby using the Boolean literals true and false.

    Constant Values

    The const keyword specifies that a variable's value is constant and tells the compiler to

    prevent the programmer from modifying it.

    // constant_values1.cppint main() {

    const int i = 5;i = 10; // C3892i++; // C2105

    }

    In C++, you can use the const keyword instead of the #define preprocessor directive to

    define constant values. Values defined with const are subject to type checking, and can be

    used in place of constant expressions. In C++, you can specify the size of an array with a

    const variable as follows:

    // constant_values2.cpp// compile with: /cconst int maxarray = 255;char store_char[maxarray]; // allowed in C++; not allowed in C

    In C, constant values default to external linkage, so they can appear only in source files. In

    C++, constant values default to internal linkage, which allows them to appear in header

    files.

    The const keyword can also be used in pointer declarations.

    // constant_values3.cppint main() {

    char *mybuf = 0, *yourbuf;char *const aptr = mybuf;*aptr = 'a'; // OKaptr = yourbuf; // C3892

    }

    http://msdn.microsoft.com/en-us/library/teas0593%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/teas0593%28v=vs.80%29.aspx
  • 7/28/2019 DSA Assignment (2)

    12/51

    A pointer to a variable declared as const can be assigned only to a pointer that is also

    declared as const.

    // constant_values4.cpp#include int main() {

    const char *mybuf = "test";char *yourbuf = "test2";printf_s("%s\n", mybuf);

    const char *bptr = mybuf; // Pointer to constant dataprintf_s("%s\n", bptr);

    // *bptr = 'a'; // Error}

    Output

    testtest

    You can use pointers to constant data as function parameters to prevent the function from

    modifying a parameter passed through a pointer.

    For objects that are declared as const, you can only call constant member functions. This

    ensures that the constant object is never modified.

    birthday.getMonth(); // Okaybirthday.setMonth( 4 ); // Error

    You can call either constant or nonconstant member functions for a nonconstant object.

    You can also overload a member function using the const keyword; this allows a different

    version of the function to be called for constant and nonconstant objects.

    You cannot declare constructors or destructors with the const keyword.

    C and C++ const Differences

    When you declare a variable as const in a C source code file, you do so as:

    const int i = 2;

    You can then use this variable in another module as follows:

    extern const int i;

    But to get the same behavior in C++, you must declare your const variable as:

    extern const int i = 2;

    http://void%280%29/http://msdn.microsoft.com/en-us/library/6ke686zh%28v=vs.80%29.aspxhttp://msdn.microsoft.com/en-us/library/6ke686zh%28v=vs.80%29.aspxhttp://void%280%29/
  • 7/28/2019 DSA Assignment (2)

    13/51

    If you wish to declare an extern variable in a C++ source code file for use in a C source

    code file, use:

    extern "C" const int x=10;

    to prevent name mangling by the C++ compiler.

    Defined constants (#define)

    You can define your own names for constants that you use very often without having to resort to

    memory-consuming variables, simply by using the #define preprocessor directive. Its format is:

    #define identifier value

    For example:

    12#define PI 3.14159#define NEWLINE '\n'

    This defines two new constants: PIand NEWLINE. Once they are defined, you can use them in the rest

    of the code as if they were any other regular constant, for example:

    12

    345678910111213141516171819

    // defined constants: calculate circumference

    #include usingnamespace std;

    #define PI 3.14159#define NEWLINE '\n'

    int main (){double r=5.0; // radiusdouble circle;

    circle = 2 * PI * r;cout

  • 7/28/2019 DSA Assignment (2)

    14/51

    NEWLINE) by the code to which they have been defined (3.14159 and '\n' respectively).

    The #define directive is not a C++ statement but a directive for the preprocessor; therefore it

    assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append

    a semicolon character (;) at the end, it will also be appended in all occurrences of the identifier within

    the body of the program that the preprocessor replaces.

    Declared constants (const)

    With the const prefix you can declare constants with a specific type in the same way as you would do

    with a variable:

    12constint pathwidth = 100;constchartabulator = '\t';

    Here,pathwidth

    andtabulator

    are two typed constants. They are treated just like regular

    variables except that their values cannot be modified after their definition.

  • 7/28/2019 DSA Assignment (2)

    15/51

    Dynamic Initialization

    Dynamic Initialization refers to initializing a variable at runtime. If you give a C++

    statement as shown below, it refers to static initialization, because you are assigning a

    constant to the variable which can be resolved at compile time.

    Int x = 5;

    Whereas, the following statement is called dynamic initialization, because it cannot beresolved at compile time.

    In x = a * b;

    Initializing x requires the value of a and b. So it can be resolved only during run time.

    Dynamic initialization is mostly used in case of initializing C++ objects.

    Dynamic initialization of objects in c++

    The dynamic initialization means that the initial values may be provided during run time.

    Even class objects can be initialized dynamically. I.e. with the values provided at run time.The following example explains it.

    A Program to find the factorial of an integer using constructor.

    #include

    #include

    Class factorial

    {

    Private:

    Int n;

    Public:Factorial (int number)

    {

    N=number;

    }

    Void display ()

    {

    Int fact=1;

  • 7/28/2019 DSA Assignment (2)

    16/51

    If (n==0)

    Cout

  • 7/28/2019 DSA Assignment (2)

    17/51

    C++ ReferencesC++ references allow you to create a second name for the a variable that you can use to read or

    modify the original data stored in that variable. While this may not sound appealing at first, what this

    means is that when you declare a reference and assign it a variable, it will allow you to treat the

    reference exactly as though it were the original variable for the purpose of accessing and modifying

    the value of the original variable--even if the second name (the reference) is located within a different

    scope. This means, for instance, that if you make your function arguments references, and you will

    effectively have a way to change the original data passed into the function. This is quite different from

    how C++ normally works, where you have arguments to a function copied into new variables. It also

    allows you to dramatically reduce the amount of copying that takes place behind the scenes, both

    with functions and in other areas of C++, like catch clauses.

    Basic Syntax

    Declaring a variable as a reference rather than a normal variable simply entails appending an

    ampersand to the type name, such as this "reference to an int"

    int& foo = ....;

    Did you notice the "...."? (Probably, right? After all, it's 25% of the example.) When a reference is

    created, you must tell it which variable it will become an alias for. After you create the reference,

    whenever you use the variable, you can just treat it as though it were a regular integer variable. But

    when you create it, you must initialize it with another variable, whose address it will keep around

    behind the scenes to allow you to use it to modify that variable.

    In a way, this is similar to having a pointer that always points to the same thing. One key difference is

    that references do not require dereferencing in the same way that pointers do; you just treat them as

    normal variables. A second difference is that when you create a reference to a variable, you need not

    do anything special to get the memory address. The compiler figures this out for you:

    int x;

    int& foo = x;

    // foo is now a reference to x so this sets x to 56foo = 56;std::cout

  • 7/28/2019 DSA Assignment (2)

    18/51

    void swap (int& first, int& second){

    int temp = first;first = second;second = temp;

    }

    Both arguments are passed "by reference"--the caller of the function need not even be aware of it:

    int a = 2;int b = 3;swap( a, b );

    After the swap, a will be 3 and b will be 2. The fact that references require no extra work can lead to

    confusion at times when variables magically change after being passed into a function. Bjarne

    Stroustrup suggests that for arguments that the function is expected to change, using a pointer

    instead of a reference helps make this clear--pointers require that the caller explicitly pass in the

    memory address.

  • 7/28/2019 DSA Assignment (2)

    19/51

    C++ Data Types

    While doing programming in any programming language, you need to use various

    variables to store various information. Variables are nothing but reserved memory

    locations to store values. This means that when you create a variable you reserve some

    space in memory.

    You may like to store information of various data type like character, wide character,

    integer, floating point, double floating point, boolean etc. Based on the data type of avariable, the operating system allocates memory and decides what can be stored in the

    reserved memory.

    Primitive Built-in Types:

    C++ offer the programmer a rich assortment of built-in as well as user defined data types.

    Following table list down seven basic C++ data types:

    Type Keyword

    Boolean bool

    Character char

    Integer int

    Floating point float

    Double floating pointdouble

    Valueless void

    Wide character wchar_t

    Several of the basic types can be modified using one or more of these type modifiers:

    signed

  • 7/28/2019 DSA Assignment (2)

    20/51

    unsigned

    short

    long

    The following table shows the variable type, how much memory it takes to store the value

    memory, and what is maximum and minimum vaue which can be stored in such type ofvariables.

    Type Typical Bit Width Typical Range

    char 1byte -127 to 127 or 0 to 255

    unsigned char 1byte 0 to 255

    signed char 1byte -127 to 127

    int 4bytes -2147483648 to 2147483647

    unsigned int 4bytes 0 to 4294967295

    signed int 4bytes -2147483648 to 2147483647

    short int 2bytes -32768 to 32767

    unsigned short int Range 0 to 65,535

    signed short int Range -32768 to 32767

    long int 4bytes -2,147,483,647 to 2,147,483,647

    signed long int 4bytes same as long int

    unsigned long int 4bytes 0 to 4,294,967,295

    float 4bytes +/- 3.4e +/- 38 (~7 digits)

  • 7/28/2019 DSA Assignment (2)

    21/51

    double 8bytes +/- 1.7e +/- 308 (~15 digits)

    long double 8bytes +/- 1.7e +/- 308 (~15 digits)

    wchar_t 2 or 4 bytes 1 wide character

    The sizes of variables might be different from those shown in the above table, depending on

    the compiler and the computer you are using.

    Following is the example which will produce correct size of various data type on your

    cmputer.

    #include using namespace std;

    int main(){

    cout

  • 7/28/2019 DSA Assignment (2)

    22/51

    typedef type newname;

    For example, the following tells the compiler that feet is another name for int:

    typedef int feet;

    Now, the following declaration is perfectly legal and creates an integer variable called

    distance:

    feet distance;

    Input and Output Statements in C++

    INPUT AND OUTPUT STATEMENTS

    Input (Read ) Statement.

    You learned how to put data into variables using assignment statement .Now you will learn how

    to put data into variables using c++ input statement.

    when the computer gets the data from the keyboard , the user is said to be acting interactively.

    Putting data into variables using cin and the operator>>.The syntax of cin together with >> is

  • 7/28/2019 DSA Assignment (2)

    23/51

    cin>>variable;

    if two variables then

    cin>>variable1>>variable2;

    This is called an input statement. In c++ , >> is called the stream extraction operator.

    By this way for so on variables ...

    suppose that statement.

    int feet;

    int inches;

    then input is

    cin>>feet>>inches;

    Output statements

    In c++ output on standard output device is use cout and the operator

  • 7/28/2019 DSA Assignment (2)

    24/51

    cout

  • 7/28/2019 DSA Assignment (2)

    25/51

    C++ Basic Input/OutputAdvertisements

    Previous Page

    Next Page

    The C++ standard libraries provide an extensive set of input/output capabilities which we willsee in subsequent chapters. This chapter will discuss very basic and most common I/O operationsrequired for C++ programming.

    C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like akeyboard, a disk drive, or a network connection etc. to main memory, this is called input

    operation and if bytes flow from main memory to a device like a display screen, a printer, a disk

    drive, or a network connection, etc, this is called output operation.

    http://www.tutorialspoint.com/cplusplus/cpp_date_time.htmhttp://www.tutorialspoint.com/cplusplus/cpp_data_structures.htmhttp://www.tutorialspoint.com/cplusplus/cpp_data_structures.htmhttp://www.tutorialspoint.com/cplusplus/cpp_date_time.htm
  • 7/28/2019 DSA Assignment (2)

    26/51

    I/O Library Header Files:

    There are following header files important to C++ programs:

    Header File Function and Description

    This file defines the cin, cout, cerr and clog objects, which correspond to the

    standard input stream, the standard output stream, the un-buffered standard error

    stream and the buffered standard error stream, respectively.

    This file declares services useful for performing formatted I/O with so-called

    parameterized stream manipulators, such as setw and setprecision.

    This file declares services for user-controlled file processing. We will discuss about

    it in detail in File and Stream related chapter.

    The standard output stream (cout):

    The predefined object cout is an instance ofostream class. The cout object is said to be"connected to" the standard output device, which usually is the display screen. The cout is used

    in conjunction with the stream insertion operator, which is written as

  • 7/28/2019 DSA Assignment (2)

    27/51

    The standard input stream (cin):

    The predefined object cin is an instance ofistream class. The cin object is said to be attached to

    the standard input device, which usually is the keyboard. The cin is used in conjunction with thestream extraction operator, which is written as >> which are two greater than signs as shown in

    the following example.

    #include

    using namespace std;

    int main( ){

    char name[50];

    cout > name;cout > name >> age;

    This will be equivalent to the following two statements:

    cin >> name;cin >> age;

  • 7/28/2019 DSA Assignment (2)

    28/51

    operators in C++

    Advertisements

    Previous Page

    Next Page

    An operator is a symbol that tells the compiler to perform specific mathematical or logicalmanipulations. C++ is rich in built-in operators and provides following type of operators:

    Arithmetic Operators

    Relational Operators

    Logical Operators

    Bitwise Operators

    Assignment Operators

    Misc Operators

    This chapter will examine the arithmetic, relational, and logical, bitwise, assignment and other

    operators one by one.

    Arithmetic Operators:

    There are following arithmetic operators supported by C++ language:

    Assume variable A holds 10 and variable B holds 20 then:

    Show Examples

    Operator Description Example

    + Adds two operands A + B will give 30

    - Subtracts second operand from the first A - B will give -10

    * Multiply both operands A * B will give 200

    / Divide numerator by de-numerator B / A will give 2

    http://www.tutorialspoint.com/cplusplus/cpp_storage_classes.htmhttp://www.tutorialspoint.com/cplusplus/cpp_loop_types.htmhttp://www.tutorialspoint.com/cplusplus/cpp_arithmatic_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_arithmatic_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_loop_types.htmhttp://www.tutorialspoint.com/cplusplus/cpp_storage_classes.htm
  • 7/28/2019 DSA Assignment (2)

    29/51

    %Modulus Operator and remainder of after an

    integer divisionB % A will give 0

    ++Increment operator, increases integer value

    by oneA++ will give 11

    --Decrement operator, decreases integer value

    by oneA-- will give 9

    Relational Operators:

    There are following relational operators supported by C++ language

    Assume variable A holds 10 and variable B holds 20 then:

    Show Examples

    Operator Description Example

    ==Checks if the value of two operands is equal or

    not, if yes then condition becomes true.(A == B) is not true.

    !=

    Checks if the value of two operands is equal or

    not, if values are not equal then condition

    becomes true.

    (A != B) is true.

    >

    Checks if the value of left operand is greater

    than the value of right operand, if yes then

    condition becomes true.

    (A > B) is not true.

    =

    Checks if the value of left operand is greater

    than or equal to the value of right operand, if

    yes then condition becomes true.

    (A >= B) is not true.

  • 7/28/2019 DSA Assignment (2)

    30/51

    Logical Operators:

    There are following logical operators supported by C++ language

    Assume variable A holds 1 and variable B holds 0 then:

    Show Examples

    Operator Description Example

    &&

    Called Logical AND operator. If both the

    operands are non zero then condition

    becomes true.

    (A && B) is false.

    ||

    Called Logical OR Operator. If any of the two

    operands is non zero then condition becomes

    true.

    (A || B) is true.

    !

    Called Logical NOT Operator. Use to reverses

    the logical state of its operand. If a condition

    is true then Logical NOT operator will make

    false.

    !(A && B) is true.

    Bitwise Operators:

    Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^are as follows:

    pqp & qp | qp ^ q

    000 0 0

    010 1 1

    111 1 0

    100 1 1

    Assume if A = 60; and B = 13; Now in binary format they will be as follows:

    A = 0011 1100

    http://www.tutorialspoint.com/cplusplus/cpp_logical_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_logical_operators.htm
  • 7/28/2019 DSA Assignment (2)

    31/51

    B = 0000 1101

    -----------------

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

    ~A = 1100 0011

    The Bitwise operators supported by C++ language are listed in the following table. Assumevariable A holds 60 and variable B holds 13 then:

    Show Examples

    Operator Description Example

    &Binary AND Operator copies a bit to the result

    if it exists in both operands.(A & B) will give 12 which is 0000 1100

    |Binary OR Operator copies a bit if it exists in

    either operand.(A | B) will give 61 which is 0011 1101

    ^Binary XOR Operator copies the bit if it is set

    in one operand but not both.(A ^ B) will give 49 which is 0011 0001

    ~Binary Ones Complement Operator is unary

    and has the effect of 'flipping' bits.(~A ) will give -60 which is 1100 0011

    > 2 will give 15 which is 0000 1111

    Assignment Operators:

    There are following assignment operators supported by C++ language:

    Show Examples

    http://www.tutorialspoint.com/cplusplus/cpp_bitwise_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_assignment_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_assignment_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_bitwise_operators.htm
  • 7/28/2019 DSA Assignment (2)

    32/51

    Operator Description Example

    =Simple assignment operator, Assigns values

    from right side operands to left side operandC = A + B will assign value of A + B into C

    +=Add AND assignment operator, It adds rightoperand to the left operand and assign the

    result to left operand

    C += A is equivalent to C = C + A

    -=

    Subtract AND assignment operator, It

    subtracts right operand from the left operand

    and assign the result to left operand

    C -= A is equivalent to C = C - A

    *=

    Multiply AND assignment operator, It

    multiplies right operand with the left operand

    and assign the result to left operand

    C *= A is equivalent to C = C * A

    /=

    Divide AND assignment operator, It divides

    left operand with the right operand and assign

    the result to left operand

    C /= A is equivalent to C = C / A

    %=

    Modulus AND assignment operator, It takes

    modulus using two operands and assign the

    result to left operand

    C %= A is equivalent to C = C % A

    > 2

    &= Bitwise AND assignment operator C &= 2 is same as C = C & 2

    ^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

    |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

    Misc Operators

    There are few other operators supported by C++ Language.

    Operator Description

    sizeof sizeof operatorreturns the size of a variable. For example sizeof(a),

    http://www.tutorialspoint.com/cplusplus/cpp_sizeof_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_sizeof_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_sizeof_operator.htm
  • 7/28/2019 DSA Assignment (2)

    33/51

    where a is integer, will return 4.

    Condition ? X : YConditional operator. If Condition is true ? then it returns value X :

    otherwise value Y

    ,Comma operatorcauses a sequence of operations to be performed. Thevalue of the entire comma expression is the value of the last expression

    of the comma-separated list.

    . (dot) and -> (arrow)Member operatorsare used to reference individual members of classes,

    structures, and unions.

    CastCasting operatorsconvert one data type to another. For example,

    int(2.2000) would return 2.

    &Pointer operator &returns the address of an variable. For example &a;

    will give actual address of the variable.

    *Pointer operator *is pointer to a variable. For example *var; will pointer

    to a variable var.

    Operators Precedence in C++:

    Operator precedence determines the grouping of terms in an expression. This affects how anexpression is evaluated. Certain operators have higher precedence than others; for example, the

    multiplication operator has higher precedence than the addition operator:

    For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher

    precedence than + so it first get multiplied with 3*2 and then adds into 7.

    Here operators with the highest precedence appear at the top of the table, those with the lowest

    appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    Show Examples

    Category Operator Associativity

    Postfix() [] -> . ++

    - -Left to right

    Unary + - ! ~ ++ -

    - (type)*

    Right to left

    http://www.tutorialspoint.com/cplusplus/cpp_conditional_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_conditional_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_comma_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_comma_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_member_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_member_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_casting_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_casting_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_operators_precedence.htmhttp://www.tutorialspoint.com/cplusplus/cpp_operators_precedence.htmhttp://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_pointer_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_casting_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_member_operators.htmhttp://www.tutorialspoint.com/cplusplus/cpp_comma_operator.htmhttp://www.tutorialspoint.com/cplusplus/cpp_conditional_operator.htm
  • 7/28/2019 DSA Assignment (2)

    34/51

    & sizeof

    Multiplicative * / % Left to right

    Additive + - Left to right

    Shift > Left to right

    Relational < >= Left to right

    Equality == != Left to right

    Bitwise AND & Left to right

    Bitwise XOR ^ Left to right

    Bitwise OR | Left to right

    Logical AND && Left to right

    Logical OR || Left to right

    Conditional ?: Right to left

    Assignment

    = += -= *=

    /= %=>>=

  • 7/28/2019 DSA Assignment (2)

    35/51

    Control StructuresA program is usually not limited to a linear sequence of instructions. During its

    process it may bifurcate, repeat code or take decisions. For that purpose, C++

    provides control structures that serve to specify what has to be done by our

    program, when and under which circumstances.

    With the introduction of control structures we are going to have to introduce a

    new concept: the compound-statementor block. A block is a group of

    statements which are separated by semicolons (;) like all C++ statements, but

    grouped together in a block enclosed in braces: { }:

    { statement1; statement2; statement3; }

    Most of the control structures that we will see in this section require a generic

    statement as part of its syntax. A statement can be either a simple statement

    (a simple instruction ending with a semicolon) or a compound statement

    (several instructions grouped in a block), like the one just described. In the

    case that we want the statement to be a simple statement, we do not need to

    enclose it in braces ({}). But in the case that we want the statement to be a

    compound statement it must be enclosed between braces ({}

    ), forming a

    block.

    Conditional structure: if and else

    The if keyword is used to execute a statement or block only if a condition is

    fulfilled. Its form is:

    if (condition) statement

    Where condition is the expression that is being evaluated. If this condition is

    true, statement is executed. If it is false, statement is ignored (not

    executed) and the program continues right after this conditional structure.

    For example, the following code fragment prints x is 100 only if the value

    stored in the x variable is indeed 100:

    12if(x == 100)

    cout

  • 7/28/2019 DSA Assignment (2)

    36/51

    If we want more than a single statement to be executed in case that the

    condition is true we can specify a block using braces { }:

    1

    2345

    if(x == 100)

    {cout

  • 7/28/2019 DSA Assignment (2)

    37/51

    while a condition is fulfilled.

    The while loop

    Its format is:

    while (expression) statement

    and its functionality is simply to repeat statement while the condition set in

    expression is true.

    For example, we are going to make a program to countdown using a while-

    loop:

    1234

    567891011121314151617

    1819

    // custom countdown using while

    #include usingnamespace std;

    int main (){int n;cout > n;

    while (n>0) {cout 0) remains

    being true.

    The whole process of the previous program can be interpreted according tothe following script (beginning in main):

    1. User assigns a value to n

    2. The while condition is checked (n>0). At this point there are two

    possibilities:

    * condition is true: statement is executed (to step 3)

    * condition is false: ignore statement and continue after it (to step 5)

  • 7/28/2019 DSA Assignment (2)

    38/51

    3. Execute statement:cout > n;

    Enter number (0 toend): 12345You entered: 12345Enter number (0 toend): 160277You entered: 160277Enter number (0 toend): 0You entered: 0

  • 7/28/2019 DSA Assignment (2)

    39/51

    131415

    cout

  • 7/28/2019 DSA Assignment (2)

    40/51

    891011

    ) {cout

  • 7/28/2019 DSA Assignment (2)

    41/51

    Using break we can leave a loop even if the condition for its end is not

    fulfilled. It can be used to end an infinite loop, or to force it to end before its

    natural end. For example, we are going to stop the count down before its

    natural end (maybe because of an engine check failure?):

    12345678910111213

    141516171819

    // break loop example

    #include usingnamespace std;

    int main (){int n;for(n=10; n>0; n--){cout

  • 7/28/2019 DSA Assignment (2)

    42/51

    goto allows to make an absolute jump to another point in the program. You

    should use this feature with caution since its execution causes an

    unconditional jump ignoring any type of nesting limitations.

    The destination point is identified by a label, which is then used as an

    argument for the goto statement. A label is made of a valid identifier followed

    by a colon (:).

    Generally speaking, this instruction has no concrete use in structured or object

    oriented programming aside from those that low-level programming fans may

    find for it. For example, here is our countdown loop using goto:

    123456789101112131415

    // goto loop example

    #include usingnamespace std;

    int main (){int n=10;loop:cout

  • 7/28/2019 DSA Assignment (2)

    43/51

    several possible constant values for an expression. Something similar to what

    we did at the beginning of this section with the concatenation of several if

    and else if instructions. Its form is the following:

    switch (expression)

    { case constant1:group of statements 1;break;

    case constant2:group of statements 2;break;

    .

    .

    .default:

    default group of statements}

    It works in the following way: switch evaluates expression and checks if it is

    equivalent to constant1, if it is, it executes group of statements 1 until

    it finds the break statement. When it finds this break statement the program

    jumps to the end of the switch selective structure.

    If expression was not equal to constant1 it will be checked against

    constant2. If it is equal to this, it will execute group of statements 2

    until a break keyword is found, and then will jump to the end of the switch

    selective structure.

    Finally, if the value ofexpression did not match any of the previously

    specified constants (you can include as many case labels as values you want

    to check), the program will execute the statements included after the

    default: label, if it exists (since it is optional).

    Both of the following code fragments have the same behavior:

    switch example if-else equivalent

    switch (x) {

    case 1:cout

  • 7/28/2019 DSA Assignment (2)

    44/51

    }

    The switch statement is a bit peculiar within the C++ language because it

    uses labels instead of blocks. This forces us to put break statements after the

    group of statements that we want to be executed for a specific condition.

    Otherwise the remainder statements -including those corresponding to other

    labels- will also be executed until the end of theswitch selective block or a

    break statement is reached.

    For example, if we did not include a break statement after the first group for

    case one, the program will not automatically jump to the end of the switch

    selective block and it would continue executing the rest of statements until it

    reaches either a break instruction or the end of the switch selective block.

    This makes it unnecessary to include braces { } surrounding the statements

    for each of the cases, and it can also be useful to execute the same block of

    instructions for different possible values for the expression being evaluated.

    For example:

    123456789

    switch (x) {case 1:case 2:case 3:cout

  • 7/28/2019 DSA Assignment (2)

    45/51

    Parameter Passing

    Parameter passing methods are the ways in which parameters are transfered between functions

    when one function calls another. C++ provides two parameter passing methods--pass-by-

    value andpass-by-reference .

    Pass By Value

    Consider a pair of C++ functions defined in Program . The function One calls the function Two.

    In general, every function call includes a (possibly empty) list of arguments. The arguments

    specified in a function call are called actual parameters . In this case, there is only one actual

    parameter--y.

    Program: Example of Pass-By-Value Parameter Passing

    The method by which the parameter is passed to a function is determined by the functiondefinition. In this case, the function Two is defined as accepting a single argument of type int

    called x. The arguments which appear in a function definition are calledformal parameters . If

    the type of a formal parameter is nota reference (see Section ), then the parameter passingmethod ispass-by-value.

    The semantics of pass-by-value work like this: The effect of the formal parameter definition is to

    create a local variable of the specified type in the given function. E.g., the function Two has a

    http://www.brpreiss.com/books/opus4/html/page590.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page590.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page590.htmlhttp://www.brpreiss.com/books/opus4/html/page592.html
  • 7/28/2019 DSA Assignment (2)

    46/51

    local variable of type int called x. When the function is called, the values (r-values) of theactual parameters are used to initialize theformal parameters before the body of the function isexecuted.

    Since the formal parameters give rise to local variables, if a new value is assigned to a formal

    parameter, that value has no effect on the actual parameters. Therefore, the output obtainedproduced by the function One defined in Program is:

    21

    Pass By Reference

    Consider the pair of C++ functions defined in Program . The only difference between thiscode and the code given in Program is the definition of the formal parameter of the function

    Two: In this case, the parameterx is declared to be a reference to an int. In general, if the type ofa formal parameter is a reference, then the parameter passing method ispass-by-reference .

    Program: Example of Pass-By-Reference Parameter Passing

    A reference formal parameter is not a variable. When a function is called that has a referenceformal parameter, the effect of the call is to associate the reference with the corresponding actual

    parameter. I.e., the reference becomes an alternative name for the corresponding actual

    parameter. Consequently, this means that the actual parameter passed by reference must bevariable.

    A reference formal parameter can be used in the called function everywhere that a variable canbe used. In particular, if the reference formal parameter is used where a r-value is required, it is

    http://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page593.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page593.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page593.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page592.htmlhttp://www.brpreiss.com/books/opus4/html/page593.htmlhttp://www.brpreiss.com/books/opus4/html/page592.html
  • 7/28/2019 DSA Assignment (2)

    47/51

    the r-value of actual parameter that is obtained. Similarly, if the reference parameter is used

    where an l-value is required, it is the l-value of actual parameter that is obtained. Therefore, the

    output obtained produced by the function One defined in Program is:

    22

    Template (C++)

    From Wikipedia, the free encyclopedia

    Jump to:navigation,search

    This article has multiple issues. Please helpimprove itor discuss these issues on thetalk page.

    This article needs additional citations for verification. (January 2009)

    This article includes alist of references, but its sources remain unclear because it has

    insufficientinline citations.(May 2009)

    This article may requirecleanupto meet Wikipedia'squality standards.(May 2009)

    Templates are a feature of theC++programming language that allow functions and classes to

    operate withgeneric types. This allows a function or class to work on many differentdata types

    without being rewritten for each one. This is effectively aTuring-completelanguage.

    Templates are of great utility to programmers in C++, especially when combined withmultiple

    inheritanceandoperator overloading. TheC++ Standard Libraryprovides many useful functionswithin a framework of connected templates.

    Major inspirations for C++ templates were the parametrized modules provided byCLUand the

    generics provided byAda.[1]

    http://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#mw-headhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#mw-headhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#mw-headhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#p-searchhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#p-searchhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#p-searchhttp://en.wikipedia.org/w/index.php?title=Template_%28C%2B%2B%29&action=edithttp://en.wikipedia.org/w/index.php?title=Template_%28C%2B%2B%29&action=edithttp://en.wikipedia.org/w/index.php?title=Template_%28C%2B%2B%29&action=edithttp://en.wikipedia.org/wiki/Talk:Template_%28C%2B%2B%29http://en.wikipedia.org/wiki/Talk:Template_%28C%2B%2B%29http://en.wikipedia.org/wiki/Talk:Template_%28C%2B%2B%29http://en.wikipedia.org/wiki/Wikipedia:Citing_sourceshttp://en.wikipedia.org/wiki/Wikipedia:Citing_sourceshttp://en.wikipedia.org/wiki/Wikipedia:Citing_sourceshttp://en.wikipedia.org/wiki/Wikipedia:INCITEhttp://en.wikipedia.org/wiki/Wikipedia:INCITEhttp://en.wikipedia.org/wiki/Wikipedia:INCITEhttp://en.wikipedia.org/wiki/Wikipedia:Cleanuphttp://en.wikipedia.org/wiki/Wikipedia:Cleanuphttp://en.wikipedia.org/wiki/Wikipedia:Cleanuphttp://en.wikipedia.org/wiki/Wikipedia:Manual_of_Stylehttp://en.wikipedia.org/wiki/Wikipedia:Manual_of_Stylehttp://en.wikipedia.org/wiki/Wikipedia:Manual_of_Stylehttp://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/Datatypehttp://en.wikipedia.org/wiki/Datatypehttp://en.wikipedia.org/wiki/Datatypehttp://en.wikipedia.org/wiki/Turing-completehttp://en.wikipedia.org/wiki/Turing-completehttp://en.wikipedia.org/wiki/Turing-completehttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Operator_overloadinghttp://en.wikipedia.org/wiki/Operator_overloadinghttp://en.wikipedia.org/wiki/Operator_overloadinghttp://en.wikipedia.org/wiki/C%2B%2B_Standard_Libraryhttp://en.wikipedia.org/wiki/C%2B%2B_Standard_Libraryhttp://en.wikipedia.org/wiki/C%2B%2B_Standard_Libraryhttp://en.wikipedia.org/wiki/CLU_%28programming_language%29http://en.wikipedia.org/wiki/CLU_%28programming_language%29http://en.wikipedia.org/wiki/CLU_%28programming_language%29http://en.wikipedia.org/wiki/Ada_%28programming_language%29http://en.wikipedia.org/wiki/Ada_%28programming_language%29http://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#cite_note-Stroustrup-1http://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#cite_note-Stroustrup-1http://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#cite_note-Stroustrup-1http://www.brpreiss.com/books/opus4/html/page593.htmlhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#cite_note-Stroustrup-1http://en.wikipedia.org/wiki/Ada_%28programming_language%29http://en.wikipedia.org/wiki/CLU_%28programming_language%29http://en.wikipedia.org/wiki/C%2B%2B_Standard_Libraryhttp://en.wikipedia.org/wiki/Operator_overloadinghttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Multiple_inheritancehttp://en.wikipedia.org/wiki/Turing-completehttp://en.wikipedia.org/wiki/Datatypehttp://en.wikipedia.org/wiki/Generic_programminghttp://en.wikipedia.org/wiki/C%2B%2Bhttp://en.wikipedia.org/wiki/Wikipedia:Manual_of_Stylehttp://en.wikipedia.org/wiki/Wikipedia:Cleanuphttp://en.wikipedia.org/wiki/Wikipedia:INCITEhttp://en.wikipedia.org/wiki/Wikipedia:Citing_sourceshttp://en.wikipedia.org/wiki/Talk:Template_%28C%2B%2B%29http://en.wikipedia.org/w/index.php?title=Template_%28C%2B%2B%29&action=edithttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#p-searchhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#mw-head
  • 7/28/2019 DSA Assignment (2)

    48/51

    Contents

    1 Technical overview

    o 1.1 Function templates

    o 1.2 Class templateso 1.3 Explicit template specialization

    2 Advantages and disadvantages

    3 Generic programming features in other languages

    4 See also

    5 References

    6 External links

    Technical overview

    There are two kinds of templates:function templates and class templates.

    Function templates

    Afunction template behaves like a function except that the template can have arguments of manydifferent types (see example). In other words, a function template represents a family of

    functions. The format for declaring function templates with type parameters is

    template function_declaration;template function_declaration;

    Both expressions have exactly the same meaning and behave exactly the same way. The latterform was introduced to avoid confusion because a type parameter does not need to be a class, itmay also be a basic type like intordouble.

    For example, the C++ Standard Library contains the function template max(x, y) which returns

    eitherx ory, whichever is larger. max() could be defined like this, using the following template:

    template Type max(Type a, Type b) {

    return a > b ? a : b;}

    This single function definition works with different kinds of data types. A function template doesnot occupy space in memory. The actual definitions of a function template are generated at

    compile-time, when the compiler has determined what types the function will be called for. The

    function template does not save memory.

    #include

    int main(){

    http://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Technical_overviewhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Technical_overviewhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Function_templateshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Function_templateshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Class_templateshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Class_templateshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Explicit_template_specializationhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Explicit_template_specializationhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Advantages_and_disadvantageshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Advantages_and_disadvantageshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Generic_programming_features_in_other_languageshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Generic_programming_features_in_other_languageshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#See_alsohttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#See_alsohttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Referenceshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Referenceshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#External_linkshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#External_linkshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#External_linkshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Referenceshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#See_alsohttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Generic_programming_features_in_other_languageshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Advantages_and_disadvantageshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Explicit_template_specializationhttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Class_templateshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Function_templateshttp://en.wikipedia.org/wiki/Template_%28C%2B%2B%29#Technical_overview
  • 7/28/2019 DSA Assignment (2)

    49/51

    // This will call max (by argument deduction)std::cout

  • 7/28/2019 DSA Assignment (2)

    50/51

    Some uses of templates, such as the maximum() function, were previously fulfilled by function-

    likepreprocessormacros. For example, the following is a C++ maximum() macro:

    #define maximum(a,b) ((a) < (b) ? (b) : (a))

    Both macros and templates are expanded at compile time. Macros are always expanded inline,while templates are only expanded inline when the compiler deems it appropriate. When

    expanded inline, macro functions and template functions have no extraneous runtime overhead.Template functions with many lines of code will incur runtime overhead when they are not

    expanded inline, but the reduction in code size may help the code to load from disk more quickly

    or fit within RAM caches.

    Templates are consideredtype-safe; that is, they require type-checking at compile time. Hence,

    the compiler can determine at compile time whether the type associated with a templatedefinition can perform all of the functions required by that template definition.

    By design, templates can be utilized in very complex problem spaces, whereas macros aresubstantially more limited.

    There are fundamental drawbacks to the use of templates:

    1. Historically, some compilers exhibited poor support for templates. So, the use of templates

    could decrease code portability.

    2. Many compilers lack clear instructions when they detect a template definition error. This can

    increase the effort of developing templates, and has prompted the development ofConceptsfor

    possible inclusion in a future C++ standard.

    3. Since the compiler generates additional code for each template type, indiscriminate use of

    templates can lead tocode bloat, resulting in larger executables.

    4. Because a template by its nature exposes its implementation, injudicious use in large systemscan lead to longer build times.

    5. It can be difficult to debug code that is developed using templates. Since the compiler replaces

    the templates, it becomes difficult for the debugger to locate the code at runtime.

    6. Templates of Templates (nesting) are not supported by all compilers, or might have a max

    nesting level.

    7. Templates are in the headers, which require a complete rebuild of all project pieces when

    changes are made.

    8. No information hiding. All code is exposed in the header file. No one library can solely contain

    the code.

    Additionally, the use of the "less than" and "greater than" signs as delimiters is problematic fortools (such astext editors) which analyze source code syntactically. It is difficult, or sometimes

    impossible[citation needed]

    , for such tools to determine whether a use of these tokens is as comparison

    operators or template delimiters. For example, this line of code:

    foo (a < b, c > d) ;

    http://en.wikipedia.org/wiki/Preprocessorhttp://en.wikipedia.org/wiki/Preprocessorhttp://en.wikipedia.org/wiki/Macro_%28computer_science%29http://en.wikipedia.org/wiki/Macro_%28computer_science%29http://en.wikipedia.org/wiki/Macro_%28computer_science%29http://en.wikipedia.org/wiki/Type_safetyhttp://en.wikipedia.org/wiki/Type_safetyhttp://en.wikipedia.org/wiki/Type_safetyhttp://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29http://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29http://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29http://en.wikipedia.org/wiki/Code_bloathttp://en.wikipedia.org/wiki/Code_bloathttp://en.wikipedia.org/wiki/Code_bloathttp://en.wikipedia.org/wiki/Text_editorhttp://en.wikipedia.org/wiki/Text_editorhttp://en.wikipedia.org/wiki/Text_editorhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Text_editorhttp://en.wikipedia.org/wiki/Code_bloathttp://en.wikipedia.org/wiki/Concepts_%28C%2B%2B%29http://en.wikipedia.org/wiki/Type_safetyhttp://en.wikipedia.org/wiki/Macro_%28computer_science%29http://en.wikipedia.org/wiki/Preprocessor
  • 7/28/2019 DSA Assignment (2)

    51/51

    may be a function call with two parameters, each the result of a comparison expression.

    Alternatively, it could be a declaration of a constructor for class foo taking a parameterd whose

    type is the parameterized a < b, c >.