c++ final notes

Upload: rajesh-kumar

Post on 06-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 C++ Final Notes

    1/92

    The history of C++

    C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in

    the early 1980's, and is based on the C language. C++ is an object

    oriented programming language, it implements data abstraction using

    a concept called classes along with some other features of oop. apart

    of the c++ program are easily reusable and extensible code is easily

    modifiable without actually having to change the code .The "++" is a

    syntactic construct used in C (to increment a variable), and C++ is

    intended as an incremental improvement of C .It contains all features of

    oops.

  • 8/3/2019 C++ Final Notes

    2/92

    For input - cin > : Extraction OperatorInput /output stream- iostream.h : double quote

    Console input/output- conio.h ( ) : parenthesis

    #include

    #include

    Void main ( ){

    int a,b,c; Couta>>b;

    C=a+b;

    Cout

  • 8/3/2019 C++ Final Notes

    3/92

    #include

    #include

    #include

    void main()

    {

    int a=12345;

    clrscr();

    cout

  • 8/3/2019 C++ Final Notes

    4/92

    Constants

    Constants are expressions with a fixed value.

    Literals

    Literals are used to express particular values within the source code of a

    program. 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.

  • 8/3/2019 C++ Final Notes

    5/92

    Integer Numerals

    1776

    707

    -273

    They are numerical constants that identify integer decimal values.

    Floating Point Numbers

    They express numbers with decimals and/or exponents. They can include eithera 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:

    3.14159 // 3.14159

    6.02e23 // 6.02 x 10^231.6e-19 // 1.6 x 10^-19

    3.0 // 3.0

    These are four valid numbers with decimals expressed in C++.

  • 8/3/2019 C++ Final Notes

    6/92

    Character and string literals

    There also exist non-numerical constants, like:

    '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 (").

  • 8/3/2019 C++ Final Notes

    7/92

    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 valueFor example:

    #define PI 3.14159

    #define NEWLINE '\n

    This defines two new constants: PI and

    NEWLINE.

    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:

    const int pathwidth = 100;

    const char tabulator = '\t';

    Here, pathwidth and tabulator are two typed constants. They are treated just like

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

  • 8/3/2019 C++ Final Notes

    8/92

    Scope of variables

    A variable can be either of global or local scope. A global variable is a

    variable declared in the main body of the source code, outside all

    functions, while a local variable is one declared within the body of a

    function or a block.

  • 8/3/2019 C++ Final Notes

    9/92

    sizeof()This operator accepts one parameter, which can be either a type or a variable itself and

    returns the size in bytes of that type or object:

    a = sizeof (char);

    This will assign the value 1 to a because char is a one-byte long type.

    The value returned by sizeof is a constant, so it is always determined before program

    execution.

    Setbase() : this is used to convert the base of one numeric value to another base value.

    The general syntax used is :

    setbase(base value);

  • 8/3/2019 C++ Final Notes

    10/92

    Explicit type casting operator

    Type casting operators allow you to convert a datum of a given type to another.

    There are several ways to do this inC++

    . The simplest one, is to precede theexpression to be converted by the new type enclosed between parentheses (()):

    int i;

    float f = 3.14;

    i = (int) f;

    The previous code converts the float number 3.14 to an integer value (3), the

    remainder is lost. Here, the typecasting operator was (int). Another way to do

    the same thing in C++ is using the functional notation: preceding the expression

    to be converted by the type and enclosing the expression between arentheses:

    i = int ( f );

    int a,b; float c; a=3; b=2;

    c=(float) a/3;

    ++

  • 8/3/2019 C++ Final Notes

    11/92

    What Is a Function?

    A function is, a subprogram that can act on data and return a value. Every C++

    program has at least one function, main(). When your program starts, main() is

    called automatically. main() might call other functions, some of which might call

    still others.

    Each function has its own name, and when that name is encountered, the

    execution of the program branches to the body of that function. When the

    function returns, execution resumes on the next line of the calling function. This

    flow is illustrated in Figure

  • 8/3/2019 C++ Final Notes

    12/92

    Why Function?

    Well-designed functions perform a specific and easily understood task.

    Complicated tasks should be broken down into multiple functions, and

    then each can be called in turn. The key is to keep the level of

    complication low in each function. Dividing the problem into blocks and

    building larger solutions from the simplified blocks is a key concept in

    programming.

    Functions come in two varieties: user-defined and built-in. Built-in

    functions are part of your compiler package; they are supplied by the

    manufacturer for your use. The include files that you have used so far

    are examples of built-in functions.

  • 8/3/2019 C++ Final Notes

    13/92

    Declaring and Defining Functions

    The declaration tells the compiler the name, return type, and

    parameters of the function. The definition tells the compiler how

    the function works. No function can be called from any other

    function that hasnt first been declared. The declaration of a

    function is called itsprototype.

    The function prototype is a statement, which means that it ends

    with a semicolon. It consists of the functions return type, name,

    and parameter list. The parameter list is a list of all the parameters

    and their types, separated by commas. Example of the

    function prototype.

  • 8/3/2019 C++ Final Notes

    14/92

    The function prototype and the function definition must agree

    exactly about the return type, the name, and the parameter list. If

    they do not agree, you get a compile-time error. Note, however,

    that the function prototype does not need to contain the names of

    the parameters, just their types.

  • 8/3/2019 C++ Final Notes

    15/92

    Defining the Function

    The definition of a function consists of the function header and its body. The

    header is exactly like the function prototype, except that the parameters must

    be named, and there is no terminating semicolon.

    The body of the function is a set of statements enclosed in braces. Figure

    shows the header and body of a function.

  • 8/3/2019 C++ Final Notes

    16/92

  • 8/3/2019 C++ Final Notes

    17/92

    Default ParametersFor every parameter you declare in a function prototype and

    definition, the calling function must pass in a value. The value

    passed in must be of the declared type. Thus, if you have a

    function declared as

    long myFunction(int);

    the function must in fact take an integer variable. If the function

    definition differs or if you fail to pass in an integer, you get a

    compiler error.

  • 8/3/2019 C++ Final Notes

    18/92

    The one exception to this rule is if the function prototype declares a

    default value for the parameter. A default value is a value to use if none

    is supplied. The preceding declaration could be rewritten as

    long myFunction (int x = 50);

    Any or all of the functions parameters can be assigned default values.

    The one restriction is this: If any one of the parameters does not have a

    default value, no previous parameter can have a default value.

    If the function prototype looks like

    long myFunction (int Param1, int Param2, int Param3);

    you can assign a default value to Param2 only if you have assigned a

    default value to Param3. You can assign a default value to Param1 only

    if youve assigned default values to both Param2and Param3.

  • 8/3/2019 C++ Final Notes

    19/92

  • 8/3/2019 C++ Final Notes

    20/92

    Overloading Functions

    C++ enables us to create more than one function with the same name. This is

    called function overloading. The functions must differ in their parameter list, with

    a different type ofparameter, a different number of parameters, or both. Heres

    an example:

    int myFunction (int, int);

    int myFunction (long, long);

    int myFunction (long);

    myFunction() is overloaded with three different parameter lists. The first and

    second versions differ in the types of the parameters, and the third differs in the

    number of parameters.

    The return types can be the same or different on overloaded functions.

    However, different return types alone are not sufficient to distinguish between

    overloaded functions.

  • 8/3/2019 C++ Final Notes

    21/92

    // function overloading

    #include

    int Double(int);

    long Double(long);

    float Double(float);

    double Double(double);

    void main()

    {

    int myInt = 6500;

    long myLong = 65000;

    float myFloat = 6.5;double myDouble = 6.5e20;

    int doubledInt;

    long doubledLong;

    float doubledFloat;

    double doubledDouble;

    cout

  • 8/3/2019 C++ Final Notes

    22/92

    doubledFloat = Double(myFloat);

    doubledDouble = Double(myDouble);

    cout

  • 8/3/2019 C++ Final Notes

    23/92

    float Double(float original)

    {

    cout

  • 8/3/2019 C++ Final Notes

    24/92

    Inline Functions

    When you define a function, normally the compiler creates just one set of

    instructions inmemory. When you call the function, execution of the program jumps to those

    instructions, and when the function returns, execution jumps back to the next

    line in the calling function. If you call the function 10 times, your program jumps

    to the same set of instructions each time. This means there is only one copy of

    the function, not 10.

    There is some performance overhead in jumping in and out of functions. It turns

    out that some functions are very small, just a line or two of code, and some

    efficiency can be gained if the program can avoid making these jumps just to

    execute one or two instructions. When programmers speak of efficiency, they

    usually mean speed: The program runs faster if the function call can be

    avoided.

  • 8/3/2019 C++ Final Notes

    25/92

    If a function is declared with the keyword inline, the compiler does not

    create a real function: It copies the code from the inline function directly

    into the calling function. No jump is made; it is just as though you had

    written the statements of the function right into the calling function.

    Note that inline functions can bring a heavy cost. If the function is called

    10 times, the inline code is copied into the calling functions each of

    those 10 times. The tiny improvement in speed you might achieve is

    more than overshadowed by the increase in size of the executable

    program.

  • 8/3/2019 C++ Final Notes

    26/92

    Some of the situations where inline expansion

    may not work are:

    1. For functions returning values, if a loop , a switch, or a goto exist.

    2. For functions not returning values, if a return statement exist.

    3. If functions contain static variable.

    4. If inline functions are recursive.

  • 8/3/2019 C++ Final Notes

    27/92

    #include

    inline int Double(int);

    void main()

    {

    int target;cout > target;

    target = Double(target);

    cout

  • 8/3/2019 C++ Final Notes

    28/92

    Recursion

    Besides calling other functions, a function can call itself. This is

    called recursion, and recursion can be direct or indirect. It is direct

    when a function calls itself; it is indirect recursion when a function

    calls another function that then calls the first function.

    It is important to note that when a function calls itself, a new copy

    of that function is run. The local variables in the second version

    are independent of the local variables in the first, and they cannot

    affect one another directly, any more than the local variables in

    main() can affect the local variables in any function it calls.

  • 8/3/2019 C++ Final Notes

    29/92

    Empty for

    #include void main()

    {

    for (int i = 0; i

  • 8/3/2019 C++ Final Notes

    30/92

    Recursion

    Besides calling other functions, a function can call itself. This is

    called recursion, and recursion can be direct or indirect. It is direct

    when a function calls itself; it is indirect recursion when a function

    calls another function that then calls the first function.

    It is important to note that when a function calls itself, a new copy

    of that function is run. The local variables in the second version

    are independent of the local variables in the first, and they cannot

    affect one another directly, any more than the local variables in

    main() can affect the local variables in any function it calls.

  • 8/3/2019 C++ Final Notes

    31/92

    Apointer is a variable that holds a memory address of

    another variable.

    Advantages ofpointer :

    1. Pointers are more efficient in handling arrays and data table.

    2. Pointers can be used to return multiple values from a function via function

    arguments.

    3. Pointers allow C to support dynamic memory management.

    4. Pointer provide an efficient tool for manipulating dynamic data structures

    such as structure , linked lists, queues, stacks and tree.

    5. Pointer reduce length and complexity of programs.

    6. Pointer increase the execution speed and thus reduce the program

    execution time.

    pointer

  • 8/3/2019 C++ Final Notes

    32/92

    Accessing the address of a variable

    The actual location of a variable in the memory is system dependent . The

    address of a variable can be accessed by operator & immediatelypreceding a variable. For example

    Int *p, num;

    P= #

    Would assign the address of variable num to the pointer variable

    p. The & operator is called as address of .

  • 8/3/2019 C++ Final Notes

    33/92

    //Demonstrates address of operator and addresses of local

    variables

    #include

    void main()

    {

    int var1 =5;

    float Var2=6553;

    long sVar = -65535;

    cout

  • 8/3/2019 C++ Final Notes

    34/92

    Declaring and initializing pointer

    The declaration of a pointer variable takes the following form;

    data type * Pointer-name;

    1. the asterisk (*) tells that the variable Pointer_name is a pointer

    variable.

    2. Pointer_name needs a memory location.

    3. pointer_name points to a variable of type datatype.

    For Example;-

    int *p;

    Declares the variable p as a pointer that points to an integerdata type.

    float *x;Declares the variable x as a pointer that points to a floating point data type

    variable.

  • 8/3/2019 C++ Final Notes

    35/92

    The Indirection Operator

    The indirection operator (*) is used in two distinct ways with

    pointers: declaration and dereference. When a pointer isdeclared, the star (*) indicates that it is a pointer, not a normal

    variable, as in the following example:

    unsigned short * pAge = 0; // make a pointer to an unsigned short

    When the pointer is dereferenced, the indirection operator

    indicates that the value at the memory location stored in the

    pointer is to be accessed, rather than the address itself.

    *pAge = 5; // assign 5 to the value at pAge

    Also note that this same character (*) is used as the multiplication

    operator. The compiler knows which operator to call based on

    context.

  • 8/3/2019 C++ Final Notes

    36/92

    typedef unsigned short int USHORT;

    void main()

    {

    USHORT myAge; // a variableUSHORT * pAge = 0; // a pointer

    myAge = 5;

    cout

  • 8/3/2019 C++ Final Notes

    37/92

    POINTER INCREMENTSAND SCALE FACTOR

    When we increment a pointer, its value is increased by the length of the

    data type that it points to. This length called the scale factor.

    The length of various data type are as follows:

    char 1 byte

    int 2 bytes

    float 4 bytes

    long int 4 bytes

    double 8 bytes

  • 8/3/2019 C++ Final Notes

    38/92

    Assignment I

    MCA-II C++ Theory

    Assignment Submission date: 9-03-2010.

    1. Explain the History of c++ Language.

    2. Explain the data types in c++.

    3. Explain the Identifier , Keyword and constants with example.

    4. Explain the c++ operators with example.

    5. What is type casting or type conversion explain with example.

    6. Explain the manipulators available in c++.

    7. Explain the decision making statements, loop statements, break, goto , and continue,

    switch statement.

    8. What is an array? Explain the different types of array.

    9. What is function ? Explain the types and categories of function.Also Write the

    advantages of function .

    10.What is difference between call by value and call by reference ? Explain with

    example .11.What is recursion? Write a program to print the Fibonacci series using recursion.

    12.Explain the storage class specifiers .

    13.What is pointer? Explain pointers and array, pointers and structure with example.

    14.Explain the bit fields typed, typedef and enumeration.

    15.Explain the inline function.

    16.Explain the default value argument.

  • 8/3/2019 C++ Final Notes

    39/92

    Assignment I

    MCA-II C++ Theory

    Assignment Submission date: 10-03-2010.

    1. WAP to find the greatest number between three given numbers using conditional

    operator.

    2. WAP to enter the days and convert them into months and days.

    3. WAP to find the factorial of a given number.

    4. WAP to convert number into word. Like 145 -- one four five

  • 8/3/2019 C++ Final Notes

    40/92

    void main()

    {

    int i=10;

    i=!5>14;

    cout symbol. ! is a unary logical operator. !i (!10) is 0 (not of

    true is false). 0>14 is false

    (zero).

  • 8/3/2019 C++ Final Notes

    41/92

    void inword(int n);

    void main()

    {

    int a;

    clrscr();

    couta ;

    inword(a);

    getch();

    }

    void inword(int n)

    {charwtab[]={"Zero","One","two","three","four","five","six","seven","eight","nine"};

    if(n>9)

    {

    inword(n/10);

    }

    cout

  • 8/3/2019 C++ Final Notes

    42/92

    #include

    #define a 10

    main()

    {

    #define a 50

    out

  • 8/3/2019 C++ Final Notes

    43/92

    #define clrscr() 100

    main()

    {

    clrscr();

    cout

  • 8/3/2019 C++ Final Notes

    44/92

    main()

    {

    int i=400,j=300;

    printf( %d %d );

    }

    Explanation:

    printf takes the values of the first two assignments of the program.Any

    number of printf's may be given. All of them take only the first two

    values.

  • 8/3/2019 C++ Final Notes

    45/92

    const Argument

    In C++, an argument to function can be declared as const .This

    type of declaration is significant only when we pass arguments by

    reference or pointers. The qualifierconst tells the compiler that the

    function should not modify the argument. The compiler will

    generate an error when this condition is violated.

    For example :

    int swap(const int *p, int * q, int * r);

  • 8/3/2019 C++ Final Notes

    46/92

    Storage class specifiers

    1.Auto

    2.Extern

    3.Register4.Static

  • 8/3/2019 C++ Final Notes

    47/92

    External variable

    #include

    #include #include

    int count=1;

    void main()

    {int j;

    clrscr();

    fun();

    for(j=0;j

  • 8/3/2019 C++ Final Notes

    48/92

    Register variable

    Using registerkeyword we can declared the register

    variable. The register modifier tells the compiler to

    store a variable in such manner as to access to it as

    fast as is possible. For example ,

    registerint counter;

    The register keyword can be used only with local

    variables and function parameters.

  • 8/3/2019 C++ Final Notes

    49/92

    Static

    1. The static modifier causes a local variable to stay in

    existence throughout the life of a program.

    2. 2. All numeric variables of the static storage class are

    initialized to zero if they are not explicitly initialized by the

    programmer.

    3. Unlike automatic variables , static local variables retain

    their values when the function is exited.

  • 8/3/2019 C++ Final Notes

    50/92

    5050

    ObjectObject--Oriented ProgrammingOriented Programming

    Object-oriented programming (OOP) is associated

    with object-oriented design (OOD).

    There are fourprinciples ofOOD, i.e.

    1. Abstraction - take only important information

    2. Encapsulation - hiding or combine data and

    operations on data in a single unit.

    3. Inheritance -create new objects from existing objects.

    4. Polymorphism - the ability to use the same expression

    to denote different operations.

  • 8/3/2019 C++ Final Notes

    51/92

    51

    Abstraction in C++

    A

    bstraction is the process of separating thelogical properties from the implementation

    details.

    E.g. driving a car is a logical property; the

    construction of the engine constitutes the

    implementation details.

    We have an abstract view of what the engine

    does, but are not interested in the engines actual

    details implementation.

    Cl

  • 8/3/2019 C++ Final Notes

    52/92

    Class

    A class is a way to bind the data and its associated

    functions together. It allows the data and function to be

    hidden , if necessary, from external use. Generally , a

    class specification has two parts: -

    1.Class declaration: the class declaration describes the

    type and scope of its members

    2.class function definition: The class functiondefinition describe how the class function are

    implemented.

    Th l f t f l d l ti i

  • 8/3/2019 C++ Final Notes

    53/92

    The general format of a class declaration is :

    class class_name

    {

    access modifier:

    data type data member name;

    data type data member name;

    ..

    ..member function() declaration;

    .

    .

    };

    The body of class is enclosed within braces and terminated by a

    semicolon. The class body contains the declaration of variables

    and functions. These functions and variables are collectively

    called class members.

  • 8/3/2019 C++ Final Notes

    54/92

    Declaring a class in C++

    The class diagram for the Car class is as

    below:

    Car

    model:string

    Color:string

    Speed:int

    drive ( )

    stop ( )

    turn( )

    Our first step is to definea new class for our car:

    class Car

    {

    //Declare our Car class here

    };

    Class

    name

    attributes

    methods

  • 8/3/2019 C++ Final Notes

    55/92

    55

    Declaring a class in C++

    Next, we want to add theattributes which we havedefined for a car.

    In object-orientedprogramming, we refer to

    attributes as members of aclass, or data members.

    For the car object class, wedefine that the model andcolor are of type string, andspeed is an int.

    class Car

    {

    string model;string color;

    int speed;

    };

    Car

    Model:string

    Color:string

    Speed:int

    drive ( )stop ( )

    turn( )

  • 8/3/2019 C++ Final Notes

    56/92

    56

    Encapsulation

    Encapsulation is the idea t hat the internalworkings of an object can be hidden from theoutside world.

    Under the object-oriented paradigm, encapsulation

    is performed in two ways:

    We encapsulate the details of how attributes arestored.

    We encapsulate the details of how methods are

    performed.

  • 8/3/2019 C++ Final Notes

    57/92

    57

    Encapsulation

    Why would we want to encapsulate objects?

    In terms of object-oriented programming, we reduce the

    need for outside users to worry about how something is

    done.

    This provides significant benefits in the area of program

    maintenance we can change those details without the

    users ever being aware (provided that the outside

    interface remains the same).

  • 8/3/2019 C++ Final Notes

    58/92

    58

    Encapsulation in C++

    The concept ofencapsulation is embodied inC++ classs by allowing us to restrict access

    to an objects members.

    This is accomplished by a set of keywordsused to describe access privileges:

    1. private

    2. public

    3. protected

    4. friend

  • 8/3/2019 C++ Final Notes

    59/92

    59

    Encapsulation in C++

    private : If a classs members are declared as private,

    then they are not accessible to anything exceptfor the object itself.

    Thus, the only place where the scope of aprivate member would be valid is within the

    objects behaviors/methods.

    By default, all members of a C++ class aredeclared as private.

  • 8/3/2019 C++ Final Notes

    60/92

    60

    Encapsulation in C++

    public:

    Members that are declared as public are

    fully accessible to the outside world.

    Any public member can be accessed by

    any other C++ object .(assuming that the

    scope is valid).

  • 8/3/2019 C++ Final Notes

    61/92

    61

    Encapsulation in C++

    If we leave the class declaration as it is, all of the memberswill beprivate (default).

    We could accomplish the same result by explicitly

    including theprivate keyword.

    class Car

    {

    string model;

    string color;

    int speed;

    };

    class Car

    {

    private:

    string model;

    string color;

    int speed;

    };

    Same

  • 8/3/2019 C++ Final Notes

    62/92

    62

    Encapsulation in C++

    If we want all of the members to bepublic,

    then we must use thepublickeyword.

    class Car{

    public:

    string model;

    string color;

    int speed;

    };

    All public

  • 8/3/2019 C++ Final Notes

    63/92

    63

    Encapsulation in C++

    We can mix-and-match keywords in orderto obtain different combinations.

    class Car {

    string model;

    public:

    string color;int speed;

    };

    class Car {

    public:

    string model;

    string color;private:

    int speed;

    };

    public

  • 8/3/2019 C++ Final Notes

    64/92

    64

    C++ Method Declarations

    Object behaviors are implemented in C++using functions that are referred to asmethods.

    Amethod(also known as a memberfunction)

    is a function that is defined within a class. Instances of an object class can execute all

    of the methods that their class defines.

    Just as with any function, the first step in

    writing a method is to determine itsinterface/header.

    The interface is simply the name of themethod, theparameters it requires, and its

    returnv

    alue.

    Object

  • 8/3/2019 C++ Final Notes

    65/92

    Object

    In c++ , the class variables are known as object. It is

    also called the instance of class.

    Creating Object:

    class name objectname;For example,

    class abc

    {

    int number;

    float cost;

    public:void getdata(int a, float b);

    void disp();

    } ab,bc;

    would create the objects ab and bc.

    abc x,y;

    Would create the objects x

    and y of type abc ( class).

  • 8/3/2019 C++ Final Notes

    66/92

    Accessing class members

    The private data of a class can be accessed only through the

    member function of that class. The main() cannot access private

    data directly. The following is the format for calling a member

    function:

    object-name.function-name( actual-arguments);

  • 8/3/2019 C++ Final Notes

    67/92

    Defining member functions

    Member functions can be defined in two places:

    outside the class definition

    inside the class definition

  • 8/3/2019 C++ Final Notes

    68/92

    Outside the class definition

    The general form of a member function definition is :

    Return type class-name :: function-name ( argument declaration)

    {

    function body;

    }

  • 8/3/2019 C++ Final Notes

    69/92

    Inside the class definitionClass item

    {

    int qty;float price;

    public:

    void getdata( )

    {

    coutqty>>price;

    }

    void putdata() // inline function

    {

    cout

  • 8/3/2019 C++ Final Notes

    70/92

    class item

    {

    int qty;

    float price;

    public:

    void getdata(int a, float b);

    void disp()

    {

    cout

  • 8/3/2019 C++ Final Notes

    71/92

    Making an outside function inline

    class item

    {

    int qty;

    float price;

    public:

    void getdata(int a, float b);

    };

    inline void item:: getdata(int a, float b)

    {

    qty=a;

    price=b;

    }

    Nesting of Member Functions

  • 8/3/2019 C++ Final Notes

    72/92

    Nesting of Member Functions

    A member function can be called by using its name inside another function of the same

    class. This is known as nesting of member function.

    class abc

    {int x,y;

    public:void input();void disp();

    int larg();

    };

    int abc:: larg()

    {

    if(x>y)return (x);

    else

    return (y);

    }

    void abc::input()

    {coutx>>y;

    }void abc::disp()

    {

    cout

  • 8/3/2019 C++ Final Notes

    73/92

    Private Member Functions

    A private member function can only be called by another

    function that is a member of its class. An object cannot

    invoke a private function using the dot operator.

    class xyz{

    int a;

    void read();

    public:

    void update();

    void write();};

    If x is an object ofxyz , then

    x.read(); // is illegal ,object cannot access

    //private members

    The function read() can be called bythe function update() to update the

    value ofa.

    void xyz :: update()

    {

    read();

    }

    Arrays of objects

  • 8/3/2019 C++ Final Notes

    74/92

    class emp

    {

    char name[40];

    int age;

    public:

    void getdata();

    void putdata();

    };

    Void emp::getdata()

    {

    coutname;

    coutage;}

    Void emp::putdata()

    {

    cout

  • 8/3/2019 C++ Final Notes

    75/92

    j g

    class time

    {

    int hours;

    int minutes;

    public:

    void gettime( int h, int m)

    { hours=h; minutes=m}

    void puttime()

    {cout

  • 8/3/2019 C++ Final Notes

    76/92

    Friend Function

    The Private members cannot be accessed from

    outside the class , means one class cannot be

    accessed the private members of other class. C++

    allows the common function to be made friendly to

    have access to the private data of these classes.

    Such a function need not be a member of any of

    these classes . It is declared using the keywordfriend.

    Characteristics of friend function

  • 8/3/2019 C++ Final Notes

    77/92

    Characteristics of friend function

    1. It is not the scope of the class to which it has been declared

    as friend.

    2. It can not be called using the object of that class.

    3. The function definition does not use either the keyword

    friend or the scope operator:: .

    4. It can be declared either in the public orprivate part of a

    class without affecting its meaning.

    5. It can be invoked like a normal function without the help of

    any object.

    6. Usually , it has the objects as arguments.

    Declaration of friend function

  • 8/3/2019 C++ Final Notes

    78/92

    Declaration of friend function

    class class-name

    {

    -------

    ---------

    public:

    friend void function-name();

    };

    class abc

  • 8/3/2019 C++ Final Notes

    79/92

    {

    int a;

    int b;

    public:

    void setv()

    { a=10;

    b=20;

    }friend float mean( abc

    p);

    };

    float mean( abc p)

    {return float(p.a+p.b)/2;

    }

    int main()

    {

    abc x;

    x.setv();

    cout

  • 8/3/2019 C++ Final Notes

    80/92

    y

    class abc

    {

    int x;public:

    void set(int i)

    { x=i; }

    friend void max(xyz, abc);

    };

    class xyz

    {

    int a;

    public:

    void st(int i){ a=i; }

    friend void max(xyz, abc);

    };

    void max(xyz m, abc n)

    {

    if(m.a>n.x)cout

  • 8/3/2019 C++ Final Notes

    81/92

    Static membervariables are normally used to maintain values

    common to the entire class. Static Keyword is used to create

    static data member. A static member variable has certain

    special characteristics. These are:

    1. It is initialized to zero when the first object of its class is

    created . No other initialization is permitted.

    2. Only one copy of that member is created for the entire

    class and is shared by all the objects of that class.

    3. It is visible only within the class , but its lifetime is the

    entire program.

    class item int main()

  • 8/3/2019 C++ Final Notes

    82/92

    class item

    { static int count;

    int number;

    public:

    void geta(int a)

    { number=a;

    count++;

    }

    void showcount()

    {cout

  • 8/3/2019 C++ Final Notes

    83/92

    Static member function: A member function

    that is declared static has the following properties :

    1. A static function can have access to only

    other static members( functions or variables)

    declared in the same class.2. A static member function can be called using

    the class name( instead of its objects) as

    follow:-

    class-name::s_function-name();

    class test

    {

  • 8/3/2019 C++ Final Notes

    84/92

    {

    int code;

    static int count;

    public:

    void setcode()

    { code=count++;

    }

    void showcode()

    {

    cout

  • 8/3/2019 C++ Final Notes

    85/92

    {

    float x;

    float y;

    public:

    void input(float a, float b){ x=a;

    y=b;

    }

    void show(test);

    friend test sum(test , test);

    };

    test sum(test c1, test c2)

    {

    test t3;

    t3.x=c1.x+c2.x;

    t3.y=c1.y+c2.y;return (t3);

    }

    void test::show(test c)

    {

    cout

  • 8/3/2019 C++ Final Notes

    86/92

    class item

    {

    int code;

    float price;

    public:

    void getdata(int a, float b)

    {

    code=a;price=b;

    }

    void show()

    {

    cout

  • 8/3/2019 C++ Final Notes

    87/92

    WAP to define a class to represent a bank

    account . include the following data members:

    name of depositor, account number, type of

    account, balance amount and member

    functions : to assign initial values, to deposit an

    amount , to withdraw an amount after checking

    the balance , to display name and balance.

    CONSTRUCTORS

  • 8/3/2019 C++ Final Notes

    88/92

    CONSTRUCTORS

    A constructor is a special member function whose task is to

    initialize the objects of its class. Its name is the same as the class

    name. The constructor is invoked whenever an object of its

    associated class is created.

    A constructor is declared and defined as follows:

    class import

    {

    int m,n;

    public:

    import(); // constructor declared.

    };

    Import::import() // constructor defined.

    {

    .

    }

    };

    FEATURES OF CONSTRUCTORS

  • 8/3/2019 C++ Final Notes

    89/92

    1. Constructor should be declared in public section.

    2. They are invoked automatically when the objects arecreated.

    3. They do not have return type.

    4. They con not be inherited.

    5. Constructor cannot be virtual.

    6. We cannot refer to their addresses.

    Note: when a constructor is declared for a class ,

    initialization of the class objects becomes mandatory.

    TYPE OF CONSTRUCTORS

  • 8/3/2019 C++ Final Notes

    90/92

    TYPE OF CONSTRUCTORS

    1. Default constructor

    2. Parameterized constructor

    3. Copy constructor

  • 8/3/2019 C++ Final Notes

    91/92

    1. Default constructor

    Parameterized constructor

  • 8/3/2019 C++ Final Notes

    92/92

    Parameterized constructor

    The constructors that can take arguments are called parameterized constructor.

    class import

    {

    int m,n;

    public:

    import ( int x, int y)

    {

    m=x;

    n=y;

    }

    };

    imort obj1(100, 200); // calling of constructor.

    Constructor can be call in two way:-

    import obj1= import(10,20); // explicit call

    or

    import obj1(23,45); // implicit call