C++ ,Basic of c++,Learn C++

download C++ ,Basic of c++,Learn C++

of 165

Transcript of C++ ,Basic of c++,Learn C++

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    1/165

    v1.11

    C++By: Rajmal Menariya

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    2/165

    v1.12

    MODULE - 1

    INTRODUCTION TO C++

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    3/165

    v1.13

    OBJECTIVES

    To learn about :

    What is C++.

    Application of C++ Program development and execution

    A simple C++ program

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    4/165

    v1.14

    WHAT IS C++

    C++ is an object-oriented language.

    Initially named C with classes, C++ was developed byBjarne Stroustrup at AT&T Bell Laboratories in MurrayHill, New Jersey, USA, in the early eighties.

    C++ is an extension of C with a major addition of theclass construct feature of Simula67.

    C++ is a superset of C.

    The three most important facilities that C++ adds onto C are classes, function overloading and operatoroverloading. The features enable us to create abstractdata types, inherit properties from existing data typesand support polymorphism, thus making C++ a trulyobject oriented language.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    5/165

    v1.15

    APPLICATIONS OF C++

    C++ is a versatile language for handling largeprograms. It is suitable for virtually any programmingtask including development of editors, compilers,databases, communication systems and any complex

    real-life systems.

    Since C++ allows us to create hierarchy-relatedobjects, we can build special object-oriented libraries,which can be used later by many programmers. C++

    programs are easily maintainable and expandable.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    6/165

    v1.16

    PROGRAM DEVELOPMENT ANDEXECUTION

    Develop the program (source code).

    Select the suitable file name under which youll like tostore the program. This is the source code file.

    Compile the source code. The file containing thetranslated code is called object code file. If errorsdebug them.

    Link the object code with other library code that isrequired for execution. The resulting code is

    executable code. If errors debug them.

    Run the executable code. If errors debug them.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    7/165v1.17

    A SIMPLE C++ PROGRAM

    #include // Header file

    main( )

    {

    cout

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    8/165v1.18

    INVOKING AND USING TURBO C++

    Naming your program

    Saving your program

    Compiling and linking

    Running your program

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    9/165v1.19

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    10/165v1.110

    C++ PROGRAMMING BASICS

    MODULE - 2

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    11/165v1.111

    OBJECTIVES

    To learn about :

    Tokens

    Basic Program Construction Output using cout

    Comments

    Variables

    Constants

    Expressions

    Operators

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    12/165v1.112

    TOKENS

    The smallest individual unit in a program is known astoken. C++ has the following tokens:

    Keywords.

    Identifiers.

    Constants.

    Strings.

    Operators.

    A C++ program is written using these tokens,whitespaces and the syntax of the language.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    13/165v1.113

    FUNCTIONS

    Typical functions are called, or invoked, during thecourse of your program. A program is executed lineby line in the order it appears in your source code,until a function is reached. Then the programbranches off to execute the function. When the

    function finishes, it returns control to the line of codeimmediately following the call to the function.

    Functions either return a value or they return void,

    meaning they return nothing.

    The function main ( )

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    14/165v1.114

    In C++ a statement controls the sequence ofexecution, evaluates an expression, or does nothing(the null statement). All C++ statements end with asemicolon, even the null statement, which is just thesemicolon and nothing else.

    Any place you can put a single statement, you can puta compound statement, also called a block. A blockbegins with an opening brace ({) and ends with aclosing brace (}). Although every statement in theblock must end with a semicolon, the block itself doesnot end with a semicolon.

    STATEMENTS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    15/165v1.115

    WHITE SPACES

    Whitespace (tabs, spaces, and newlines) is generallyignored in statements.

    The assignment statement x = a + b; could be writtenas x =a + b;

    Whitespace can be used to make your programs

    more readable and easier to maintain, or it can beused to create horrific and indecipherable code.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    16/165

    v1.116

    OUTPUT USING cout

    To print a value to the screen, write the word cout,followed by the insertion operator (

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    17/165

    v1.117

    COMMENTS

    Comments are simply text that is ignored by thecompiler, but that may inform the reader of what youare doing at any particular point in your program.

    C++ comments come in two flavors: the double-slash(//) comment, and the slash-star (/*) comment. Thedouble-slash comment, which tells the compiler toignore everything that follows this comment, until the

    end of the line.The slash-star comment mark tells thecompiler to ignore everything that follows until it findsa star-slash (*/) comment mark.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    18/165

    v1.118

    typedef

    It can become tedious, repetitious, and, most

    important, error-prone to keep writing unsigned shortint.

    C++ enables you to create an alias for this phrase byusing the keyword typedef, which stands for type

    definition.In effect, you are creating a synonym, and itis important to distinguish this from creating a newtype. typedef is used by writing the keyword typedef,followed by the existing type and then the new name.

    For example typedef unsigned short int USHORTcreates the new name USHORT that you can use

    anywhere you might have written unsigned short int.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    19/165

    v1.119

    VARIABLES

    In C++ a variable is a place to store information.

    A variable is a location in your computer's memory in

    which you can store a value and from which you canlater retrieve that value.

    When you define a variable in C++, you must tell the

    compiler what kind of variable it is: an integer, acharacter, and so forth. This information tells thecompiler how much room to set aside and what kindof value you want to store in your variable.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    20/165

    v1.120

    FUNDAMENTAL VARIABLE TYPES

    Type Size Range

    unsigned short int 2 bytes

    short int 2 bytes

    unsigned long int 4 bytes

    long int 4 bytes int (16 bit) 2 bytes ?

    int (32 bit) 4 bytes

    unsigned int (16 bit) 2 bytes

    unsigned int (32 bit) 2 bytes

    char 1 byte

    float 4 bytes

    double 8 bytes

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    21/165

    v1.121

    DEFINING VARIABLES

    You create or define a variable by stating its type,followed by one or more spaces, followed by thevariable name and a semicolon.

    The variable name can be virtually any combination ofletters, but cannot contain spaces. Legal variablenames include x, J23qrsnf, and myAge. Goodvariable names tell you what the variables are for;using good names makes it easier to understand theflow of your program.

    The following statement defines an integer variablecalled myAge:

    int myAge;

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    22/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    23/165

    v1.123

    CONSTANTS

    Like variables, constants are data storage locations.Unlike variables, and as the name implies, constantsdon't change. You must initialize a constant when youcreate it, and you cannot assign a new value later.

    A literal constant is a value typed directly into your

    program wherever it is needed. e.g. int myAge = 39;

    A symbolic constant is a constant that is representedby a name, just as a variable is represented. If yourprogram has one integer variable named students

    and another named classes, you could compute howmany students you have, given a known number ofclasses, if you knew there were 15 students per class:e.g. students = classes * 15;

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    24/165

    v1.124

    EXPRESSIONS

    Anything that evaluates to a value is an expression in

    C++. An expression is said to return a value. Thus,3+2; returns the value 5 and so is an expression. Allexpressions are statements.

    3.2 // returns the value 3.2, expression

    The expression x = a + b; not only adds a and b andassigns the result to x, but returns the value of that

    assignment (the value of x) as well. Thus, thisstatement is also an expression.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    25/165

    v1.125

    OPERATORS

    An operator is a symbol that causes the compilerto take an action. Operators act on operands, andin C++ all operands are expressions. In C++ thereare several different categories of operators.

    Categories of operators are: Assignment operators.

    Logical operators.

    Relational operators.

    Conditional(Ternary Operator)

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    26/165

    v1.126

    NEW OPERATORS

    :: Scope Resolution operator.

    ::* Pointer-to-member declarator.

    ->* Pointer to-member operator.

    .* Pointer to member operator.

    new Memory allocation operator.

    delete Memory release operator.

    endl Line feed operator.

    setw Field width operator.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    27/165

    v1.127

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    28/165

    v1.128

    LOOPS AND DECISIONS

    MODULE - 3

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    29/165

    v1.129

    OBJECTIVES

    To learn about :

    Loops

    Decisions

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    30/165

    v1.130

    LOOPS

    Loops cause a section of your program to berepeated a certain number of times. The repetitioncontinues while a condition is true. When thecondition becomes false the loop ends and the control

    passes to the statement following the loop.

    Various kinds of loops are

    for loop

    while loop do-while loop

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    31/165

    v1.131

    for LOOP

    A for loop performs initialization before the firstiteration. Then it performs condition testing and, at theend of each iteration, some form of stepping. Theform of the for loop is

    for(initialization ; expression; step)

    Statement

    Any of initialization, expression or step may be empty.The initialization code begins once at beginning. Theexpression is tested before each iteration. At the endof each iteration the step executes.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    32/165

    v1.132

    while LOOP

    The form of while loop is

    while(expression)

    Statement

    The expression is evaluated once at the beginning of

    the loop and again before each further iteration of thestatement.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    33/165

    v1.133

    do-while LOOP

    The form of do-while is

    do

    Statementwhile(expression)

    The do-while is different from while because the

    statement always executes at least once, even if theexpression evaluates to false the first time. In a simplewhile statement if the conditional is false the first timethe statement never executes.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    34/165

    v1.134

    DECISIONS: if-else

    The if-else statement executes in two forms

    if (expression)

    Statement

    if (expression)

    Statementelse

    Statement

    The expression evaluates to either true or false. The

    statement means either a simple statementterminated by a semi colon or a compound statement,which is a group of simple statements enclosed inbraces. The statement can be another if statement.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    35/165

    v1.135

    switch STATEMENT

    A switch statement selects from among pieces of

    code based on the value of an integral expression. Itsform is

    switch (selector) {

    case integral-value1 : statement; break;

    ()

    default : statement; break; }

    Selector is an expression that produces an integralvalue. The switch compares the result of selector to

    each integral-value. If it finds a match thecorresponding statement execute. If no match isfound the default statement executes.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    36/165

    v1.136

    OTHER CONTROL STATEMENTS

    break

    continue

    goto

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    37/165

    v1.137

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    38/165

    v1.138

    STRUCTURES AND UNIONS

    MODULE - 4

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    39/165

    v1.139

    OBJECTIVES

    To learn about :

    Structures

    Unions

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    40/165

    v1.140

    STRUCTURES

    A structure is a collection of simple variables. Theyprovide a method of packing data of different types. Astructure is a convenient tool for handling a group oflogically related data items. It is a user-defined datatype with a template that serves to define its data

    properties. It has the following form:

    struct [tag] { member-list } [declarators];

    [struct] tag declarators;

    The struct keyword defines a structure type and/or avariable of a structure type.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    41/165

    v1.141

    LIMITATION OF C STRUCTURE

    struct complex

    {float x;

    float y;

    };

    struct complex c1,c2,c3;

    The complex numbers can be easily assigned valuesusing the dot operator but we cannot attemptarithmetic operations on them

    c3 = c1 + c2; is illegal in C.

    Also, structures in donot permit data hiding. Structuremembers can be easily accessed anywhere by thefunctions.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    42/165

    v1.142

    EXTENSIONS TO STRUCTURES

    In C++ a structure can have both variables andfunctions as members. It can also declare some of itsmembers as private so that they may not be accesseddirectly by external functions.

    In C++ structure names are stand-alone and can beused like any other type names. The keyword structcan be omitted in the declaration of structurevariables.

    student st1; // This is an error in C.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    43/165

    v1.143

    STRUCTURES AND CLASSES

    The members of a struct are public by default, while ina class they default to private.

    struct and class are otherwise functionally equivalent.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    44/165

    v1.144

    UNION

    A union is a user-defined data type that can hold

    values of different types at different times. It is similarto a structure except that all of its members start atthe same location in memory. A union variable cancontain only one of its members at a time. The size of

    the union is at least the size of the largest member. Ithas the form:

    union [tag] { member-list } [declarators];

    [union] tag declarators;

    The union keyword declares a union type and/or avariable of a union type.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    45/165

    v1.145

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    46/165

    v1.146

    FUNCTIONS IN C++

    MODULE - 5

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    47/165

    v1.147

    OBJECTIVES

    To learn about :

    Functions

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    48/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    49/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    50/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    51/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    52/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    53/165

    v1.153

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    54/165

    v1.154

    CLASSES AND OBJECTS

    MODULE - 6

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    55/165

    v1.155

    OBJECTIVES

    To learn about :

    Classes

    Objects

    Friend functions

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    56/165

    v1.156

    CLASSES

    A class is a way to bind data and its associatedfunctions together. It allows the data (and functions) tobe hidden, if necessary from external use. Whendefining a class we are creating abstract data type

    that can be treated like any other built-in data type. Aclass specification has two parts:

    Class declaration

    Class function definitions

    The class declaration describes the type and scope ofits members. The class function definitions describehow the class functions are implemented.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    57/165

    v1.157

    class class_name

    {

    private:

    variable declaration;

    function declaration;

    public:variable declaration;

    function declaration;

    };

    The class declaration is very similar to that of structdeclaration. The keyword class specifies that whatfollows is an abstract data type class_name. The bodyof the class is enclosed

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    58/165

    FRIEND FUNCTIONS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    59/165

    v1.159

    FRIEND FUNCTIONS

    There could be situations where two classes wouldwant to share a function. In such situations, C++allows the common function to be made friendly withboth the classes thereby allowing the function to have

    access to the private data of these two classes. Sucha function need not be the member of any of theseclasses.

    class ABC

    {public:

    friend void xyz(void); //declaration

    };

    CHARACTERISTICS OF A FRIEND

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    60/165

    v1.160

    CHARACTERISTICS OF A FRIENDFUNCTION

    It is not in the scope of the class to which it has beendeclared as a friend.

    Since it is not in the scope of the class, it cannot becalled using the object of that class.

    Unlike member functions it cannot access themember names directly and has to use an objectname and dot membership operator with eachmember name.

    It can be declared in either public or private part ofthe class, without effecting its meaning.

    Usually, it has the objects as arguments.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    61/165

    v1.161

    POINTERS TO MEMBERS

    It is possible to take the address of a member of aclass and assign it to a pointer. The address of amember can be obtained by applying the & to a fullyqualified class member name. A class member

    pointer can be declared using the operator ::* with theclass name.

    The dereferencing operator ->* is used to access a

    member when we use pointer to both the memberand the object. The dereferencing operator .* is usedwhen object itself is used with member pointer.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    62/165

    v1.162

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    63/165

    v1.163

    CONSTRUCTORS AND

    DESTRUCTORS

    MODULE - 7

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    64/165

    v1.164

    OBJECTIVES

    To learn about :

    The need of constructors and destructors.

    Constructors.

    Destructors.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    65/165

    v1.165

    WHAT IS THE NEED ?

    One of the aims of C++ is to create user-defined datatypes such as class, which behave very similar tobuilt-in data types.

    This means that we should be able to initialize a classtype variable much the same way as initialization ofordinary variable.

    Also, when the variable in the built in type goes out ofscope it should be destroyed.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    66/165

    v1.166

    CONSTRUCTORS

    C++ provides a special member function called theconstructor, which enables an object to initialize itselfwhen it is created.

    This is known as automatic initialization of objects.

    It is special because its name is same as the classname. The constructor is invoked whenever an object

    of is associated class is created. It is calledconstructor because it constructs the values of datamembers of its class.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    67/165

    SPECIAL CHARACTERISTICS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    68/165

    v1.168

    SPECIAL CHARACTERISTICS

    They should be declared in the public section.

    They are invoked when the objects are created. They don't have return types and hence don't return

    anything.

    They cannot be inherited, though a derived class can

    call the base class constructor. They can have default arguments.

    Constructors cannot be virtual.

    We cannot refer to their address.

    An object with a constructor or destructor cannot beused as a member of a union.

    They make implicit calls to the operators new anddelete when memory allocation is required.

    PARAMETRIZED CONSTRUCTORS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    69/165

    v1.169

    PARAMETRIZED CONSTRUCTORS

    It is sometimes necessary to initialize various data

    elements of different objects with different valueswhen they are created. C++ permits us to achieve thisobjective by passing arguments to the constructorfunction when they are created. The constructors that

    can take arguments are called parameterizedconstructors.

    We must pass the initial values as arguments to theconstructor when an object is declared. By calling theconstructor explicitly

    Integer int 1 = Integer (0,100); // explicit call

    By calling the constructor implicitly

    Integer int 1(0,100); // implicit call

    COPY CONSTRUCTOR

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    70/165

    v1.170

    COPY CONSTRUCTOR

    A copy constructor is used to declare and initialize an

    object from another object.Integer i2 (i1);

    Suppose Integer is a class, i2 would define the object

    and at the same time initialize it to the values of i1.This can also be done as

    Integer i2 = i1;

    The process of invoking through the copy constructoris called copy initialization..

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    71/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    72/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    73/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    74/165

    ARRAY FUNDAMENTALS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    75/165

    v1.175

    ARRAY FUNDAMENTALS

    An array is a collection of data storage locations, each

    of which holds the same type of data. Each storagelocation is called an element of the array.

    You declare an array by writing the type, followed bythe array name and the subscript. The subscript is the

    number of elements in the array, surrounded bysquare brackets. For example,

    long LongArray[25]; declares an array of 25 longintegers, named LongArray. When the compiler seesthis declaration, it sets aside enough memory to holdall 25 elements. Because each long integer requires 4bytes, this declaration sets aside 100 contiguousbytes of memory

    ARRAY ELEMENTS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    76/165

    v1.176

    ARRAY ELEMENTS

    You access each of the array elements by referring to

    an offset from the array name.

    Array elements are counted from zero. Therefore, thefirst array element is arrayName[0].

    When you write a value to an element in an array, the

    compiler computes where to store the value based onthe size of each element and the subscript. Supposethat you ask to write over the value at LongArray[5],which is the sixth element. The compiler multiplies the

    offset (5) by the size of each element--in this case, 4.It then moves that many bytes (20) from the beginningof the array and writes the new value at that location.

    FENCE POST ERRORS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    77/165

    v1.177

    FENCE POST ERRORS

    It is so common to write to one past the end of anarray that this bug has its own name. It is called afence post error.

    This refers to the problem in counting how manyfence posts you need for a 10-foot fence if you needone post for every foot.

    Most people answer 10, but of course you need11.This sort of "off by one" counting can be the baneof any programmer's life.

    INITIALIZING AN ARRAY

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    78/165

    v1.178

    INITIALIZING AN ARRAY

    You can initialize a simple array of built-in types, suchas integers and characters, when you first declare thearray. After the array name, you put an equal sign (=)and a list of comma-separated values enclosed in

    braces. For example,

    int IntegerArray[5] = { 10, 20, 30, 40, 50 };

    ARRAY OF OBJECTS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    79/165

    v1.179

    ARRAY OF OBJECTS

    Any object, whether built-in or user-defined, can be

    stored in an array. When you declare the array, youtell the compiler the type of object to store and thenumber of objects for which to allocate room. Thecompiler knows how much room is needed for each

    object based on the class declaration. The class musthave a default constructor that takes no arguments sothat the objects can be created when the array isdefined. Accessing member data in an array ofobjects is a two-step process. You identify the

    member of the array by using the index operator ([ ]),and then you add the member operator (.) to accessthe particular member variable.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    80/165

    MORE ON ARRAYS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    81/165

    v1.181

    MORE ON ARRAYS

    Arrays and pointers.

    Arrays and strings.

    Linked list and other data structures.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    82/165

    v1.182

    QUERIES

    MODULE 9

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    83/165

    v1.183

    OPERATOR OVERLOADING

    MODULE - 9

    OBJECTIVES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    84/165

    v1.184

    OBJECTIVES

    To learn about :

    What is operator overloading.

    Defining operator overloading. Steps for operator overloading.

    Overloading unary and binary operators.

    Rules for operator overloading.

    WHAT IS OPERATOR OVERLOADING

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    85/165

    v1.185

    WHAT IS OPERATOR OVERLOADING

    C++ permits us to add to two variables of user-definedtypes with the same syntax that is applied to basictypes. This means that C++ has the ability to provide

    the operators with a special meaning for a data type.The mechanism of giving such special meanings toan operator is known as operator overloading.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    86/165

    v1.186

    Operator overloading provides a flexible option for thecreation of new definitions for most of the C++

    operators. We can overload all C++ operators exceptfor the following

    Class member access operator ( ., .* ).

    Scope resolution operator ( :: ).

    Size operator ( sizeof ).

    Conditional operator ( ?: ).

    When an operator is overloaded its original meaningis not lost. Although the semantics of an operator canbe extended, we cannot change its syntax, the

    grammatical rules that govern its use such as thenumber of operands, precedence and associativity.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    87/165

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    88/165

    v1.188

    Operator functions must be either member function(non-static) or friend functions.

    A basic difference them is that a friend function willhave only one argument for unary operators and twofor binary operators, while a member function has noarguments for unary operators and only one for binary

    operator. This is because the operator used to invoke the

    member function is passed implicitly and therefore isavailable for member function.

    This is not the case with friend functions. Argumentsmay be passed by value or by reference.

    STEPS OF OPERATOR OVERLOADING

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    89/165

    v1.189

    STEPS OF OPERATOR OVERLOADING

    Create a class that defines the data type that is to beused in the overloading operation.

    Declare the operator function operator op( ) in the

    public part of the class. It may be either a memberfunction or friend function.

    Define the operator function to implement the required

    operations.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    90/165

    v1.190

    OVERLOADING UNARY AND BINARYOPERATOR

    RULES FOR OVERLOADING OPERATORS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    91/165

    v1.191

    RULES FOR OVERLOADING OPERATORS

    Only existing operators can be overloaded. New

    operators cannot be created. The overloaded operator must have at least one

    operand that is of user defined type.

    We cannot change the basic meaning of an operator.

    That is, we cannot redefine the plus (+) operator tosubtract one value from the other.

    Overloaded operators follow the syntax rules of theoriginal operators. That cannot be overridden.

    There are some operators that cannot be overloaded. We cannot use friend functions to overload certain

    operators. However member functions can be used tooverload them.

    Unary operators overloaded by means of a member

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    92/165

    v1.192

    Unary operators, overloaded by means of a memberfunction, take no explicit arguments and return noexplicit values. But, those overloaded by means of a

    friend function take one reference argument.

    Binary operators overloaded through a memberfunction take one explicit argument and those whichare overloaded through a friend function take two

    explicit arguments. When using binary operators overloaded through a

    member function, the left hand operator must be anobject of the relevant class.

    Binary arithmetic operators such as +, -, * and / mustexplicitly return a value. They must not attempt tochange their own arguments.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    93/165

    MODULE 10

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    94/165

    v1.194

    INHERITANCE

    MODULE - 10

    OBJECTIVES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    95/165

    v1.195

    OBJECTIVES

    To learn about :

    Inheritance

    Single Inheritance

    Multiple Inheritance

    Hierarchical Inheritance

    Hybrid Inheritance

    Virtual base class

    Abstract base class

    Constructors in derived classes

    Nesting of classes

    INHERITANCE

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    96/165

    v1.196

    INHERITANCE

    Reusability is an important concept of Object OrientedProgramming (OOP). It is always better to reusesomething rather than trying to reinvent the wheel.

    The mechanism of deriving new class from an old oneis called inheritance (or derivation). The old class isreferred to as base class and the new one is calledderived class.

    The derived class inherits some or all of the traits ofthe base class. A class can also inherit propertiesfrom more than one class or from more than onelevel.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    97/165

    SINGLE INHERITANCE

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    98/165

    v1.198

    SINGLE INHERITANCE

    In single inheritance, a common form of inheritance,

    classes have only one base class.

    PrintedDocument

    Book

    PaperbackBook

    MULTIPLE INHERITANCE

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    99/165

    v1.199

    MULTIPLE INHERITANCE

    A class can inherit the attributes of two or moreclasses. This is known as multiple inheritance.Multiple inheritance allows us to combine the featuresof several existing classes as starting point for

    defining new classes. It is like a child inheriting thephysical features of one parent and the intelligence ofthe other.

    class D : visibilityB1, visibilityB2

    {

    // Body of D

    };

    HIERARCHICAL INHERITANCE

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    100/165

    v1.110

    HIERARCHICAL INHERITANCE

    The base class will include all features that arecommon to the subclasses.

    A subclass can be constructed by inheriting thefeatures of the base class.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    101/165

    v1.110

    Students

    Comp.

    Arts

    Mech. Elec...

    MedicalEngineering

    HYBRID INHERITANCE

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    102/165

    v1.110

    HYBRID INHERITANCE

    There could be situations where we need to apply twoor more types of inheritance to design a program.

    For instance, take the case of processing the student

    results.

    Assume weightage is to be given to sports beforefinalising the result.

    The weightage for sports is stored in a separate classcalled sports.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    103/165

    VIRTUAL BASE CLASS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    104/165

    v1.110

    VIRTUAL BASE CLASS

    Consider a situation where all three kinds ofinheritance, namely, multilevel, multiple andhierarchical inheritance are involved.

    This is illustrated in the figure.

    The child has two direct base classes parent1 andparent2 which themselves have a common base classgrandparent.

    The child inherits the traits of the grandparent via two

    different paths. It can also inherit directly. The grandparent is

    sometimes referred to as indirect base class.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    105/165

    v1.110

    Grandparent

    Child

    Parent 1 Parent 1

    ABSTRACT CLASS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    106/165

    v1.110

    ABSTRACT CLASS

    An abstract class is one that is not used to createobjects.

    An abstract class is designed only to act as a base

    class (to be inherited by other classes).

    It is a design concept in program development andprovides a base upon which other classes may be

    built.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    107/165

    NESTING OF CLASSES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    108/165

    v1.110

    C++ supports yet another way of inheriting propertiesof one class into another. This approach takes a viewthat an object can be a collection of many other

    objects. That is a class can contain objects of otherclasses as its members.

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    109/165

    v1.110

    QUERIES

    MODULE -11

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    110/165

    v1.111

    POINTERS,

    VIRTUAL FUNCTIONS ANDPOLYMORPHISM

    MODULE 11

    OBJECTIVES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    111/165

    v1.111

    To learn about :

    Pointers

    Polymorphism

    Virtual functions

    WHY USE POINTERS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    112/165

    v1.111

    Accessing array elements.

    Passing arguments to a function when the functionneeds to modify the original arguments.

    Passing arrays and strings to function.

    Obtaining memory from the system.

    Creating data structures such as linked lists.

    ADDRESSES AND POINTERS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    113/165

    v1.111

    There are a few key concepts behind pointers. The first key concept: Every byte in the computer

    memory has an address. Addresses are numbers justas they are for house or street. The program when it

    is loaded into memory occupies a certain range ofthese addresses.

    This means that every variable and every function inyour program starts at a particular address.

    ADDRESS OF OPERATOR(&)

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    114/165

    v1.111

    The address occupied by a variable can be found out byusing the address of operator ( & ).

    #include

    main()

    {

    int var1 = 100;

    int var2 = 100;

    cout

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    115/165

    v1.111

    A variable that holds an address value is called apointer variable.

    What is the data type of pointer variables?

    Its not the same as the variable whose address is

    being stored; a pointer to an int is not type int.

    int* ptr;

    The asterisk means pointer to. Thus the statement

    defines ptr as pointer to int. This is another way ofsaying that this variable can hold the address ofinteger variables.

    ACCESSING THE VALUE OF THE VARIABLEPOINTED TO

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    116/165

    v1.111

    POINTED TO

    #include main()

    {

    int var1 = 100;

    int* ptr; // Pointer to an integerptr = &var1; // Assigns the address ofvar1 to ptr

    cout

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    117/165

    v1.111

    When the asterisk is used in front of a variable name

    as it is in *ptr expression it is called indirectionoperator. It means the value of the variable pointed toby. Thus, *ptr represents the value of the variablepointed to by ptr.

    Indirection is also referred to as dereferencing.

    int v;

    int* p;

    p = &v;

    v = 3; // Direct Addressing, assigns 3 to v*p = 5; // Indirect Addressing, assigns 5 to v

    POINTER TO A VOID

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    118/165

    v1.111

    Consider a machine that uses a 32-bit word, Itsaddressing may be designed to use 32-bitboundaries, so along fits nicely in a single word andthe ordinary address works nicely as a pointer.However a char might be implemented in 8 bits on

    such a machine which means that 4 characters wouldfit in a word. That means the char pointer wouldrequire some additional information to locate aparticular byte inside a word. Thus the char pointer

    will be of a different size than the long pointer.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    119/165

    v1.111

    If one always knows how big a pointer is, you can

    pass the address of any type to a function, and thefunction can perform proper typecasting based onsome other piece of information.

    C++ invented the void pointer for this purpose.

    A void pointer means a pointer to any type of data.

    POINTER CONSTANTS AND POINTER

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    120/165

    v1.112

    VARIABLES

    Can we use the increment operator instead of thestatement *(v+1), *(v++)?

    The answer is no and the reason is that you cant

    increment a constant. The expression v is the address where the system

    has chosen to place your array and it will stay thereuntil the program terminates, v is a constant.

    While you cant increment an address you canincrement the pointer that holds the address.

    POLYMORPHISM

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    121/165

    v1.112

    Polymorphism as the name suggests means onename, multiple forms.

    Function overloading and Operator overloading areimplementations of polymorphism.

    The overloaded member functions are selected forinvoking by matching arguments both type andnumber. The information is known to the compiler atthe compile time and therefore is able to select the

    appropriate function for particular calls at compiletime. This is called early binding or static binding orstatic linking. Also known as compile timepolymorphism.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    122/165

    v1.112

    The compiler defers the decision to run-time.

    Appropriate member function is selected only at run-time. This is known as run-time polymorphism.

    C++ supports a mechanism called virtual function toachieve run-time polymorphism. At run-time it isknown what class objects are under construction, theappropriate version of the function is called.

    Since the function is linked with the class much laterafter the compilation, this process is termed as latebinding.

    It is also called dynamic binding because theselection of the function is done dynamically at run-time.

    POINTER TO OBJECT

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    123/165

    v1.112

    A pointer can point to an object created by class.

    Consider the following statement:Item x;

    Where Item is the class and x is its instance. Similarly

    we can define a pointer it_ptr of type Item.

    Item it_ptr;

    Object pointers are useful in creating objects at run-time. We can also use object pointer to access thepublic members of an object.

    this POINTER

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    124/165

    v1.112

    C++ uses a unique keyword called this to representan object that invokes a member function. this is apointer that points to the object for which this functionwas called.

    For instance, the function A.max( ) will set the pointerthis to the address of the object A. The startingaddress is same as the address of the variable in theclass structure.

    The unique pointer is automatically passed to the

    member function when it is called. The pointer thisacts as an implicit argument to all member functions.

    POINTERS TO DERIVED CLASSES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    125/165

    v1.112

    We can use pointers not only to the base objects butalso to the objects of the derived class.

    Pointers to the objects of the base class are type

    compatible with pointers of the derived class.

    Therefore a single pointer variable can be made topoint to objects belonging to different classes.

    VIRTUAL FUNCTIONS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    126/165

    v1.112

    An essential requirement of polymorphism is theability to refer to objects without any regard to theirclasses. This necessitates the use of single pointervariable to refer to objects of different classes. Herewe use the pointer to the base class to refer to all

    derived objects. This is achieved using virtualfunctions.

    When we use the same function name in both thebase and the derived classes, the function in base

    class is declared as virtual using the keyword virtualpreceding its normal declaration. Thus, by making thebase pointer to point to different objects, we canexecute different versions of the virtual function

    RULES FOR VIRTUAL FUNCTIONS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    127/165

    v1.112

    The virtual functions must be members of the same

    class. They cannot be static members.

    They are accessed by using object pointers.

    A virtual function can be a friend of another class.

    A virtual function in the base class must be definedeven if it is not used.

    The prototypes of base class version of a virtualfunction and the entire derived class version must beidentical. If two functions with the same names havedifferent prototype, C++ consider them as overloadedfunctions, and the virtual function mechanism isignored.

    W t h i t l t t b t h

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    128/165

    v1.112

    We cannot have virtual constructors but we can havevirtual destructors.

    While a base pointer can point to any type of thederived object, the reverse is not true. That is wecannot use a pointer to a derived class to access anobject of the base type.

    When a base pointer points to a derived class,incrementing or decrementing it will not make it pointto the object of the derived class. It is incremented ordecremented only to its base type. Therefore, we

    should not use this method to move the pointer to thenext object.

    If a virtual function is derived in the base class it need

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    129/165

    v1.112

    If a virtual function is derived in the base class, it neednot necessarily be redefined in the base class. In

    such cases, calls will invoke the base function.

    PURE VIRTUAL FUNCTIONS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    130/165

    v1.113

    It is a normal practice to declare a function virtual

    inside the base class and redefine it in the derivedclass. The function inside the base class is seldomused for performing any task. It only serves as aplaceholder.

    Such functions are called do-nothing functions. A do-nothing function may be defined as follows.

    virtual void display( ) = 0;

    Such functions are called pure virtual functions.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    131/165

    v1.113

    A pure virtual function is a function declared in a

    base class that has no definition relative to the baseclass. In such cases, the compiler requires eachderived class to either define the function or re-declare it as a pure virtual function.

    A class containing pure virtual functions cannot beused to declare any objects of its own.

    Such classes are called Abstract Base Classes(ABC). The main objective of the ABC is to providesome traits to the derived classes and to create a

    base pointer required for achieving run-timepolymorphism.

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    132/165

    v1.113

    MODULE -12

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    133/165

    v1.113

    MANAGING CONSOLE I/O

    OPERATIONS

    OBJECTIVES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    134/165

    v1.113

    To learn about :

    Stream

    Stream Classes

    Formatting the output.

    INTRODUCTION

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    135/165

    v1.113

    C++ uses the concept of stream and stream classesto implement I/O operations with the console and diskfiles.

    The I/O system is designed to work with a wide

    variety of devices including terminals, disks and tapedrives. Although each device is very different the I/Osystem supplies an interface known as stream, that isindependent of the device being accessed.

    STREAMS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    136/165

    v1.113

    A stream is sequence of bytes.

    It acts as a source from which the input data can betaken and acts as a destination to which output datacan be sent.

    The source stream is called the input stream and thedestination stream is called output stream.

    The data in the input stream can come from thekeyboard or any other storage device.

    Similarly the data in the output stream can go to thescreen or any other storage device.

    STREAM CLASSES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    137/165

    v1.113

    ios (General input/output stream class)

    Contains basic facilities that are used by all other inputand output classes.

    It also contains a pointer to a buffer object (streambufobject).

    Declares constants and functions that are necessary for

    handling input and output operations.

    istream (input stream)

    Inherits the properties of ios.

    Declares input functions such as get(), getline() and

    read() Contains overloaded extraction operator >>.

    ostream (output stream)

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    138/165

    v1.113

    ostream (output stream)

    Inherits the properties of ios.

    Declares output functions such as put(), write(). Contains overloaded insertion operator

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    139/165

    v1.113

    C++ supports a number of features that could be usedfor formatting the output.

    These feature include:

    Ios class functions and flags Manipulators

    User-defined output functions

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    140/165

    v1.114

    MODULE -13

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    141/165

    v1.114

    WORKING WITH FILES

    OBJECTIVES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    142/165

    v1.114

    To learn about :

    Classes for file streams

    Various file operations

    Binary vs. Text files

    Command line processing

    INTRODUCTION

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    143/165

    v1.114

    Streams provide a uniform way of dealing with data

    coming from the keyboard or the hard disk and goingout to the screen or hard disk. To open and closefiles, you create ifstream and ofstream objects.

    the particular objects used to read from or write tofiles are called ofstream objects.

    These are derived from the iostream objects you've

    been using so far.

    CLASSES FOR FILE STREAMS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    144/165

    v1.114

    Class Contents

    filebuf Its purpose is to set the file buffersto read and write

    fstreambase Provides operations common to filestreams.

    ifstream Provides input operations

    ofstream Provides output operations

    fstream Provides support for simultaneous

    Input and output operations

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    145/165

    v1.114

    VARIOUS FILE OPERATIONS

    BINARY VERSUS TEXT FILES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    146/165

    v1.114

    Some operating systems, such as DOS, distinguish

    between text files and binary files. Text files store everything as text (as you might have

    guessed), so large numbers such as 54,325 arestored as a string of numerals (`5', `4', `,', `3', `2', `5').This can be inefficient, but has the advantage that thetext can be read using simple programs such as theDOS program type.

    To help the file system distinguish between text andbinary files, C++ provides the ios::binary flag. On

    many systems, this flag is ignored because all data isstored in binary format.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    147/165

    COMMAND LINE PROCESSING

    OS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    148/165

    v1.114

    Many operating systems, such as DOS and UNIX,

    enable the user to pass parameters to your programwhen the program starts.

    These are called command-line options, and aretypically separated by spaces on the command line.For example:

    SomeProgram Param1 Param2 Param3

    These parameters are not passed to main() directly.

    Instead, every program's main() function is passedtwo parameters.

    The first is an integer count of the number ofarguments on the command line The program name

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    149/165

    v1.114

    arguments on the command line. The program nameitself is counted, so every program has at least one

    parameter.

    The second parameter passed to main() is an array ofpointers to character strings. Because an array nameis a constant pointer to the first element of the array,you can declare this argument to be a pointer to apointer to char, a pointer to an array of char, or anarray of arrays of char. Typically, the first argument is

    called argc (argument count), but you may call itanything you like. The second argument is oftencalled argv (argument vector), but again this is just aconvention.

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    150/165

    v1.115

    MODULE -14

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    151/165

    v1.115

    TEMPLATES & EXCEPTIONS

    OBJECTIVES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    152/165

    v1.115

    To learn about :

    Templates

    Use of templates

    Advantages of templates

    Templates vs. macros.

    Templates vs.. void pointers

    Exception handling

    INTRODUCTION

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    153/165

    v1.1

    15

    Templates provide direct support for generic

    programming that is, programming using types asparameters.

    A template can be used to create family of classes

    and functions.

    Exception handling provides a mechanism to identifyand manage certain disastrous conditions during the

    execution of the program.

    TEMPALTES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    154/165

    v1.1

    15

    Templates are mechanisms for generating functionsand classes based on type parameters (templates aresometimes called "parameterized types").

    By using templates, you can design a single class thatoperates on data of many types, instead of having tocreate a separate class for each type.

    USE OF TEMPLATES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    155/165

    v1.1

    15

    Create a type-safe collection class (for example, astack) that can operate on data of any type.

    Add extra type checking for functions that would

    otherwise take void pointers.

    Encapsulate groups of operator overrides to modifytype behavior (such as smart pointers).

    ADVANTAGES OF TEMPLATES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    156/165

    v1.1

    15

    Templates are easier to write. You create only one

    generic version of your class or function instead ofmanually creating specializations.

    Templates can be easier to understand, since they

    can provide a straightforward way of abstracting typeinformation.

    Templates are type-safe. Because the types that

    templates act upon are known at compile time, thecompiler can perform type checking before errorsoccur.

    TEMPLATES VS. MACROS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    157/165

    v1.1

    15

    In many ways, templates work like preprocessor

    macros, replacing the templated variable with thegiven type.

    Here are some problems with the macro:

    There is no way for the compiler to verify that the macroparameters are of compatible types.

    The macro is expanded without any special type checking.

    The i and j parameters are evaluated twice. If eitherparameter has a post incremented variable, the increment isperformed two times.

    Because the preprocessor expands macros, compilererror messages will refer to the expanded macro,rather than the macro definition itself. Also, the macrowill show up in expanded form during debugging.

    TEMPLATES VS. VOID POINTERS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    158/165

    v1.1

    15

    Many functions that are now implemented with voidpointers can be implemented with templates.

    Void pointers are often used to allow functions tooperate on data of an unknown type.

    When using void pointers, the compiler cannotdistinguish types, so it cannot perform type checkingor type-specific behavior such as using type-specificoperators, operator overloading, or constructors anddestructors.

    With templates, you can create functions and classesthat operate on typed data The type looks abstracted

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    159/165

    v1.1

    15

    that operate on typed data. The type looks abstractedin the template definition. However, at compile timethe compiler creates a separate version of thefunction for each specified type. This enables thecompiler to treat class and function templates as ifthey acted on specific types. Templates can also

    improve coding clarity, because you don't need tocreate special cases for complex types such asstructures.

    EXCEPTION HANDLING

    The C++ language provides built-in support for

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    160/165

    v1.1

    16

    The C++ language provides built in support forhandling anomalous situations, known as

    "exceptions," which may occur during the execution ofyour program.

    With C++ exception handling, your program cancommunicate unexpected events to a higher

    execution context that is better able to recover fromsuch abnormal events.

    These exceptions are handled by code that is outsidethe normal flow of control.

    In C++, the process of raising an exception is called"throwing" an exception.

    A designated exception handler then "catches" thethrown exception

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    161/165

    v1.1

    16

    thrown exception.

    Exceptions are of two kinds, namely, synchronousexceptions and asynchronous exceptions.

    Errors such as out of range index and overflow aresynchronous exceptions.

    The exceptions that are caused by events that arebeyond the control of the program are asynchronousexceptions.

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    162/165

    v1.1

    16

    SYNTAX OF EXCEPTION HANDLING CODE

    GENERAL MECHANISM FOR ERRORHANDLING IS AS FOLLOWS:

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    163/165

    v1.1

    16

    Find the problem (Hit the exception)

    Inform that the error has occurred (Throw theexception)

    Receive the error information (Catch theexception)

    Take corrective actions (Handle the exception)

    STRIKING THING ABOUT EXCEPTIONS

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    164/165

    v1.1

    16

    One of the striking thing about C++ exceptions is thatthey allow you to return any type of object from afunction regardless of what the function return type is.

    The other fascinating feature of exceptions is that ifyouve constructed some of the objects in a block, and

    you hit an exception, the only destructors called are

    for the objects not all.

    QUERIES

  • 8/3/2019 C++ ,Basic of c++,Learn C++

    165/165