System Programming Practical Session 8 C++ classes.

Slides:



Advertisements
Similar presentations
Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב ' Classes – - המשך.
System Programming Practical Session 9 C++ classes.
1 CSE 303 Lecture 21 Classes and Objects in C++ slides created by Marty Stepp
Operator Overloading and Memory Management. Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
OOP Languages: Java vs C++
1 CSE 303 Lecture 22 Advanced Classes and Objects in C++ slides created by Marty Stepp
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
1 COMS 261 Computer Science I Title: Classes Date: November 4, 2005 Lecture Number: 27.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
On dynamic memory and classes ● We previously had only discussed dynamic memory in regards to structs and dynamic arrays. ● However, they can be used (to.
Memory Management.
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Learning Objectives Pointers as dada members
Copy Constructor / Destructors Stacks and Queues
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
C++ Programming Functions
Programming with ANSI C ++
C++ Programming Functions
Pointers Revisited What is variable address, name, value?
Memberwise Assignment / Initialization
The Bag and Sequence Classes with Linked Lists
Dynamically Allocated Memory
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Automatics, Copy Constructor, and Assignment Operator
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Automatics, Copy Constructor, and Assignment Operator
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Practical Session 4 Rule of 5 R-value reference Unique pointer
9-10 Classes: A Deeper Look.
C++ Constructor Insanity CSE 333 Summer 2018
Destructor CSCE 121.
Chapter 9 - Object-Oriented Programming: Inheritance
Resource Allocation and Ownership
Java Programming Language
C++ Constructor Insanity CSE 333 Autumn 2018
COP 3330 Object-oriented Programming in C++
C++ Constructor Insanity CSE 333 Winter 2019
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Introduction to Classes and Objects
Presentation transcript:

System Programming Practical Session 8 C++ classes

Outline Basic concepts Classes that hold pointers Destructor Copy constructor Operator=

C++ simple class example // THE DECLARATION FILE OF THE CLASS POINT (Point.h)    class Point    {   public:      Point();      Point(double xval, double yval);      void move(double dx, double dy);      double getX() const;      double getY() const;        private:      double _x;      double _y;   };

C++ simple class example //  THE IMPLEMENTATION FILE OF CLASS POINT (Point.cpp)  #include "Point.h" Point::Point():_x(0), _y(0){ } Point::Point(double xval, double yval):_x(xval),_y(yval){} void Point::move(double dx, double dy) {   _x = _x + dx;   _y = _y + dy; } double Point::getX() const {   return _x; double Point::getY() const {     return _y;

C++ simple class example Use example #include <iostream> #include “point.h” int main( ){     Point p(0,0); //Point p; p.move(10,15); const Point p2(20,12); std::cout << p2.getx() << std::endl;  std::cout << p2.gety() << std::endl;       // p2.move(1,1);     compilation error since move is not declared const }

Member Initialization List class Circle{ public: Circle(); Circle(double centerX, double centerY, double radius); ………….. private: Point _center; double _radius; }; Circle::Circle(): _center(0,0) , _radius(1) {} Circle::Circle(double centerX, double centerY, double radius): _center(centerX, centerY) , _radius(radius) {}

Member Initialization List Example: Circle::Circle(): _center(0,0) , _radius(1) {} Rules The initial value can be any expression. The order the initialization happens is according to the order the member variables are declared. The member initialization list is executed before the body of the constructor. Not initializing a member via the initialization list means implicitly calling its default constructor Const members of a class can only be initialized via member initialization list.

Inheritance Syntax: class Derived : public Base { }; #include “point.h” #include “color.h” // suppose that we have defined class Color… class Pixel : public Point{ Color _color; …… }; Pixel::Pixel(Point point, Color color) : Point(point), _color(color) {} // example of a derived constructor calling the base constructor // Syntax: Derived::Derived(….) : Base(….) {…}

Operator -> Shortcut for accessing members of an object pointed by a pointer. ptr->member is a shortcut for (*ptr).member class Point{.....} int main( ){     Point *p1=new Point(0,0);     Point p2(0,0);     p1->getX();     (*p1).getX();     p2.getX();     (&p2)->getX(); }

Objects In C++, object variables hold values, not object references. When one object is assigned to another, a copy of the actual values is made. When modifying an object in a function, you must remember to use call by reference. Two object variables cannot jointly access one object. If you need this effect in C++, then you need to use pointers. An object variable can only hold values of a particular type. If you want a variable to hold objects from different subclasses, you need to use pointers. If you want a variable point to either null or to an actual object, then you need to use pointers in C++.

Classes that hold pointers A class that has a pointer data member should include the following member functions: A virtual destructor A copy constructor operator= (assignment)

Linked List Example Link data_ next_ List head_ data_ next_ data_ next_

Link class Link { private: Link* next_; std::string data_; public:     Link(const std::string& data,  Link* link);     Link(const Link& aLink); //copy constructor     virtual ~Link(); // destructor     void setNext(Link* link);     Link* getNext() const;     const std::string& getData() const; };

Link Link::Link(const std::string& data, Link* link) : data_(data) {    setNext(link); } void Link::setNext(Link* link) {    next_=link; Link* Link::getNext() const {    return next_; const std::string& Link::getData() const {    return data_; Link::~Link() { } \\destructor Link::Link(const Link& aLink) { \\copy constructor    data_=aLink.getData();    next_=0;

List class List { private: Link* head_; Link* copy() const;     void clear();     public:     List();      const Link* getHead() const;     void insertData(const std::string& data);     void removeFirst();     List(const List& aList);     virtual ~List();     List& operator=(const List &L); };

List::List() : head_(0) { } const Link* List::getHead() const{    return head_; } void List::insertData(const std::string& data){    head_ = new Link(data, head_); void List::removeFirst(){    if (0 != head_) {      Link* tmp = head_;      head_ = head_->getNext();      delete tmp;   } List::~List() {   clear(); void List::clear(){    while (0 != head_) {      removeFirst();

Link* List::copy() const {   if (0 == getHead())     return 0;   else {       Link *head = new Link(*getHead());      Link *next = head;      for (Link *origPtr = getHead()->getNext(); 0 != origPtr;  origPtr = origPtr->getNext()) {         next->setNext(new Link(*origPtr));        next = next->getNext();      }     return head;   } } List::List(const List &aList){     head_ = aList.copy(); } List & List::operator=(const List &L) {   if (this == &L)       return *this;   clear();   head_ = L.copy();   return *this;

Destructor An object's destructor function is called when that object is about to "go away“. For local variables (objects declared on the stack) and value parameters – When the variable goes out of scope. For dynamically allocated storage (objects on the heap) – When the programmer frees the storage using delete.

Destructor void f(List L) { List *p = new List(); while (...) {             ...           }           delete p;         } Is a destructor function of a reference parameter called at the end of the function? No!

/**   * Destructor: "deep delete"   */  List::~List() {    clear();  } void List::removeFirst() {   if (0 != head_) {     Link* tmp = head_;     head_ = head_->getNext();         delete tmp;   } } void List::clear(){   while (0 != head_) {     removeFirst();

Copy Constructor An object's copy constructor is called (automatically, not by the programmer) when it is created, and needs to be initialized to be a copy of an existing object. This happens when an object is: Passed as a value parameter to a function, Point q(2,2); Point p(0,0); p.moveTo(q); //moveTo(Point point) Returned (by value) as a function result, Declared with initialization from an existing object of the same class. void f(Point p){ Point temp=p;     Point temp2(p);  …

Example List f( List L ); int main() { List L1, L2; ...    ...    L2 = f( L1 );      // copy constructor called here to copy L1 } List f( List L ) {    List tmp1 = L;    // copy constructor called here to copy L    List tmp2(L);     // copy constructor called here to copy L    return tmp1;      // copy constructor called here 

Copy Constructor Declaration class List {    public: ……     List(const List &L);// copy constructor    ... };

Copy Constructor Definition List::List(const List &aList){     head_ = aList.copy(); } Link* List::copy() const {   if (0 == getHead())     return 0;    else {      Link *head = new Link(*getHead());      Link *next = head;      for (Link *origPtr = getHead()->getNext();   0 != origPtr; origPtr = origPtr->getNext()) {        next->setNext(new Link(*origPtr));        next = next->getNext();      }     return head;   }

Operator= By default, class assignment is just a field-by-field assignment If a class includes pointer fields, the default assignment operator causes aliasing which lead to trouble! Solution: overload operator= to perform deep copy. Syntax: List & operator=(const List &L);

Operator= Note that operator= differs from the copy constructor in three important ways: The object being assigned to has already been initialized; therefore, if it has a pointer field, the storage pointed to must be freed to prevent a storage leak. It is possible for a programmer to assign from a variable into itself; for example: L1 = L1. The operator= code must check for this case, and do nothing. The operator= code must return a value

Definition of operator= It should always include the following 4 sections: check assignment to self clear existing data members copy data member from other return this List & List::operator=(const List &L) {  if (this == &L) {      return *this;    }    clear();    head_ = L.copy();    return *this; }