SlideShare une entreprise Scribd logo
1  sur  2
Télécharger pour lire hors ligne
Object Oriented Programming                    License: http://creativecommons.org/licenses/by-nc-nd/3.0/    Object Oriented Programming

                                         POINTERS TO OBJECTS                                                     class String{              Example:
  Objects are stored in memory, so pointers can point to objects just as they can to                                int size;
  variables of basic types.                                                                                         char *contents;
  The new Operator:                                                                                               public:
  The new operator allocates memory of a specific size from the operating system and                                String();                                     // Default constructor
  returns a pointer to its starting point.                                                                          String(const char *);                         // Constructor
   If it is unable to find space, in returns a 0 pointer.                                                           String(const String &);                       // Copy constructor
  When you use new with objects, it does not only allocate memory for the object, it also
                                                                                                                    const String& operator=(const String &);      // Assignment operator
  creates the object in the sense of invoking the object’s constructor.                                             void print() const ;
                                                                                                                    ~String();                                    // Destructor
  This guarantees that the object is correctly initialized, which is vital for avoiding
                                                                                                                 };
  programming errors.
                                                                                                                 int main()
  The delete Operator:                                                                                           {
  To ensure safe and efficient use of memory, the new operator is matched by a                                       String *sptr = new String[3];     // Creats 3 objects
  corresponding delete operator that releases the memory back to the operating system.                                                                                             See Example: e71.cpp
                                                                                                                     String s1("String_1");            // A String object
  If you create an array with new Type[ ];, you need the brackets when you delete it:                                String s2("String_2");            // Another String object
                                                                                                                     *sptr = s1;                       // Assignment to the first elelement of the array
  int * ptr = new int[10];
                                                                                                                     *(sptr + 1) = s2;                 // Assignment to the second element of the array
  :                                                                                                                  sptr->print();                    // Prints the first element
  delete [ ] ptr;                                                                                                    (sptr+1)->print();                // Prints the second element
 Don’t forget the brackets when deleting arrays of objects.                                                          sptr[1].print();                  // Prints the second element
 Using them ensures that all the members of the array are deleted and that the                                       delete[] sptr;                    // Objects pointed by sptr are deleted
 destructor is called for each one.                                                                                  return 0;
 If you forget the brackets, only the first element of the array will be deleted.                                }
 http://www.faculty.itu.edu.tr/buzluca                              ©1999-2010 Dr. Feza BUZLUCA        7.1    http://www.faculty.itu.edu.tr/buzluca                     ©1999-2010 Dr. Feza BUZLUCA   7.2
 http://www.buzluca.info                                                                                      http://www.buzluca.info




Object Oriented Programming                                                                                  Object Oriented Programming

                             Linked List of Objects                                                             In the previous example the Teacher class must have a pointer to the next object
                                                                                                                and the list class must be declared as a friend, to enable users of this class
 A class may contain a pointer to objects of its type. This pointer can be used to
                                                                                                                building linked lists.
 build a chain of objects, a linked list.
                                                                                                               If this class is written by the same group then it is possible to put such a pointer
class Teacher{                                                                                                 in the class.
   friend class TeacherList;
                                                                                                               But usually programmers use ready classes, written by other groups, for example
   string name;
                                                                                                               classes from libraries. And these classes may not have a next pointer.
   int age, numOfStudents;
   Teacher * next;                     // Pointer to next object of teacher                                    To build linked lists of such ready classes the programmer can derive a new class
 public:                                                                                                       (TeacherForList) with a next pointer.
   Teacher(const string &, int, int); // Constructor
   void print() const;                                                                                        class TeacherForList : public Teacher{       // TeacherForList is a Teacher with a pointer
                                                      // linked list for teachers                                friend class Teacher_list;
   const string& getName() const {return name;}
                                                      class TeacherList{                                         TeacherForList * next;                        // next Teacher
   ~Teacher()              // Destructor
                                                         Teacher *head;                                          TeacherForList(const string &, int, int);     // constructor
};
                                                        public:                                               };
                                                         TeacherList(){head=0;}
                                                         bool append(const string &,int,int);                 TeacherForList :: TeacherForList (const string & n, int a, int nos)
                                                         bool del(const string &);                                                              :Teacher (n, a, nos)
                                                         void print() const ;                                 {
                                                         ~TeacherList();                                         next = 0;
                          See Example: e72.cpp        };                                                      }
 http://www.faculty.itu.edu.tr/buzluca                              ©1999-2010 Dr. Feza BUZLUCA        7.3    http://www.faculty.itu.edu.tr/buzluca                     ©1999-2010 Dr. Feza BUZLUCA   7.4
 http://www.buzluca.info                                                                                      http://www.buzluca.info




