newcpp

download newcpp

of 17

Transcript of newcpp

  • 8/22/2019 newcpp

    1/17

    Procedure oriented programming

    Some characteristics exhibited by POP are :

    Emphasis is on doing things (algorithm)

    Large programs are divided into smaller programs known as function.Most of the functions share global data.

    Dave move openly around the system.

    Functions transform data from one form to another.Employs top-down approach in program.

    Object-oriented programming paradigm

    Object oriented programming treats data as critical element in theprogram development and does not allow it to flow freely around the system,if ties data more closely to the function that operate on it, and protects it

    from accidental modification from outside function. OOP allowsdecomposition of a problem into a number of entities called objects and thenbuilds data and function around there objects. the organization of data and

    function in OOP is shown below:

    Object A Object - B

    Object - C

    Data

    Functions

    Data

    Functions

    Main function

    Function 1 Function 2 Function 3

    Function 4 Function 5 Function 6 Function 7

  • 8/22/2019 newcpp

    2/17

    Functions

    Data

    Fig : Organization of data and function in OOP

    SOME OF THE FEATURES OF OOP ARE:

    - Emphasis is on data rather than procedure

    - Programs are divided into what are known as object.- Date structure are designed such that they characterize the objects.

    - Functions that operate on the data of an object are tied together in

    the data structure.- Data is hidden and can not be accessed by external function.- Objects may be communicate with each other through function.

    - New data and function can be easily added whenever necessary- Follows bottom of approach in program design.

    BASIC CONCEPT OF OOP

    There includes:-- Objects

    - Classes- Data abstraction and encapsulation

    - Inheritance

    - Polymorphism

    - Dynamic binding

    - Message passing

    OBJECT

    Objects are basic run time entities in an object-oriented system. They mayrepresent in person a place, a bank account, a table of data or any item that

    the program has to handle. They may also represent user defined data suchas vectors time and lists.

    Each objects contains data and code to manipulate the data.Objects caninteract without having to known details of each others data or code.

    OBJECT: STUDENT

    DATA

    NameDate of birth

    Marks

  • 8/22/2019 newcpp

    3/17

    FUNCTIONS

    TotalAverage

    CLASSES

    Objects are containing data and code to manipulate that data. Theentire set of data and code of an object can be made a user defined datatype with the help of classes.

    Objects are variable of the class. Once a class has been defined, we cancreate any number of object belonging to that class. Each object isassociated with the data of type class with which they are created.

    A class thus a collection of objects of similar type, For example:mango, apple and orange are members of the class fruit.

    Classes are user-defined data types and behave like the built in types

    of a programming language.

    DATA ABSTRACTION & ENCAPSULATION

    The wrapping up of data and function into a single unit is known asencapsulation. Data encapsulation is the most striking feature of a class. The

    data is not accessable to the outside world, and any those function, whichare wrapped in the class, can access it.

    Abstraction refers to the act of representing essential features

    without including the background details or explanations. Classes are theconcept of abstract attributes suchas size, weight and cost, and functions to

    operate on these attributes, The attributes are some-times called datamembers.

    Since the classes are the concept of data abstraction, they are knownas abstract data types(ADT)

    INHERITANCE

    Inheritance is the process by which objects of one class acquire theproperties of objects of another class.

    In OOP, the concept of inheritance provides the idea of reusability. This

    means that we can add additional features to an existing to an class without

    modifying it. This is possible by deriving a new class from the existing one.The new class will have the combine feature of both the classes.

    Inheritance is a technique of information in a hierarchical form. it islike a child inheriting the features of its parents.

    The technique of building new classes from the existing classes

    is called inheritance

    Forms of inheritance:

  • 8/22/2019 newcpp

    4/17

    The derived class inherits some or any of the features of the base classdepending on the visibility mode and level of inheritance.

    - single inheritance

    - multiple inheritance

    - hierarchical inheritance- multilevel inheritance

    - hybrid inheritance

    - multipath inheritance

    POLYMORPHISM

    Polymorphism, a Greek term, means the ability to take more thanone form. It is a mechanism, that allows a single name/operator to be

    associated with different operations depending on the type of data passed toit. In C++ it is achieved by function overloading, operator overloading,dynamic binding (virtual function).

    See the following Figure that a single function name can be used to

    handle different number and different types arguments. Using a singlefunction name to perform different types of tasks is known as function

    overloading.

    DYNAMIC BINDING

    Binding refers to the linking of a procedure call to the code to theexecuted in response to the call. Dynamic Binding means the code associated

    with the given procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance.

    MESSAGE PASSING

    An OOP consist a set of objects that communicate with each other steps:

    1. Creating classes that define objects and its behaviour2. Creating objects from class definations.

    3. Establishing communication among objects.

    Objects communicate with one another by sending and receivinginformation.

    employee.salary(name);

    object message information

    Shape

    Draw()

    Circle object

    Draw(circle)

    Box object

    Draw (box)

    Triangle Obj.

    Draw(triangle)

  • 8/22/2019 newcpp

    5/17

    Message passing involves specifying the name of the object, the name

    of the function (manage)&the information to be sent.

    ADVANTAGES/BENEFITS OF OOP

    OOP offers several benefits to both the program designer and the user.The main advantages are:

    1. Through inheritance, we can eliminate redundant code and extend the

    use of existing classes.2. We can build programs from the standard working modules that

    communicate with one another.

    3. The principles of data hiding the programmer to build secure program.4. It is possible to have multiple instances of an object to co-exist

    without any interference.5. It is possible to map objects in problem domain.6. It is easy to partition the work in a project based on objects.7. System can be easily operated.

    8. Software complexity can be easily managed.

    APPLICATION OF OOP

    The promising areas application of OOP include:- Real-Time system

    - Simulation and modeling- Object oriented database

    - Hyper text, Hyper media and expertext

    - Al and expert system

    - Neural network and parallel programming- Decision support and office automation system

    - CIM/CAM/CAD systems.

    EXAMPLES OF OOP : C++, JAVA, ADS, Eiffel, Simula, Smalltalk

    Basic Structure of C++

    Include files

    Class declaration

    Member functions definitions

    Main function program

  • 8/22/2019 newcpp

    6/17

    It is common practice to organize a program into three separate files.The class declarations are placed in a header file and the definitions of

    member functions go into another file. This approach enables theprogrammer to separate the abstract specification of the interface (class)from the implementation details. Finally the main program that uses theclass is places in a third file which includes the previous two files as

    well as any other files required.

    Application of C++

    These include: -- C++ allows us to create hierarchy related objects.

    - C++ able to make the real world problems.

    - C++ programs are maintainable and expendable when new featuresneed to be implemented.

    - C++ will replace C as general-purpose language.

    Some of the claimed advantages of C++ are: -

    New programs would be developed in less time because old

    code can be reduced.

    Creating and using new data types would be easier than C.

    The memory management in C++ would be easier and more

    transparent.

    Programs would be less bug-prone, as C++ uses a stricter

    syntax and type checking. Data hiding , the usage of data by one part while other

    program part while other program parts cannot access the data,would be easier to implement with C++.

    Introduction to tokens: -

    - Keyword

    - Identifier- Constant

    - String

    - Operator

    Keyword

    The keyword implement specific C++ language features. They are explicitly

    reserved identifiers cannot be used as names for the names for the programsvariable or other user-defined program elements.

    Key words are reserved to the compiler for use by the language. You cannotdefine classes, variables, or the function that have these keywords as their

    names. The list is a bit arbitrary, as some of the keywords are specific are toa given compiler.

  • 8/22/2019 newcpp

    7/17

    Auto break case char class constContinue default delete do double else

    Enum extern float for friend goto etc.

    Identifier &constant

    Identifiers refer to the name of variable, function, array etc.

    They are the fundamental s requirement of any language has its own rulesfor naming there identifiers:

    Rules:- Only alphabetical character, digit and underscore are permitted.

    - The name cannot be start with a digit.- Uppercase and lowercase letters are significant.

    - A declared keyword cannot be used as a variable name.

    Constant refer to fixed value that do not change during the execution of aprogram C++ support several kinds of literal constant. They include integer,

    character, floating-point number and string. Literal constant do not havethe memory location.

    Example:

    123 decimal integers12.34 floating point

    a character constantsC++ string constant

    C++ also recognize backslash character constant available in C.

    What is variable?

    In C++ a variable is a place to store the information. A variable isallocation in your computers memory in which you can storea value and from you can retrieve that value. Your computers

    memory can be viewed as a series of cubbyholes. Each cubbyhole isone of many, many such holes all lined up. Each cubbyholes or

    memory location is numbered sequentially. These numbers areknown as memory address.

    Table: Variable Types.

    Type Size Value

    unsigned short int 2 bytes 0 to 65,535

    short int 2 bytes -32,768 to 32,767

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

    long int 4 bytes -2,147,483,648 to2,147,483,647

    int(16 bit) 2 bytes -32,768 to 32,767

    int(32 bit) 4 bytes -2,147,483,648 to

    2,147,483,647

  • 8/22/2019 newcpp

    8/17

    unsigned int(16 bit) 2 bytes 0 to 65,535

    unsigned int(32 bit) 4 bytes 0 to 4,294,967,295

    Char 1 byte 256 character values

    Float 4 bytes 1.2e-38 to 3.4e38

    Double 8 bytes 2.2e-308 to 1.8e308

    Reference Variable

    C++ introduced a new kind of variable. A reference variable provides an alias

    for a previously defined variable. For example, if we make the variable sum areverence to the variable total, then sum and total can be used

    interchangeably to represent variable. A reference variable is created asfollows:

    Data-type & reference-name = variable nameExample:

    float total=100;float &sum=total;

    Total is a float variable that has already been deceleration; sum is the

    alternative name declared to represent the variable total. Both the variablerefers to the same data object in the memory. Now the statements: -

    Cout

  • 8/22/2019 newcpp

    9/17

    you use the operator with nothing in front of it. Heres an example that showsglobal scope resolution for both a variable and a function.

    #include

    int counter = 50; //global variableint main()

    {for(register int counter = 1; //this refers to the

    counter < 10; //local variablecounter++){

    printf(%d/n,::counter) //global variable

    printf(%d\n,counter); //local variable}

    return(0);}

    In this code fragment the scope operator is used to address a global variableinstead of the local variable with the same name.MEMBER DEREFERENCING OPERATORS

    Operator Function

    ::* to declare a pointer to a member of a class

    * to access a member using object name and apointer to that member

    ->* to access a member using a pointer to theobject and a pointer to that member

    MEMORY MANAGEMENT OPERATORS

    new and delete

    The C++ language defines two operators, which are specific for the allocationand de-allocation of memory. These operators are new and delete.

    Pointer-variable = new data-type

    The most basic example of the use of these operators is given below. An int

    pointer variable is used to point to memory, which is allocated by the operatornew. This memory is later released by the operator delete.

    int *ip;ip = new int;

    //any other statements

    delete ip;

    Note that new and delete are operators and therefore do not requireparentheses, which are required for functions like malloc() and free(). The

    operator delete returns void, the operator new returns pointer to the kind ofmemory thats asked for by its argument

  • 8/22/2019 newcpp

    10/17

    Allocating and de-allocating arrays

    When the operator new is used to allocate an array, the size of the variable isplaced between square brackets following the type.

    int *intarr;

    intarr = new int[20]; //allocates 20 ints

    The syntactical rule for the operator new is that this operator must be followedby a type, optionally followed by a number in square brackets. The type andnumber specification lead to an expression, which is used by the compiler todeduce its size in C an expression like sizeof (int [20]) might be used.

    An array is de-allocated by using the operator delete:

    delete [] int arr;

    in this statement the array operator [] indicate that an array is being de-allocated. The rule of thumb here is whenever new is followed by [], deleteshould be followed by it too.

    The new operator offers the following advantages over the function malloc()

    1. It automatically computes the size of the data object

    2. It automatically returns the correct pointer type3. It is possible to initialize the object while creating the memory space4. Like any operator, new and delete can be overloaded

    MANIPULATORS

    MANIPULATORS are operators that are used to format the data display. The

    most commonly used manipulators are endl and setw.

    The endl operator, when used in an output statement, cause a linefeed to be

    inserted. It has the same effect as using the new line character \n.For example:

    cout

  • 8/22/2019 newcpp

    11/17

    cout

  • 8/22/2019 newcpp

    12/17

    printf(%d,y);}

    A function definition also known as function

    implementation and include the following elements :

    1. Function Name2. Function Type

    3. List of parameters4. Local variable declaration5. Function statements6. A return statement (if function return a value)

    A general format of a function definition to implement

    these elements is given below.

    RETURN BY REFERENCE

    A Function can also return a reference. Consider the following function.

    int & max(int &x ,int &y)

    {if (x>y)

    return x;else

    return y;}

    since return type of max() is int &, the function return reference to x ory (and not values). Then a function call such as max(a,b) will yield a reference

    to either a or b depending on their values.

    INLINE FUNCTION

    When a function is called, it takes a lot of time in executing a series ofinstructions for task such as jumping to the function, saving registers, pushingarguments into the stack and returning to the calling function. When function

    function_type function_name(parameter list){

    local variable declaration;

    execuatable statement1;

    execuatable statement2;

    return statement;

    }

  • 8/22/2019 newcpp

    13/17

    is small, a substantial percentage of execution time may be spent in suchoverhead. To eliminate the cost of calls to small function, C++ proposes a newfeature called inline function. It is expanded inline when it is invoked.

    Some of the situation where inline expansion may not work are :

    1. for function returning values.

    2. for function not returning values, if a return statement exists.3. if function contain static values.

    4. if inline function is recursive.

    FUNCTION OVERLOADING

    Overloading term refers to the use of the same thing for differentpurpose. C++ also permits overloading of functions. This means that we can

    use the same function name to create functions that perform a variety ofdifferent task. This is known as function polymorphism in OOP.

    Declaration.

    int add(int a, int b); //prototype 1

    int add(int a, int b, int c); //prototype 2double add (double a, double b); //prototype 3

    double add (int p, double q); //prototype 4

    The compiler first tries to find an exact match in which the types ofactual arguments are the same and use that function.

    If an exact match is not found, the compiler uses the integralpromotions to the actual arguments, to find the match.

    If all the steps fail, then the compiler will try the use defineconversion in combination with integral promotions and built in conversions

    to find a unique match.

    SPECIFYING A CLASS

    inline function_header

    {function body

    }

    class class_name

    {private:

    variable declaration;

    function declaration;public:

    variable declaration;

    function declaration;};

  • 8/22/2019 newcpp

    14/17

    The class declaration is similar to struct declaration. The keywordclass specifies that what follows is an abstract data of type class_name.

    The class body contains declaration of variable and functions.

    These functions and variable are called members. They are usually groupedunder two sections, private and public, the visibility labels of class.

    By default, class member are Private, and they are only accessedwithin the class. The public members can be accessed from outside the class

    also. The variables declared inside the class are known as data members andfunctions are known as member functions. The binding of data and functionstogether into a single class-type variable are referred as encapsulation.

    PRIVATE MEMBER FUNCTION

    A private member function can only be called by another functionthat of its class. Even an object cannot invoke a private member function

    using dot operator.

    Example:class sample

    {int m;

    void read(void);public:

    void update(void);void write (void);

    };

    if s1 is an object of sample class, thens1. read(); //would not work; object cannot access private

    members.

    Therefore, the function read() can called by function update orwrite () function only.

    Void sample :: update(void){

    read();}

    STATIC DATA MEMBERS

    A data member of class can be qualified as static. The properties

    of static member variable are similar to that of C static operator.It is initialized to zero when the first object of its class is

    created. No other initialization is permitted.Only one copy of that member crated for the entire class and is

    shared by all the objects of that class.It is visible only within the class, but its lifetime is the entire

    program.int item :: count; // definition of static data member

  • 8/22/2019 newcpp

    15/17

    The type and scope of each static member variable must bedefined outside the class definition. Here item is a class and count is a staticdata member.

    Object 1 object 2 object 3no. no. no.

    (static data member : count , shared by all object)

    STATIC MEMBER FUNCTION

    Like static data member variable, we can have static member functionalso. It have following properties.

    A static function can have access to only other static members(function or variables) declared in same class.

    A static member function can be called using the class name(instead of object) as follows :

    class_name :: function_name

    Example :

    Class test

    {int code;

    static int count;public :

    void secode(void){

    code = ++count;}void show code (void){

    cout

  • 8/22/2019 newcpp

    16/17

    t2.setcode();test :: showcount();

    test t3;

    t3.setcode();

    test :: showcount();t1.showcode();

    t2.showcode();t3.showcode();

    }

    The output of the above program is :

    22

    123

    FRIEND FUNCTION

    There could be a situation where we would like two classes to share a

    particular function. In such situation, c++ allows the common function to bemade friendly with both the classes, there by allowing the function to haveaccess to the private data of these classes. Such function need not be amember of any of these classes.

    To make an outside function friendly, to class, we have to simplydeclare this function as a friend of the class as shown below in example.

    class ABC;class XYZ{

    int x;public:

    void setdata(int i){

    x=i;}

    friend void max(XYZ,ABC);};

    class ABC{

    int a;public:

    void setdata(int i){

    a=i;}

    friend void max(XYZ,ABC);};

  • 8/22/2019 newcpp

    17/17

    void max(XYZ m,ABC n){

    if ( m.x>=n.a )cout