SlideShare ist ein Scribd-Unternehmen logo
1 von 79
Object Oriented
 Progr amming
      in

    c++
Definition :   Object    oriented
 programming is an approach that
 provides a way of modularizing
 programs by creating partitioned
 memory area for both data and
 functions that can be used as
 templates for creating copies of
 such modules on demand.

An object   is considered to be a
  partitioned  area  of   computer
  memory that stores data and set
  of operations that can access
Basic concepts of Object
  Oriented Programming
Objects
   Objects    are   basic    runtime
    entities in an object    oriented
    system.    They may represent a
    person, a place, a table, of data
    or any item that the program must
    handle.
   Objects contain data and code to
    manipulate the data.
Class
   Class is a way to bind the data
    and its associated functions
    together.
   A class allows its data to be
    hidden from its external use.
   A new abstract data type is
    created during definition of a
    class
Data Encapsulation
   Data Encapsulation is the wrapping up
    of data and functions into a single
    unit.
   The data is not accessible to the
    outside world, only those functions
    which are wrapped in the class can
    access it.
   The insulation of the data from
    direct access by the program is
    called data hiding or information
    hiding
Inheritance
   Inheritance is the process
    by which objects of one
    class acquire properties of
    objects of another class.
Polymorphism

   Polymorphism means the ability
    to take more than one form
   One of the principal advantages of
    object-oriented          programming
    techniques      over      procedural
    programming techniques is that they
    enable programmers to create modules
    that do not need to be changed when
    a new type of object is added.

     A programmer can simply create a
    new object that inherits many of its
    features from existing objects. This
    makes    object-oriented    programs
    easier to modify.
Why create new types:

   A class is a user-defined data type that has data
    members and member functions.

   variable types include i.e. integers, characters.

   The type of variable you declare tells a   lot about
    it self.
   If you declare height and width as         integers,
    trying to hold anything else in these      variables
    causes an error, example tying to hold     your name
    in this variables causes an error.

   By declaring a variable type it tells you:
           – their size in memory
           – information that they can hold
           – and what actions that can be performed on
             them.
   In real world applications a
    type is a category. Example of
    types can be – car, house
    person, fruit, and shape.

   New types are created to solve
    real    world  problems,    i.e.
    keeping track of an employee
    records    or  simulating    the
    working of an heating system.
   It’s   possible   to    solve   complex
    problems   by   using    integers   and
    characters, but it’s easier to solve
    complex   problems    if   you   create
    representations of the object that
    you are talking about.

   A class is a user-defined data type
    that has data members and member
    functions
Revisiting C++ Structures

   Structures provide a method of packaging
    together, data of different types. Once a
    structure has been defined we can create
    variables of that type using declarations
    similar to the built-in type declarations.
   Structures enables us to access a collection of
     dissimilar, or varying data types, such as
    string name, an integer part number, and a
    real price.
Revisiting C+
                                        + Structures

   Structures give the ability of grouping data together
    and working with the data as a whole unit.
   Example a book has a collection of different things, i.e.
    title, author, call number, publisher, number of pages,
    date of publication.
              Title             string
              Author             string
              Call number        integer
              Publisher          string
              Price              float
Revisiting C+
                                  + Structures
   A data structure that stores different types of
    data under a single variable name is called a
    record.

   A structure contains a number of data types
    grouped together. These data types may or
    may not be of same type.
Declaring of a structure

   Two events needs to be carried out in
    declaring of structures same as variables.
    A. Declaring of the structure
    B. Assigning of specific values to individual record
       elements
   A structure must be declared first in the
    program.
   Declaring a structure requires listing the
    data type, data names, and arrangement of
    data items.
    Syntax:
1.             Struct <structure name>
2.             {
3.                  structure element 1;
4.                  structure element 2;
5.                  structure element 3;
6.             }; [one or more structure variables];
    Example:
1.     Struct book
2.     {
3.             char name;
4.             float price;
5.              int pages;
6.     };

    A new data type called struct book is defined.

    Each variable of this data type will consist of a character variable
     called name, a float variable called price and an integer variable
     called pages.

    Once the structure has been declared one or more variables can
     be declared to be of that type
Example:
 Struct book b1,b2,b3;

   The variables b1, b2, b3 are declared to be of the type struct book
   The declaration of the structure type and the structure variable can be
    combined
    Example One:
       Struct book
       {
                char name[10];
                float price;
                int   pages;
       }b1,b2,b3;

   Example Two:
      Struct
      {
             int month;
             int day;
             int year;
      } birth;

   Assigning actual data values to the data items of a
    structure is referred to as populating the structure.
Accessing the Structure Elements


   To access a member of the structure, specify
    the name of the structure variable then a dot
    and the structure element.
   As per the example above:- birth.month refers
    to the first member of the birth structure,
    birth.day refers to the second member of the
    structure, and birth.year refers to the third
    member.
 The period in each of these variable names is
  called the member access operator or the dot
  operator
  Example:
           B1.pages
 Before a dot there must be a structure variable
  and after the dot a structure element.
Nested Structures

Example                          1.   struct customers
 Consider the following two
                                 2.   {
  structures:
                                 3.       char   cust_name[25];
1.   Struct employee
2.   {                           4.       char   address[30];
3.        char   emp_name[25];   5.       char   city[10];
4.        char   address[30];    6.       char   state[2];
5.        char   city[10];       7.       int    zip;
6.        char   state[2];
                                 8.       int    balance;
7.        int    zip;
8.        int    salary;         9.   }
9.   }
    Even thought the two structures have different data one
     structure can be created to consolidate the two together.