Object Oriented Programming                                                                                  Object Oriented Programming

                                                                                                                                  Pointers and Inheritance
  Another way to build linked lists of such ready classes without using inheritance                          If a class Derived has a public base class Base, then a pointer to Derived can be
  is to define a node class.                                                                                 assigned to a variable of type pointer to Base without use of explicit type
  Each object of the node class will hold the addresses of an element of the list.                           conversion.
                                                                                                             In other words, a pointer to Base can carry the address of an object of Derived.
                                                                                                             The opposite conversion, for pointer to Base to pointer to Derived, must be explicit.
    class TeacherNode{                                   // TeacherNode has a Teacher
       friend class TeacherList;                                                                             For example, a pointer to Teacher can point to objects of Teacher and to objects of
       Teacher * element;                                 //   The element of the list                       Principal.
       TeacherNode * next;                                //   next node                                     A principal is a teacher, but a teacher is not always a principal.
       TeacherNode(const string &, int, int);             //   constructor
       ~TeacherNode();                                    //   destructor                                          class Base{
    };
                                                                                                                   };
    TeacherNode::TeacherNode(const string & n, int a, int nos){                                                    class Derived : public Base {
      element = new Teacher(n, a, nos);
      next = 0;                                                                                                    };
    }                                                                                                              Derived d;
    TeacherNode::~TeacherNode(){                                                                                   Base *bp = &d;                                // implicit conversion
      delete element;                                                                                              Derived *dp = bp;                             // ERROR! Base is not Derived
                                                                       See Example: e73.cpp
    }                                                                                                              dp = static_cast<Derived *>(bp);              // explicit conversion
 http://www.faculty.itu.edu.tr/buzluca                              ©1999-2010 Dr. Feza BUZLUCA        7.5    http://www.faculty.itu.edu.tr/buzluca                     ©1999-2010 Dr. Feza BUZLUCA   7.6
 http://www.buzluca.info                                                                                      http://www.buzluca.info




                                                                                                                                                                                                            1
Object Oriented Programming                                                                     Object Oriented Programming

   If the class Base is a private base of Derived , then the implicit conversion of a                                  Heterogeneous Linked Lists
   Derived* to Base* would not be done.                                                           Using the inheritance and pointers, heterogeneous linked lists can be created.
   Because, in this case a public member of Base can be accessed through a pointer                A list specified in terms of pointers to a base class can hold objects of any class
   to Base but not through a pointer to Derived.                                                  derived from this base class.
   Example:                                                                                       We will discuss heterogeneous lists again, after we have learnt polymorphism.

   class Base{
       int m1;                                                                                          Example: A list of teachers and principals
      public:
       int m2;                           // m2 is a public member of Base                                                        next        next         next           next          next       0
                                                                                                         head
   };

   class Derived : private Base {        // m2 is not a public member of Derived
                                                                                                         insert()
      :                                                                                                                        Teacher t1
                                                                                                         delete()                                                       Teacher t2 Teacher t3
   };
                                                                                                                                            Principal p1 Principal p2
                                                                                                       List my_list
   Derived d;                                                                                                                                                              See Example: e74.cpp
   d.m2 = 5;                               // ERROR! m2 is private member of Derived
   Base *bp = &d;                          // ERROR! private base
   bp = static_cast<Base*>(&d);            // ok: explicit conversion                            There is a list class in the Standard Template Library (STL) of the C++. You don’t
   bp->m2 = 5;                             // ok                                                 need to write classes to build linked lists. You can use the list class of the library.

 http://www.faculty.itu.edu.tr/buzluca                      ©1999-2010 Dr. Feza BUZLUCA   7.7    http://www.faculty.itu.edu.tr/buzluca                             ©1999-2010 Dr. Feza BUZLUCA    7.8
 http://www.buzluca.info                                                                         http://www.buzluca.info




                                                                                                                                                                                                        2

Contenu connexe

Tendances

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptJulie Iskander
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaRafael Magana
 
Ms Ajax String And Object Extensions
Ms Ajax String And Object ExtensionsMs Ajax String And Object Extensions
Ms Ajax String And Object Extensionsjason hu 金良胡
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Basic Mechanism of OOPL
Basic Mechanism of OOPLBasic Mechanism of OOPL
Basic Mechanism of OOPLkwatch
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScripttaobao.com
 
