C++Lang chap1

download C++Lang chap1

of 9

Transcript of C++Lang chap1

  • 8/11/2019 C++Lang chap1

    1/9

    CHAPTER 1

    General Concepts In C++

    1.1 Concepts of Object Oriented Programming

    Object oriented programming languages have developed in an evolutionary manner and have

    become very popular over the past few years. C++ is one such language. The C++ language is the

    key to increased productivity and improved reliability, even when a novice programmer uses it.

    Programming a computer is still one of the most difficult tasks ever undertaken by mankind.

    To become a proficient programmer, one needs to be talented, creative, intelligent and logical

    thinker. C++ is a new way of reasoning as to what it means to compute and how we can organize

    information inside a computer.

    1.1.1 What is an Object

    Putting it in the laymans language, an object is something that has a fixed shape or well definedboundary. If you look at your computer desk, you would notice several objects of varying

    descriptions. They may be connected to, or related to, adjacent objects. For example, a keyboard

    may be attached to a PC, and it is also easy to see that different parts of PC are distinct objects.

    You will observe two characteristic things about objects. Firstly, each object has certain dis-

    tinctions or attributes which enable you to recognize and classify it. For example, a chair has four

    legs, a seat, and a back rest. Secondly, each object has certain actions associated with it. For

    example, a chair declared as an object, can be moved from one place to another.

    In computer terms, an object is a collection of related variables and functions bound together to

    form a higher-level entity. The variables define the state of the object, while the functions define

    the actions that can be performed on the object. For example, a plastic scale is an object. It can be

    used to scale (measure) as well as draw lines. So the object scale can be used for two

    functions measure and draw lines.

    C++ programming language involves building a program or a system from objects, in the same

    way that we might build a car from its components. We may have to build some of these software

    objects ourselves, while others may be available to us from a library we have at our disposal. Thus

    we can think of a program as being constructed from a set of interrelated parts (modules) which

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    2/9

    4 Programming in C++ Part I

    activate each other by sending messages (information) to one other. Hence when a program in

    C++ is running, it works with components (modules) sending code to other components (modules)

    and causing them to execute.

    An object can be constructed, destroyed, and copied onto another object. It can also allocate a

    new object. This is achieved by using constructors and destructors; this determines how the

    objects of a class are created, or initialized, copied, and destroyed. Thus, object-oriented program-

    ming is a technique for writing good programs for a set of problems.

    1.2. What is a Class?

    The concept of class is best understood with an analogy. Out of the several objects in a room, let us

    talk about the picture on the wall. There is a class, which we can call the class of "Pictures" of

    which the picture on the wall is aninstance(meaning an example but in C++ terminology, the

    word "instance"). The picture in the room belongs to the class of pictures, which contains all pic-

    tures everywhere. Thus in C++, it is said "an object is an instance of a class", which means in our

    example that a "picture is an occurrence of the idea picture".

    Another example is a chair on which I am sitting. We can call it "My chair". The chair across

    the room is also an object. We can call this second chair "Her chair". Both these objects share cer-

    tain common characteristics or attributes (and associated actions which enable them to be recog-

    nized or classified as belonging to a singleChair Class.) Thus My chair and Her chair are two

    examples (instances) of the Chair Class but they exist independent of each other and the values of

    their characteristics or attributes differ. For example they occupy different positions in the room,

    their colours are different. Thus "Chair" is a class, but MyChair and HerChair are objects.

    1.2.1 Objects Declared as a ClassIn C++ programming, a class is a definition from which objects can be created. A sample example

    would be a "customer" class consisting of the definition of customer data and the proceses (re-

    ferred to as methods) which can act on it. This brings together data and all the processes which

    may act on it into a single unit. An individual object would have values defined for Customer

    Identification (ID), Name, and address. When the Customer class receives a message (namely,

    delete customer), it would activate the corresponding method to do this action.

    We shall try to understand, by a simple example in C++, as to how the idea explained above

    can be used.

    We have a function that gives us the square root of a value, and we might declare it as:

    float square_root();

    The above function works out square roots. It is recognized by the name "Square_root" and

    returns a value in the form of a floating point number. We can use it in the following assignment

    statement:

    x=square_root(y);

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    3/9

    Part I General Concepts In C++ 5

    The above statement in C++ has the effect of calling the function "square_root" and passing it

    the value of the variable "y". The function works out the square root of that value and passes it

    back as a floating point number. That value is then assigned to "x". The points to note are:

    (a) The function can be used exactly as shown above, that is, the function is used directly

    within the language as if it were a variable.

    (b) All functions within C++ have a data type which determines the form of the return value.

    For example, in the above case of square_root it is of the floating point type.

    An object when executed returns a value. The class defines the type of data returned by anobject. A class can be created for any data type.

    The data type of a function in C++ is similar to the "class" of an object, because the "class" of

    an object defines the data type and the structure or shape that an object can have.

    Diffe re nc e s be twe e n Ob je c ts a nd Func t ions

    The main difference between objects and functions is that a function is usually written to per-

    form only a single service such as the calculation of a square root. A class offers a range of differ-

    ent services, each of which is activated by a different message. The function that an object carries

    out is thus determined by the message that is sent to it.

    As an example, the class "number" could offer addition, subtraction, multiplication, division

    and exponentiation as services. Each would be invoked by a different message which would

    include a number as a parameter. Thus "number +1" would have the meaning: add 1 to the current

    value of number. "+1" is the message which is sent to the object "number", The "+" invokes the

    service of addition. Note that "1" is also an object which has value "1"; it is an instance or an

    example of the class "number".

    Thus for each class all the services that can be provided are defined once and for all. They are

    coded into the class and are never coded elsewhere. This is applied to any service which you may

    wish to provide on any organized data, no matter how complex it is. It could be printing or reading

    a record. It may also be searching a value in a table or arranging a table in a particular order.

    The two other parts defined in a class are:

    (a) Messages

    (b) Methods

    Messages. These are valid messages to which an object will respond. They are thelabelsfor the

    method. Suppose a guest comes to my house and I tell my wife to get two cups of tea. The messageI have given is clear and precise and is a valid message. My wife will get two cups of tea. Themethod to prepare the tea is none of my concern, because she may either prepare tea herself ororder the servant to do so, or she may bring the tea which was already prepared. I am only con-cerned with the final action. The action is to bring the two cups of tea.

    In an object oriented programming, the procedure of an action is hidden from the

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    4/9

    6 Programming in C++ Part I

    message giver.

    Another point to be noted in an object oriented programming is that the same message may be

    actioned differently by different objects. For example, if my father was only present in the house,

    and if I had told him to get two cups of tea, he might not have taken any action at all. Thus the

    message though clear is not valid for the object (i.e. for my father). However, the same message

    would have been valid for my mother, because she would have gladly brought the tea if my wife

    was not at home.

    The same message is executed differently by different objects.

    Thus we may conclude that an action is initiated in objected-oriented programming by the

    transmission of amessageto an agent (object) responsible for that action. The message encodes

    the request for an action, and is accompanied by an additional piece of information (arguments),

    needed to carry out the request. The receiver is the agent to whom the message is sent. If the

    receiver accepts the message, it accepts the responsibility to carry out the indicated action. In

    response to a message, the receiver will perform somemethodto satisfy the request.

    Methods. This is the processing which is carried out when a message is sent to an object. Amethod is defined for each message.

    1.3 Encapsulation

    In computer programming, a data type is defined in terms of the information it can contain and the

    operation that can be performed with it. An abstract data type is more generalized than one con-

    strained by the properties of the objects it contains. For example, the data type "pet" is more gen-

    eralized than the data types "pet dog", "pet bird", and "pet fish." The standard example used in

    illustrating an abstract data type is the stack, a small portion of memory used to store information,

    generally on a temporary basis. As an abstract data type, the stack is simply a structure onto which

    values can be pushed (added) and from which they can also be popped (removed). The type of

    value, such asinteger, is irrelevant to the definition.

    The way in which the program performs operations on abstract data types is encapsulated, or

    hidden, from the rest of the program. Thus encapsulation is the practice of including in an object

    everything it needs, (both data and processes) hidden from other objects in the system. The inter-

    nal state of an object is not directly accessible from outside, and cannot be altered by external

    changes to the application.

    Encapsulation enables the programmer to change the definition of the data type or itsoperations without introducing errors to the existing code that uses the abstract data type.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    5/9

    Part I General Concepts In C++ 7

    Abstract data types represent an intermediate step between traditional programming and the

    object oriented programming. Object oriented programming is the one in which a program is

    viewed as a collection of discrete objects which are self-contained collections of data structures

    and routines that interact with other objects. An object is an example of a class that can be used as

    a variable in a program. The object in C++ responds to messages, which are the principal means of

    communication.

    1.4 Data Hiding

    There is an important principle in regard to message passing the principle ofinformation hiding.

    In this principle, the client sending a request need not know the actual means by which the request

    will be honoured. In sending a message, there is a designated receiverfor that message. The

    receiver is some agent to whom the message is sent. The interpretation of the message (i.e. the

    method used to respond to the message) is dependent on the receiver, and can vary with different

    receivers. For example, in the case of the request of getting two cups of tea, I made a mistake when

    I requested my father to bring two cups of tea, as my father is elder to me and he might have felt

    bad in accepting this message. Thus, he may not act upon my request and issue an error diagnostic

    by his gesture or action.

    The aim of data hiding is to make all modules as independent of one another as possible. It

    provides a number of benefits namely one can use a module without having to think about how it

    works. Another benefit is locality. By locality, we mean the change to one part of the program

    does not require changes in other parts of the program.

    1.4.1 Classes and Instances

    All objects are instances (examples) of a class. The method induced by an object in response to a

    message is determined by the class of the receiver. All objects of a given class use the same

    method in response to a similar message. For example, the message: "bring two cups of tea" given

    to a hotel bearer will convey the same message whether the bearer belong to a 5 Star or 3 Star

    hotel. The message is conveyed to bearerclassand he/she will manage to "get the two cups of

    tea".

    1.5 Inheritance

    Inheritance is defined as the property of objects by which instances of a class can have access to

    data and method of definitions contained in a previously defined class, without those definitions

    being restated.

    Classes are linked together in a hierarchy. They form a tree, whose root is the class of "ob-jects". Each class (except for the root class) will have a superclass (a class above it in the hierar-

    chy) and possibly subclasses. A class caninherit(i.e. acquire) methods from its superclass and in

    turn can pass methods on to its subclasses.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    6/9

    8 Programming in C++ Part I

    We can understand the concept of inheritance by studying Figure 1.1. This figure shows a

    rough hierarchy of life forms, constructed using familiar nouns. In the figure, each noun in the

    hierarchy is asubsetof the noun above it and asupersetof the noun below it. In effect, the nouns

    inherit qualities from each other. In order to define each noun we only need to define its distin-

    guishing features in terms of the noun above it in the hierarchy. Thus if we know that a cat is a

    mammal, we also know that it suckles its young, that it is warm-blooded etc. It inherits these

    qualities by virtue of being a mammal.

    Monkeys which are at the samelevelas the class cat in this hierarchy, also inherit these quali-

    ties. In terms of this hierarchy, we only need to define the distinguishing features of the cat family,

    if the superclass of mammal is well defined. Thus we only need to define that its members have

    claws, eat meat and so on. This classification is an efficient way of condensing information.

    Figure 1.1

    Hierarchy of life forms

    Another example of inheritance is a pie chart. A pie chart can be further broken down into a

    circle and sectors. Suppose we now want to create a Circle Class. We can see that this class should

    Life

    Flora Fauna

    Animals Insects

    Birds Mammals

    Monkeys Cats

    Lions

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    7/9

    Part I General Concepts In C++ 9

    have all the instance variables and methods of Point Class. We would need an additional instance

    variable, "Radius. Thus we would inheritfrom Point Class, a new child class, the Circle Class

    (also called subclass). Of course, we would also need to define one instance variable, Radius.

    Inheritance is always transitive. A class can inherit features from superclasses many levels

    away. For example, if Dog is a subclass of class Mammal, and class Mammal is in turn a subclass

    of class Animal, then Dog will inherit attributes both from Mammal and from Animal. Similarly, a

    florist (one who sells flowers) will have a certain behaviour because a florist is also a shopkeeper.

    Thus we can expect a florist to accept money for the sale of flowers. Such an activity is not unique

    to florists, but is common to all shopkeepers such as bakers, grocers, stationers, toy store owners,

    etc. because they all belong to a subclass of shopkeepers.

    Briefly, inheritance means that the behaviour and data associated with child classes are always

    an extension of the proprieties associated with parent classes. A subclass must have all the prop-erties of the parent class, and those of others as well.

    1.5.1 Multiple Inheritance

    Another variant of inheritance is the idea of multiple inheritance. This is the ability of a class to

    inherit from more than one parent class. A simple example of where this might be useful is given

    by the idea of a "contract programmer". We might define such an individual to have inherited

    some of the attributes or characteristics of a programmer and some of the attributes of a contract

    worker (namely, the one who has a contract for a particular duration). Thus methods can also have

    be multiple inheritance. In the above example, the methods of "hire subcontractor", assign task to

    programmer are both inherited by the contract programmer class.

    Ad va nta ge s o f I nher ita nce Some of the important benefits of inheritance are:

    (a) Software reusability

    (b) Code sharing

    (c) Consistency of interface

    (d) Software components

    (e) Rapid prototype

    1.6 Polymorphism

    Polymorphism includes the ability to use the same message to objects of different classes

    and have them behave differently.

    Thus we could define the message "+" for both the addition of numbers and the concatenation

    (joining) of characters, even though both these operations are completely different. Thus poly-

    morphism provides the ability to use the same word to invoke different methods, according to

    similarity of meaning.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    8/9

    10 Programming in C++ Part I

    A class that is created from another class (base class) is called the derived class. A derived

    class inherits all the features of its base class. It can then add data elements and routines. It can

    redefine routines from the base class, and it can restrict access to base-class features. Thus poly-

    morphism (many shapes) allows the programmer to define a base class that includes routines that

    perform standard operations on groups of related objects, without regard to the exact type of each

    object. The programmer can redefine the routines, taking into account the type of the object, in the

    derived classes for each of the types. For example, we can say that the South Indian dish, dosais

    the base class. The derived classes may be paper dosa, plain dosa, masala dosa, etc. Preparation of

    each of the derived class of dosa is an inxtension of the base classes i.e.dosa.

    The three main ideas (encapsulation, inheritance and polymorphism) tend to build on each

    other, so that once we have encapsulation, then we can build classification heirarchies of inheri-tance, and from these we can really begin to use the power of polymorphism.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap1

    9/9

    Part I General Concepts In C++ 11

    TESTPAPER

    Time: 3 Hrs

    Max Marks: 100

    Answer the following questions.

    1. State true or false:

    (a) Object-oriented programming is a new way of thinking about the process of

    decomposing problems and developing programming solutions.

    (b) Obects and classes extend the concept of abstract data types by ading the notion of

    inheritance.

    (c) Classes can be organized into a hierarchical inheritance tree.

    (d) By reducing the interdependency among software components, object oriented

    programmong permits the development of reusable software systems.

    (e) Object-oriented programming views a program as a collection of largely autono-

    mous agents, called objects.

    2. Indicate which of the following is true about C++ object and class.

    (a) An object when exectued returns a value. The class defines the type of data

    returned by an object.

    (b) A class can not be created for any data type.

    3. Differentiate between object and a function giving an example of each.

    4. Read the following passage regarding message and methods used to pass the message in

    an object oriented programming such as C++:

    "Action is initiated in C++ by the transmission of a message to an agent (an object)

    responsible for the action. The message encodes the request for an action, and is acompa-

    nied by any additional information (arguments) needed to carry out the request. The

    receiver is the agent to whom the message is sent. If the receiver accepts the message, it

    accepts the responsibility to carry out the indicated action. In response to a message, the

    receiver will perform somemethodto satisfy the request."

    Explain how would you respond to the message received from your computer science

    teacher to prepareclass resultof class XI students studying in your school.

    5. Differentiate among the following terms:

    (a) Class (b) Object (c) Instance6. Explain the term inheritance. Give an example of multiple inheritance. What are the

    advantage of using the concept of inheritance in object oriented programming such as

    C++.

    7. Write short notes on:

    (a) Polymorphism (b) Encapsulation

    bpbonline all rights reserved