1.   Struct address_info
2.   {
3.      char address[30];
4.      char city[10];
5.      char state[2];
6.      int    zip;
7.   }
This structure can be used as a member in the other structures.

1.    Struct employee
2.    {
3.        char     emp_name[25];
4.        struct address_info      e_address;
5.        int      salary;
6.    };
7.    struct customer
8.    {
9.        char     cust_name[25];
10.       struct address_info     c_address;
11.       int      balance;
12.   };
Array Of Structures

Example:
1.  Struct stores
2.   {
3.        int employees;
4.        int registers;
5.        int sales;
6.  } store[1000];

   The code creates 1000 store structures, each
    containing three members.
Example:
1.    Struct stores
2.    {
3.          int employees;
4.          int registers;
5.          int sales;
6.    } store[1000];
The code creates 1000 store structures, each containing
   three members.
Limitations of C Structures

  C does not allow the struct data types to
   be treated as built in types. The struct
   data types can not be added nor subtracted
   from each other.
Example:
1.    Struct sum
2.    {
3.         Float x;
4.         Float y;
5.    };
6.    Struct sum s1,s2,s3;

   The variables s1,s2 and s3 can
    be assigned values using the dot
    operator but can not be added
    nor subtracted from each other.
    Example:
     s3 = s1 +s2
     s3 = s2 – s1
    is illegal in C++.
Classes and Members

   Def:A class is a user-defined data type
    that   has   data   members    and    member
    functions.
   A class is similar to the c++ structure
    except that the definition of the class
    and all the functions that operate on the
    class are grouped together in one place,
    and further it allows its data to be
    hidden from its external use.
   By declaring a class we create a new
    abstract data type and also we bind the
    data   and    its   associated     functions
    together.
   A class has two major parts:
      a) Class declaration
      b) Class function definitions


   The class declaration describes   the   type
    and scope of its members.

     The class function definitions describe
    how the class functions are implemented.
Class Declaration
Syntax:
•    Class class_name
•    {
•          permission_label_1:
•                type member variables;
•          permission_label_2:
•                type member functions();
•    } object_name
   The class declaration is similar to a struct
    declaration.   The keyword class indicates
    that what follows is an abstract data of the
    type class_name.
   The body of a class is enclosed within
    braces and terminated by a semicolon.
   The body of a class contains a declaration
    of the data and functions, which are
    collectively called class members.
   The variables declared inside a class are
    known as data members while the functions
    are known as member functions.
Class name is the name for the class and the
  optional field object_name is one or several,
  valid object identifiers.

   The body of the declaration can contain
    members that can be either data or function
    declarations.

   The permission labels can be of any the
    three   keywords, Private:, Public:, or
    Protected:.
–   Private members of a class are accessible only by
    other members of the same class, or functions of a
    friend class.

–   Protected members are accessible from members of
    their same class and friend classes and also from
    members of their derived classes.

–   Public members are accessible from anywhere the
    class is visible.
Example:
1. Class cat
2. {
3.     int itsAge;    // member variable

4.     int itsWeight;
5.     void Meow(); //member function or method
6. }
   By declaring the class the memory is not
    allocated. What the declaration does is, it
    tells the compiler what the cat is, what data
    it contains (itsAge, itsWeight) and what it
    can do Meow ().
   It also tells the compiler how much room must
    be set aside for each cat that will be
    created. No space is set aside for the
    function Meow, no space is set aside for
    member functions/methods.
   By default functions and data declared within
    the class are private to that class and may
    be accessed only by other members of the
    class.
   Like structures a class has two
    kinds of members: data members and
    member functions.
    Data Members
     – Variables in a class are referred
       to as member variables or data
       members.
     – A car class can have member
       variables    representing  seats,
       radio, tires, engine etc.
Member Functions
– The functions in a class manipulate member
  variables. They are referred to as member
  functions or methods of a class.
– Member functions are functions defined
  within a class that act on the members of
  a class.
    Methods  of a class might include
     start(), Brake(). Move().
    A cat class might have data members that
     represent age and weight, its methods
     might be sleep(), Meow(), ChaseMise().
– Member functions or methods are part of
  the class, they determine what the class
  can do.
Naming conventions for classes

 C++ is case sensitive, and all class names should follow
  the same pattern so as to distinguish data members from
  non data members.
Example
    itsAge, itsWeight, itsSpeed
    cCat, cPerson.
    Cat, Person
    Rectangle, rectangle, RECTANGLE
    ChaseMise()
    Drawcircle()
Defining an object

   Once a class has been declared, we can create
    variables of that type by using the class name.
        Example:

              Cat Frisky;
   In C++ the class variables are known as objects.
    Therefore the code defines Frisky, which is an
    object whose class is Cat. An object of the new
    type is defined the same way as defining an
    integer variable
Accessing class members
   The private data members of a class can only be accessed
    through the member functions of that class. The data
    members of a class can only be accessed by using the dot
    operator.

        Example:
   To assign 50 to Frisky’s weight member variable, write

                Frisky.itsWeight = 50;
   To call the Meow() function write

                     Frisky.Meow();
Assign to objects not to classes

   Values are assigned to variables and not to
    types.
    Example:
   If you assign
           int = 5    // the compiler will return an error-
                            Wrong
           Cat.itsAge = 5;           // Wrong , you cant assign 5
                                    to the age part of the cat.
      It should be
           int x;           //define x to be an int
           X = 5;           // set x’s value to 5
           Cat Frisky; // define frisky, object of a class cat
           Frisky.itsAge = 5;// assign 5 to the object frisky.