javaimplementation
javaimplementationjavaimplementation
javaimplementationFaRaz Ahmad
 
Oop06 6
Oop06 6Oop06 6
Oop06 6schwaa
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++Haris Lye
 

Tendances (20)

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Enumerable
EnumerableEnumerable
Enumerable
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Ms Ajax String And Object Extensions
Ms Ajax String And Object ExtensionsMs Ajax String And Object Extensions
Ms Ajax String And Object Extensions
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
Basic Mechanism of OOPL
Basic Mechanism of OOPLBasic Mechanism of OOPL
Basic Mechanism of OOPL
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
Objective c
Objective cObjective c
Objective c
 
Oop06 6
Oop06 6Oop06 6
Oop06 6
 
Brief Summary Of C++
Brief Summary Of C++Brief Summary Of C++
Brief Summary Of C++
 

En vedette

Oop09 6
Oop09 6Oop09 6
Oop09 6schwaa
 
Oop02 6
Oop02 6Oop02 6
Oop02 6schwaa
 
Oop10 6
Oop10 6Oop10 6
Oop10 6schwaa
 
Oop05 6
Oop05 6Oop05 6
Oop05 6schwaa
 
Oop03 6
Oop03 6Oop03 6
Oop03 6schwaa
 
Oop01 6
Oop01 6Oop01 6
Oop01 6schwaa
 
Oop04 6
Oop04 6Oop04 6
Oop04 6schwaa
 

En vedette (8)

Oop09 6
Oop09 6Oop09 6
Oop09 6
 
Oop02 6
Oop02 6Oop02 6
Oop02 6
 
Oop10 6
Oop10 6Oop10 6
Oop10 6
 
Inheritance
InheritanceInheritance
Inheritance
 
Oop05 6
Oop05 6Oop05 6
Oop05 6
 
Oop03 6
Oop03 6Oop03 6
Oop03 6
 
Oop01 6
Oop01 6Oop01 6
Oop01 6
 
Oop04 6
Oop04 6Oop04 6
Oop04 6
 

Similaire à Oop07 6

Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctorSomnath Kulkarni
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfLadallaRajKumar
 
DeclaringConstructir.pptx
DeclaringConstructir.pptxDeclaringConstructir.pptx
DeclaringConstructir.pptxSinbadMagi
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
Review constdestr
Review constdestrReview constdestr
Review constdestrrajudasraju
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONShweta Shah
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop Samad Qazi
 

Similaire à Oop07 6 (20)

Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
C++
C++C++
C++
 
C++
C++C++
C++
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
DeclaringConstructir.pptx
DeclaringConstructir.pptxDeclaringConstructir.pptx
DeclaringConstructir.pptx
 
Java String
Java String Java String
Java String
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
 
Review constdestr
Review constdestrReview constdestr
Review constdestr
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Java Constructor
Java ConstructorJava Constructor
Java Constructor
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 