Private versus Public
   All members of a class- member variables/data and member
    functions/methods are private by default.
   Private members of a class are hidden to all but not to the
    member functions of that class.
   Private members can be accessed only by the methods of the
    class itself.
   Public members can be accessed through any object of the
    class.
   The public members are visible and accessible to everybody
Example:
1.    Class cat
2.    {
3.            int itsAge;
4.            int itsWeight;
5.            void Meow();
6.    };
    In this declarations itsAge, itsWeight and Meow() are all private
     since all members of a class are private by default.
    If the following is written in the main function,
           –   Cat Boots;
           –   Boots.itsage = 5;   //the compiler returns an error can’t access
               private data .
  In order to access the data members of the class Cat, use
   the keyword public
Example:
1.    Class cat
2.    {
3.           public:
4.                   int itsAge;
5.                   int itsWeight;
6.                   void Meow();
7.    };
Program to demonstrate the access of private data members
1.  #include <iostream.h>
2.  class XYCoord
3.  {
4.  int x, y;
5.  };

6.    void main(void)
7.    {
8.    // Make an instance of the class
9.    XYCoord coord;
10.   coord.x = 2;
11.   coord.y = 3;
12.   }
   The new thing in this code is the operator:: of scope
    included in the definition of set_values(), its used to
    declare a member of a class outside it.



   X and y are made private and therefore the rest of
    the program does not have a way to directly access
    them.
Advantages of classes
The limitation of the c++ structures
   They do not allow the struct data type to be treated like built in types.
 Example:
          Struct nuclear
          {
                      float a;
                      float b;
          };
                      sttuct nuclear n1,n2,cn3;

   The nuclear objects can easly be assigned values using the dot operator
   But they can not be added together or subtracted from the other.
         Example:
                      N3 = n2 +n1; //illegal
   Structures do not permit data hiding, structure members can be directly accessed by the structure
    variables, or any function in the scope. The structure members are public members

   An advantage of classes is that several different objects can
    be declared from it.
Member function can be defined in two places:
 1. Outside the class definition
 2. Inside the class definition
Outside of the class definition
   Member functions defined inside a class have to be declared separately outside a class
         1. # include<iostream.h>
         2. class set
         3. {
         4.         int a,b;
         5. public:
         6.         void input(void);
         7.         void display(void);
         8.         int largest(void);
         9. };
         10.int set :: largest(void)
         11.{
         12.        if (a >= b)
         13.          return (a);
         14.        else
         15.          return(b);
         16.}
17.   void set :: input(void)
18.   {
19.       cout << "Enter the values of a and b"<< "n";
20.       cin >> a >> b;
21.   }
22.   void set :: display(void)
23.   {
24.       cout <<"Largest value is "<<largest()<<endl;
25.   }
26.   main()
27.   {
28.       set A;
29.       A.input();
30.       A.display();
31.                                }
   A member function begins with the name
    of the class followed by two colons,
    the name of a function and its
    parameters.
   The   difference   between   a   member
    function and a normal function is that
    a   member   function  incorporates   a
    membership   identity  label   in   the
    header.   The label tells the compiler
    which class the function belongs to.

.
Syntax:
  Return type class_name      ::   function   name
  (argument declaration)
  {
     function body
  }

   The label class name:: tells the compiler
    that the function name belongs to the class
    name.   Meaning the scope of the function is
    restricted to the class name specified in the
    header
   The symbol :: is called a scope
    resolution operator.

   The special characteristics of
    member functions include:-

   Several classes can use the
    same function name. The class
    name resolves their scope.
   Member functions can access the
    private data of the class, but
    non member function cannot. (This
    rule is overcome by the friend
    function)
   A   member   function   can  call
    another member function directly
    without using the dot operator
Inside of the class definition
   In this, the function declaration is replaced by the   actual
    function definition inside the class.
Example:
1.      Class book
2.      {
3.              char name;
4.              int number;
5.              float cost;
6.            public:
7.              void getdata(int a, float b);
8.              void putdata(void)
9.              {
10.                     cout << number <<endl;
11.                     cout << cost <<endl;
12.             }
13.     };
   A function defined inside a class is treated as an     inline
    function.
Nesting of member functions
     A member function can be called by using its name inside another member function of the
      same class.
1.    # include<iostream.h>
2.    class set
3.    {
4.        int a,b;
5.       public:
6.        void input(void);
7.        void display(void);
8.        int largest(void);
9.    };
10.   int set :: largest(void)
11.   {
12.       if (a >= b)
13.         return (a);
14.       else
15.         return(b);
16.   }
17.   void set :: input(void)
18.   {
19.     cout << "Enter the values of a an b"<< "n";
20.     cin >> a >> b;
21.   }
22.   void set :: display(void)
23.   {
24.     cout <<"Largest value is "<<largest()<<endl;
                  // nesting of member function

25.   }
26.   main()
27.   {
28.     set A;
29.     A.input();
30.     A.display();
31.   }
Private member functions
   Even though the data members are put on
    the private section and the functions
    on the public some situations require
    some functions to be put in the private
    section.
   Functions that deal with adding of bank
    accounts, deleting a customer account
    or providing accessing balance accounts
    of   customers    should  be   put   in
    restricted areas.
   A private member function can only be
    called by another member function that
    is a member of its class
Example:
1.     Class bankcustomer
2.     {
3.            int m;
4.            int custbalance();
5.            void custdelete(void);
6.            int addaccount();
7.            public:
8.            void update(void);
9.            void write(void);
10.           void check(void);
11.    };
   In this case if Robert is an object of the class
    backcustomer he can not directly access the balance by
    using the custbalance function.
       Robert.custbalance(); // object can not access private
    member
    The function custbalance can be
     called by the function check() to
     check the balance.
1.   Void bankcustomer :: check(void)
2.   {
3.         custbalance();
4.   }
Arrays within a class
     Arrays   can  be   used         as    member
      variables in a class.
Example:
1.    Const int no=20;
2.
3.    Class array
4.    {
5.          int emp[no];
6.          public:
7.          void setbalance(void);
8.          void display(void)
9.    };
An array variable emp is declared as a private member
    of the class array, and can be used is the member
    function like any other array variable.
1.  #include<iostream.h>         19.   void items :: getitem(void)
2. #include <stdio.h>            20.   {
3. const m = 50;                 21.       cout << "tEnter item
4. class items                         code:";
5. {                             22.       cin >> itemcode[count];
6.      int itemcode[m];         23.       cout << "tEnter item
7.      float itemprice[m];            cost:";
                                 24.       cin >> itemprice[count];
8.      int count;
                                 25.       count ++;
9. public:
                                 26.   }
10.     void cnt(void)
                                 27.   void items ::
11.     {
                                       displaysum(void)
12.           count = 0;
                                 28.   {
13.     }
                                 29.       float sum = 0;
14.     void getitem(void);
                                 30.       for (int i=0; i<count; i++)
15.     void displaysum(void);
                                 31.               sum = sum +
16.     void remove(void);             itemprice[i];
17.     void                     32.       cout << "Total value :"
    displayitems(void);                << sum <<endl;
18. };                           33.   }
34.   void items :: remove(void) //        52. main()
      delete a specified item.             53. {
35.   {
                                           54.      items order;
36.        int a;
37.        cout << "enter item code:";     55.      order.cnt();
38.        cin >>a;                        56.      int x;
39.        for ( int i=10; i<count; i++)   57.      do
40.                 if(itemcode[i] ==a)    58.      {
41.                                        59.             cout <<"t MAIN
      itemprice[i]=0;                          MENU n";
42.   }                                    60.             cout <<"nt1 :
43.   void items :: displayitems(void)           Add an item ";
44.   {                                    61.             cout <<"nt2 :
45.        cout << "code Price";                 Display total value";
46.        for(int i=0; i<count; i++)      62.             cout <<"nt3 :
47.        {                                     Delete an item";
48.                 cout <<"n" <<         63.             cout <<"nt4 :
      itemcode[i];                               Display all items";
49.                 cout <<"   "
      <<itemprice[i];                      64.             cout <<"nt5 :
                                                 Quit";
50.        }
51.       cout << "n";                    65.             cout << "nnt
                                               What is your choice?";
52.   }                                    66.             cin >> x;
67. switch(x)                       Program Explanation:
68.             {                   The program has two arrays
69.                      case 1 :   itemcode[], to hold the code
      order.getitem();              number of items and itemprice[] to
70.                                 hold the prices.
                break;              Data member count is use to keep
71.                    case 2 :     a record of the items in the list.
      order.displaysum();           The statement
72.
                break;                   Cont int m=50; //defines the
                                    size of the array members
73.                      case 3 :
      order.remove();               The function CNT() sets the
74.                                 variable count to zero. Getitem()
                break;              gets the item code and the item
75.                    case 4 :     price and assigns them to the
      order.displayitems();         array members itemCode[count]
76.                                 and itemPrice[count].     Count is
                break;              incremented after the assignment
77.                  default        operation is over. Remove()
        : cout << "Error in         function deletes a given item from
    input; try againn";            the list, it uses the item code to
78.            }                    locate it in the list and sets the
79.     }while(x !=5);              price to zero. Lastly the function
                                    displayItems() displays all the
80.     return 0;                   items in the list
81. }
Arrays of objects

1. Example:                 Employee is a user defined
                            data type and can be used
2.     Class employee       to create objects that
                            relate to different
3.     {                    categories of the
4.         char             employees
     name[30];           Example:
5.         float age;          Employee manager[3];
6.         public:
                                Employee
7.         void             supervisor[10]; Employee
     getinfo(void);         workers[100];
8.         void
     putinfo(void);
9.     };
   The array manager contains three objects,, namely
    manager[0], manager[1],manager[2], of type employee
    class. The foreman array contains 15 objects and the
    worker array contains 75 objects.

   Since the array of objects behave the same way as any
    object, you can use the array accessing method to access
    individual elements and then the dot operator to access
    the member functions.


   manager[i].putinfo();

// will display the ith element of the array manager
   and invoke the member function
             putdata().
Program Example : Array of objects. The program reads in
           a number of employees and prints them on the screen
1.     #include <iostream.h>                22.   const int size=3;
2.    class employee                        23.     main()
3.    {                                     24.     {
4.          char name[30];                  25.         employee manager[size];
5.          float age;                      26.         for(int i=0; i<size; i++)
6.      public:                             27.         {
7.          void getdata(void);             28.         cout <<"nDetails of
8.          void putdata(void);                   manager"<<i+1<<"n";
9.      };                                  29.         manager[i].getdata();
10.     void employee :: getdata(void)      30.         }
11.     {                                   31.         cout <<"n";
12.         cout << "Enter the employee     32.         for (i=0; i<size; i++)
      name:";                               33.         {
13.         cin >> name;                    34.         cout <<"n Manager" << i + 1
14.         cout <<"Enter the employee                  <<"n";
      age:";                                35.         manager[i].putdata();
15.         cin >> age;                     36.         }
16.     }                                   37.         return 0;
17.   void employee :: putdata(void)        38.   }
18.     {
19.         cout <<"Name :" << name
      <<"n";
20.         cout <<"Age: " <<age << "n";
21.     }
Practice:
 Modify the above program to
  accommodate different types of
  employees, i.e. supervisors,
  workers etc.