Oop07 6

  • 1. Object Oriented Programming License: http://creativecommons.org/licenses/by-nc-nd/3.0/ Object Oriented Programming POINTERS TO OBJECTS class String{ Example: Objects are stored in memory, so pointers can point to objects just as they can to int size; variables of basic types. char *contents; The new Operator: public: The new operator allocates memory of a specific size from the operating system and String(); // Default constructor returns a pointer to its starting point. String(const char *); // Constructor If it is unable to find space, in returns a 0 pointer. String(const String &); // Copy constructor When you use new with objects, it does not only allocate memory for the object, it also const String& operator=(const String &); // Assignment operator creates the object in the sense of invoking the object’s constructor. void print() const ; ~String(); // Destructor This guarantees that the object is correctly initialized, which is vital for avoiding }; programming errors. int main() The delete Operator: { To ensure safe and efficient use of memory, the new operator is matched by a String *sptr = new String[3]; // Creats 3 objects corresponding delete operator that releases the memory back to the operating system. See Example: e71.cpp String s1("String_1"); // A String object If you create an array with new Type[ ];, you need the brackets when you delete it: String s2("String_2"); // Another String object *sptr = s1; // Assignment to the first elelement of the array int * ptr = new int[10]; *(sptr + 1) = s2; // Assignment to the second element of the array : sptr->print(); // Prints the first element delete [ ] ptr; (sptr+1)->print(); // Prints the second element Don’t forget the brackets when deleting arrays of objects. sptr[1].print(); // Prints the second element Using them ensures that all the members of the array are deleted and that the delete[] sptr; // Objects pointed by sptr are deleted destructor is called for each one. return 0; If you forget the brackets, only the first element of the array will be deleted. } http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.1 http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.2 http://www.buzluca.info http://www.buzluca.info Object Oriented Programming Object Oriented Programming Linked List of Objects In the previous example the Teacher class must have a pointer to the next object and the list class must be declared as a friend, to enable users of this class A class may contain a pointer to objects of its type. This pointer can be used to building linked lists. build a chain of objects, a linked list. If this class is written by the same group then it is possible to put such a pointer class Teacher{ in the class. friend class TeacherList; But usually programmers use ready classes, written by other groups, for example string name; classes from libraries. And these classes may not have a next pointer. int age, numOfStudents; Teacher * next; // Pointer to next object of teacher To build linked lists of such ready classes the programmer can derive a new class public: (TeacherForList) with a next pointer. Teacher(const string &, int, int); // Constructor void print() const; class TeacherForList : public Teacher{ // TeacherForList is a Teacher with a pointer // linked list for teachers friend class Teacher_list; const string& getName() const {return name;} class TeacherList{ TeacherForList * next; // next Teacher ~Teacher() // Destructor Teacher *head; TeacherForList(const string &, int, int); // constructor }; public: }; TeacherList(){head=0;} bool append(const string &,int,int); TeacherForList :: TeacherForList (const string & n, int a, int nos) bool del(const string &); :Teacher (n, a, nos) void print() const ; { ~TeacherList(); next = 0; See Example: e72.cpp }; } http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.3 http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.4 http://www.buzluca.info http://www.buzluca.info Object Oriented Programming Object Oriented Programming Pointers and Inheritance Another way to build linked lists of such ready classes without using inheritance If a class Derived has a public base class Base, then a pointer to Derived can be is to define a node class. assigned to a variable of type pointer to Base without use of explicit type Each object of the node class will hold the addresses of an element of the list. conversion. In other words, a pointer to Base can carry the address of an object of Derived. The opposite conversion, for pointer to Base to pointer to Derived, must be explicit. class TeacherNode{ // TeacherNode has a Teacher friend class TeacherList; For example, a pointer to Teacher can point to objects of Teacher and to objects of Teacher * element; // The element of the list Principal. TeacherNode * next; // next node A principal is a teacher, but a teacher is not always a principal. TeacherNode(const string &, int, int); // constructor ~TeacherNode(); // destructor class Base{ }; }; TeacherNode::TeacherNode(const string & n, int a, int nos){ class Derived : public Base { element = new Teacher(n, a, nos); next = 0; }; } Derived d; TeacherNode::~TeacherNode(){ Base *bp = &d; // implicit conversion delete element; Derived *dp = bp; // ERROR! Base is not Derived See Example: e73.cpp } dp = static_cast<Derived *>(bp); // explicit conversion http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.5 http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.6 http://www.buzluca.info http://www.buzluca.info 1
  • 2. Object Oriented Programming Object Oriented Programming If the class Base is a private base of Derived , then the implicit conversion of a Heterogeneous Linked Lists Derived* to Base* would not be done. Using the inheritance and pointers, heterogeneous linked lists can be created. Because, in this case a public member of Base can be accessed through a pointer A list specified in terms of pointers to a base class can hold objects of any class to Base but not through a pointer to Derived. derived from this base class. Example: We will discuss heterogeneous lists again, after we have learnt polymorphism. class Base{ int m1; Example: A list of teachers and principals public: int m2; // m2 is a public member of Base next next next next next 0 head }; class Derived : private Base { // m2 is not a public member of Derived insert() : Teacher t1 delete() Teacher t2 Teacher t3 }; Principal p1 Principal p2 List my_list Derived d; See Example: e74.cpp d.m2 = 5; // ERROR! m2 is private member of Derived Base *bp = &d; // ERROR! private base bp = static_cast<Base*>(&d); // ok: explicit conversion There is a list class in the Standard Template Library (STL) of the C++. You don’t bp->m2 = 5; // ok need to write classes to build linked lists. You can use the list class of the library. http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.7 http://www.faculty.itu.edu.tr/buzluca ©1999-2010 Dr. Feza BUZLUCA 7.8 http://www.buzluca.info http://www.buzluca.info 2