END

Weitere ähnliche Inhalte

Andere mochten auch

CMSC22: Object Oriented Programming - The RPG
CMSC22: Object Oriented Programming - The RPGCMSC22: Object Oriented Programming - The RPG
CMSC22: Object Oriented Programming - The RPGJedaiah Joel Lumagbas
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NETA R
 
Vb net xp_03
Vb net xp_03Vb net xp_03
Vb net xp_03Niit Care
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Asfand Hassan
 
Operators , Functions and Options in VB.NET
Operators , Functions and Options in VB.NETOperators , Functions and Options in VB.NET
Operators , Functions and Options in VB.NETShyam Sir
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vbSalim M
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Nettjunicornfx
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in CSmit Parikh
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structuresindra Kishor
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programAAKASH KUMAR
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedurepragya ratan
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ programmatiur rahman
 

Andere mochten auch (18)

CMSC22: Object Oriented Programming - The RPG
CMSC22: Object Oriented Programming - The RPGCMSC22: Object Oriented Programming - The RPG
CMSC22: Object Oriented Programming - The RPG
 
Date & time functions in VB.NET
Date & time functions in VB.NETDate & time functions in VB.NET
Date & time functions in VB.NET
 
Savitch Ch 03
Savitch Ch 03Savitch Ch 03
Savitch Ch 03
 
Vb net xp_03
Vb net xp_03Vb net xp_03
Vb net xp_03
 
Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]Course outline [csc241 object oriented programming]
Course outline [csc241 object oriented programming]
 
Operators , Functions and Options in VB.NET
Operators , Functions and Options in VB.NETOperators , Functions and Options in VB.NET
Operators , Functions and Options in VB.NET
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
Programming and problem solving with c++, 3rd edition
Programming and problem solving with c++, 3rd editionProgramming and problem solving with c++, 3rd edition
Programming and problem solving with c++, 3rd edition
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structures
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedure
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ program
 

Ähnlich wie 2 lesson 2 object oriented programming in c++

Ähnlich wie 2 lesson 2 object oriented programming in c++ (20)

Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Structure prespentation
Structure prespentation Structure prespentation
Structure prespentation
 
Structures
StructuresStructures
Structures
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
Lecture 19 - Struct and Union
Lecture 19 - Struct and UnionLecture 19 - Struct and Union
Lecture 19 - Struct and Union
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 

2 lesson 2 object oriented programming in c++

  • 1. Object Oriented Progr amming in c++
  • 2. Definition : Object oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. An object is considered to be a partitioned area of computer memory that stores data and set of operations that can access
  • 3. Basic concepts of Object Oriented Programming
  • 4. Objects  Objects are basic runtime entities in an object oriented system. They may represent a person, a place, a table, of data or any item that the program must handle.  Objects contain data and code to manipulate the data.
  • 5. Class  Class is a way to bind the data and its associated functions together.  A class allows its data to be hidden from its external use.  A new abstract data type is created during definition of a class
  • 6. Data Encapsulation  Data Encapsulation is the wrapping up of data and functions into a single unit.  The data is not accessible to the outside world, only those functions which are wrapped in the class can access it.  The insulation of the data from direct access by the program is called data hiding or information hiding
  • 7. Inheritance  Inheritance is the process by which objects of one class acquire properties of objects of another class.
  • 8. Polymorphism  Polymorphism means the ability to take more than one form
  • 9. One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added.  A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.
  • 10. Why create new types:  A class is a user-defined data type that has data members and member functions.  variable types include i.e. integers, characters.  The type of variable you declare tells a lot about it self.  If you declare height and width as integers, trying to hold anything else in these variables causes an error, example tying to hold your name in this variables causes an error.  By declaring a variable type it tells you: – their size in memory – information that they can hold – and what actions that can be performed on them.
  • 11. In real world applications a type is a category. Example of types can be – car, house person, fruit, and shape.  New types are created to solve real world problems, i.e. keeping track of an employee records or simulating the working of an heating system.
  • 12. It’s possible to solve complex problems by using integers and characters, but it’s easier to solve complex problems if you create representations of the object that you are talking about.  A class is a user-defined data type that has data members and member functions
  • 13. Revisiting C++ Structures  Structures provide a method of packaging together, data of different types. Once a structure has been defined we can create variables of that type using declarations similar to the built-in type declarations.  Structures enables us to access a collection of dissimilar, or varying data types, such as string name, an integer part number, and a real price.
  • 14. Revisiting C+ + Structures  Structures give the ability of grouping data together and working with the data as a whole unit.  Example a book has a collection of different things, i.e. title, author, call number, publisher, number of pages, date of publication.  Title string Author string Call number integer Publisher string Price float
  • 15. Revisiting C+ + Structures  A data structure that stores different types of data under a single variable name is called a record.  A structure contains a number of data types grouped together. These data types may or may not be of same type.
  • 16.
  • 17. Declaring of a structure  Two events needs to be carried out in declaring of structures same as variables. A. Declaring of the structure B. Assigning of specific values to individual record elements  A structure must be declared first in the program.  Declaring a structure requires listing the data type, data names, and arrangement of data items.
  • 18. Syntax: 1. Struct <structure name> 2. { 3. structure element 1; 4. structure element 2; 5. structure element 3; 6. }; [one or more structure variables];
  • 19. Example: 1. Struct book 2. { 3. char name; 4. float price; 5. int pages; 6. };  A new data type called struct book is defined.  Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages.  Once the structure has been declared one or more variables can be declared to be of that type
  • 20. Example:  Struct book b1,b2,b3;   The variables b1, b2, b3 are declared to be of the type struct book  The declaration of the structure type and the structure variable can be combined Example One:  Struct book  {  char name[10];  float price;  int pages;  }b1,b2,b3; 
  • 21. Example Two:  Struct  {  int month;  int day;  int year;  } birth;   Assigning actual data values to the data items of a structure is referred to as populating the structure.
  • 22. Accessing the Structure Elements  To access a member of the structure, specify the name of the structure variable then a dot and the structure element.  As per the example above:- birth.month refers to the first member of the birth structure, birth.day refers to the second member of the structure, and birth.year refers to the third member.
  • 23.  The period in each of these variable names is called the member access operator or the dot operator Example: B1.pages  Before a dot there must be a structure variable and after the dot a structure element.
  • 24.
  • 25.
  • 26. Nested Structures Example 1. struct customers  Consider the following two 2. { structures: 3. char cust_name[25]; 1. Struct employee 2. { 4. char address[30]; 3. char emp_name[25]; 5. char city[10]; 4. char address[30]; 6. char state[2]; 5. char city[10]; 7. int zip; 6. char state[2]; 8. int balance; 7. int zip; 8. int salary; 9. } 9. }
  • 27. Even thought the two structures have different data one structure can be created to consolidate the two together. 1. Struct address_info 2. { 3. char address[30]; 4. char city[10]; 5. char state[2]; 6. int zip; 7. }
  • 28. This structure can be used as a member in the other structures. 1. Struct employee 2. { 3. char emp_name[25]; 4. struct address_info e_address; 5. int salary; 6. }; 7. struct customer 8. { 9. char cust_name[25]; 10. struct address_info c_address; 11. int balance; 12. };
  • 29. Array Of Structures Example: 1. Struct stores 2. { 3. int employees; 4. int registers; 5. int sales; 6. } store[1000];  The code creates 1000 store structures, each containing three members.
  • 30. Example: 1. Struct stores 2. { 3. int employees; 4. int registers; 5. int sales; 6. } store[1000]; The code creates 1000 store structures, each containing three members.
  • 31.
  • 32. Limitations of C Structures  C does not allow the struct data types to be treated as built in types. The struct data types can not be added nor subtracted from each other. Example: 1. Struct sum 2. { 3. Float x; 4. Float y; 5. }; 6. Struct sum s1,s2,s3; 
  • 33. The variables s1,s2 and s3 can be assigned values using the dot operator but can not be added nor subtracted from each other. Example:  s3 = s1 +s2  s3 = s2 – s1 is illegal in C++.
  • 34. Classes and Members  Def:A class is a user-defined data type that has data members and member functions.  A class is similar to the c++ structure except that the definition of the class and all the functions that operate on the class are grouped together in one place, and further it allows its data to be hidden from its external use.  By declaring a class we create a new abstract data type and also we bind the data and its associated functions together.
  • 35. A class has two major parts: a) Class declaration b) Class function definitions  The class declaration describes the type and scope of its members.  The class function definitions describe how the class functions are implemented.
  • 36. Class Declaration Syntax: • Class class_name • { • permission_label_1: • type member variables; • permission_label_2: • type member functions(); • } object_name
  • 37. The class declaration is similar to a struct declaration. The keyword class indicates that what follows is an abstract data of the type class_name.  The body of a class is enclosed within braces and terminated by a semicolon.  The body of a class contains a declaration of the data and functions, which are collectively called class members.  The variables declared inside a class are known as data members while the functions are known as member functions.
  • 38. Class name is the name for the class and the optional field object_name is one or several, valid object identifiers.  The body of the declaration can contain members that can be either data or function declarations.  The permission labels can be of any the three keywords, Private:, Public:, or Protected:.
  • 39. Private members of a class are accessible only by other members of the same class, or functions of a friend class. – Protected members are accessible from members of their same class and friend classes and also from members of their derived classes. – Public members are accessible from anywhere the class is visible.
  • 40. Example: 1. Class cat 2. { 3. int itsAge; // member variable 4. int itsWeight; 5. void Meow(); //member function or method 6. }
  • 41. By declaring the class the memory is not allocated. What the declaration does is, it tells the compiler what the cat is, what data it contains (itsAge, itsWeight) and what it can do Meow ().  It also tells the compiler how much room must be set aside for each cat that will be created. No space is set aside for the function Meow, no space is set aside for member functions/methods.  By default functions and data declared within the class are private to that class and may be accessed only by other members of the class.
  • 42. Like structures a class has two kinds of members: data members and member functions. Data Members – Variables in a class are referred to as member variables or data members. – A car class can have member variables representing seats, radio, tires, engine etc.
  • 43. Member Functions – The functions in a class manipulate member variables. They are referred to as member functions or methods of a class. – Member functions are functions defined within a class that act on the members of a class.  Methods of a class might include start(), Brake(). Move().  A cat class might have data members that represent age and weight, its methods might be sleep(), Meow(), ChaseMise(). – Member functions or methods are part of the class, they determine what the class can do.
  • 44. Naming conventions for classes  C++ is case sensitive, and all class names should follow the same pattern so as to distinguish data members from non data members. Example  itsAge, itsWeight, itsSpeed  cCat, cPerson.  Cat, Person  Rectangle, rectangle, RECTANGLE  ChaseMise()  Drawcircle()
  • 45. Defining an object  Once a class has been declared, we can create variables of that type by using the class name. Example: Cat Frisky;  In C++ the class variables are known as objects. Therefore the code defines Frisky, which is an object whose class is Cat. An object of the new type is defined the same way as defining an integer variable
  • 46. Accessing class members  The private data members of a class can only be accessed through the member functions of that class. The data members of a class can only be accessed by using the dot operator. Example:  To assign 50 to Frisky’s weight member variable, write Frisky.itsWeight = 50;  To call the Meow() function write Frisky.Meow();
  • 47. Assign to objects not to classes  Values are assigned to variables and not to types. Example:  If you assign int = 5 // the compiler will return an error- Wrong Cat.itsAge = 5; // Wrong , you cant assign 5 to the age part of the cat.  It should be  int x; //define x to be an int  X = 5; // set x’s value to 5  Cat Frisky; // define frisky, object of a class cat  Frisky.itsAge = 5;// assign 5 to the object frisky.
  • 48. Private versus Public  All members of a class- member variables/data and member functions/methods are private by default.  Private members of a class are hidden to all but not to the member functions of that class.  Private members can be accessed only by the methods of the class itself.  Public members can be accessed through any object of the class.  The public members are visible and accessible to everybody
  • 49. Example: 1. Class cat 2. { 3. int itsAge; 4. int itsWeight; 5. void Meow(); 6. };  In this declarations itsAge, itsWeight and Meow() are all private since all members of a class are private by default.  If the following is written in the main function, – Cat Boots; – Boots.itsage = 5; //the compiler returns an error can’t access private data .
  • 50.  In order to access the data members of the class Cat, use the keyword public Example: 1. Class cat 2. { 3. public: 4. int itsAge; 5. int itsWeight; 6. void Meow(); 7. };
  • 51.
  • 52. Program to demonstrate the access of private data members 1. #include <iostream.h> 2. class XYCoord 3. { 4. int x, y; 5. }; 6. void main(void) 7. { 8. // Make an instance of the class 9. XYCoord coord; 10. coord.x = 2; 11. coord.y = 3; 12. }
  • 53.
  • 54. The new thing in this code is the operator:: of scope included in the definition of set_values(), its used to declare a member of a class outside it.  X and y are made private and therefore the rest of the program does not have a way to directly access them.
  • 55. Advantages of classes The limitation of the c++ structures  They do not allow the struct data type to be treated like built in types.  Example:  Struct nuclear  {  float a;  float b;  };  sttuct nuclear n1,n2,cn3;   The nuclear objects can easly be assigned values using the dot operator  But they can not be added together or subtracted from the other.  Example:  N3 = n2 +n1; //illegal  Structures do not permit data hiding, structure members can be directly accessed by the structure variables, or any function in the scope. The structure members are public members 
  • 56. An advantage of classes is that several different objects can be declared from it.
  • 57. Member function can be defined in two places: 1. Outside the class definition 2. Inside the class definition
  • 58. Outside of the class definition  Member functions defined inside a class have to be declared separately outside a class 1. # include<iostream.h> 2. class set 3. { 4. int a,b; 5. public: 6. void input(void); 7. void display(void); 8. int largest(void); 9. }; 10.int set :: largest(void) 11.{ 12. if (a >= b) 13. return (a); 14. else 15. return(b); 16.}
  • 59. 17. void set :: input(void) 18. { 19. cout << "Enter the values of a and b"<< "n"; 20. cin >> a >> b; 21. } 22. void set :: display(void) 23. { 24. cout <<"Largest value is "<<largest()<<endl; 25. } 26. main() 27. { 28. set A; 29. A.input(); 30. A.display(); 31. }
  • 60. A member function begins with the name of the class followed by two colons, the name of a function and its parameters.  The difference between a member function and a normal function is that a member function incorporates a membership identity label in the header. The label tells the compiler which class the function belongs to. .
  • 61. Syntax: Return type class_name :: function name (argument declaration) { function body }  The label class name:: tells the compiler that the function name belongs to the class name. Meaning the scope of the function is restricted to the class name specified in the header
  • 62. The symbol :: is called a scope resolution operator.  The special characteristics of member functions include:-  Several classes can use the same function name. The class name resolves their scope.
  • 63. Member functions can access the private data of the class, but non member function cannot. (This rule is overcome by the friend function)  A member function can call another member function directly without using the dot operator
  • 64. Inside of the class definition  In this, the function declaration is replaced by the actual function definition inside the class. Example: 1. Class book 2. { 3. char name; 4. int number; 5. float cost; 6. public: 7. void getdata(int a, float b); 8. void putdata(void) 9. { 10. cout << number <<endl; 11. cout << cost <<endl; 12. } 13. };  A function defined inside a class is treated as an inline function.
  • 65. Nesting of member functions  A member function can be called by using its name inside another member function of the same class. 1. # include<iostream.h> 2. class set 3. { 4. int a,b; 5. public: 6. void input(void); 7. void display(void); 8. int largest(void); 9. }; 10. int set :: largest(void) 11. { 12. if (a >= b) 13. return (a); 14. else 15. return(b); 16. }
  • 66. 17. void set :: input(void) 18. { 19. cout << "Enter the values of a an b"<< "n"; 20. cin >> a >> b; 21. } 22. void set :: display(void) 23. { 24. cout <<"Largest value is "<<largest()<<endl; // nesting of member function 25. } 26. main() 27. { 28. set A; 29. A.input(); 30. A.display(); 31. }
  • 67. Private member functions  Even though the data members are put on the private section and the functions on the public some situations require some functions to be put in the private section.  Functions that deal with adding of bank accounts, deleting a customer account or providing accessing balance accounts of customers should be put in restricted areas.  A private member function can only be called by another member function that is a member of its class
  • 68. Example: 1. Class bankcustomer 2. { 3. int m; 4. int custbalance(); 5. void custdelete(void); 6. int addaccount(); 7. public: 8. void update(void); 9. void write(void); 10. void check(void); 11. };  In this case if Robert is an object of the class backcustomer he can not directly access the balance by using the custbalance function. Robert.custbalance(); // object can not access private member
  • 69. The function custbalance can be called by the function check() to check the balance. 1. Void bankcustomer :: check(void) 2. { 3. custbalance(); 4. }
  • 70. Arrays within a class  Arrays can be used as member variables in a class. Example: 1. Const int no=20; 2. 3. Class array 4. { 5. int emp[no]; 6. public: 7. void setbalance(void); 8. void display(void) 9. }; An array variable emp is declared as a private member of the class array, and can be used is the member function like any other array variable.
  • 71. 1. #include<iostream.h> 19. void items :: getitem(void) 2. #include <stdio.h> 20. { 3. const m = 50; 21. cout << "tEnter item 4. class items code:"; 5. { 22. cin >> itemcode[count]; 6. int itemcode[m]; 23. cout << "tEnter item 7. float itemprice[m]; cost:"; 24. cin >> itemprice[count]; 8. int count; 25. count ++; 9. public: 26. } 10. void cnt(void) 27. void items :: 11. { displaysum(void) 12. count = 0; 28. { 13. } 29. float sum = 0; 14. void getitem(void); 30. for (int i=0; i<count; i++) 15. void displaysum(void); 31. sum = sum + 16. void remove(void); itemprice[i]; 17. void 32. cout << "Total value :" displayitems(void); << sum <<endl; 18. }; 33. }
  • 72. 34. void items :: remove(void) // 52. main() delete a specified item. 53. { 35. { 54. items order; 36. int a; 37. cout << "enter item code:"; 55. order.cnt(); 38. cin >>a; 56. int x; 39. for ( int i=10; i<count; i++) 57. do 40. if(itemcode[i] ==a) 58. { 41. 59. cout <<"t MAIN itemprice[i]=0; MENU n"; 42. } 60. cout <<"nt1 : 43. void items :: displayitems(void) Add an item "; 44. { 61. cout <<"nt2 : 45. cout << "code Price"; Display total value"; 46. for(int i=0; i<count; i++) 62. cout <<"nt3 : 47. { Delete an item"; 48. cout <<"n" << 63. cout <<"nt4 : itemcode[i]; Display all items"; 49. cout <<" " <<itemprice[i]; 64. cout <<"nt5 : Quit"; 50. } 51. cout << "n"; 65. cout << "nnt What is your choice?"; 52. } 66. cin >> x;
  • 73. 67. switch(x) Program Explanation: 68. { The program has two arrays 69. case 1 : itemcode[], to hold the code order.getitem(); number of items and itemprice[] to 70. hold the prices. break; Data member count is use to keep 71. case 2 : a record of the items in the list. order.displaysum(); The statement 72. break; Cont int m=50; //defines the size of the array members 73. case 3 : order.remove(); The function CNT() sets the 74. variable count to zero. Getitem() break; gets the item code and the item 75. case 4 : price and assigns them to the order.displayitems(); array members itemCode[count] 76. and itemPrice[count]. Count is break; incremented after the assignment 77. default operation is over. Remove() : cout << "Error in function deletes a given item from input; try againn"; the list, it uses the item code to 78. } locate it in the list and sets the 79. }while(x !=5); price to zero. Lastly the function displayItems() displays all the 80. return 0; items in the list 81. }
  • 74. Arrays of objects 1. Example: Employee is a user defined data type and can be used 2. Class employee to create objects that relate to different 3. { categories of the 4. char employees name[30]; Example: 5. float age; Employee manager[3]; 6. public: Employee 7. void supervisor[10]; Employee getinfo(void); workers[100]; 8. void putinfo(void); 9. };
  • 75. The array manager contains three objects,, namely manager[0], manager[1],manager[2], of type employee class. The foreman array contains 15 objects and the worker array contains 75 objects.  Since the array of objects behave the same way as any object, you can use the array accessing method to access individual elements and then the dot operator to access the member functions. 
  • 76. manager[i].putinfo(); // will display the ith element of the array manager and invoke the member function putdata().
  • 77. Program Example : Array of objects. The program reads in a number of employees and prints them on the screen 1. #include <iostream.h> 22. const int size=3; 2. class employee 23. main() 3. { 24. { 4. char name[30]; 25. employee manager[size]; 5. float age; 26. for(int i=0; i<size; i++) 6. public: 27. { 7. void getdata(void); 28. cout <<"nDetails of 8. void putdata(void); manager"<<i+1<<"n"; 9. }; 29. manager[i].getdata(); 10. void employee :: getdata(void) 30. } 11. { 31. cout <<"n"; 12. cout << "Enter the employee 32. for (i=0; i<size; i++) name:"; 33. { 13. cin >> name; 34. cout <<"n Manager" << i + 1 14. cout <<"Enter the employee <<"n"; age:"; 35. manager[i].putdata(); 15. cin >> age; 36. } 16. } 37. return 0; 17. void employee :: putdata(void) 38. } 18. { 19. cout <<"Name :" << name <<"n"; 20. cout <<"Age: " <<age << "n"; 21. }
  • 78. Practice:  Modify the above program to accommodate different types of employees, i.e. supervisors, workers etc.
  • 79. END