Presentation is loading. Please wait.

Presentation is loading. Please wait.

System Programming Practical Session 8 C++ classes.

Similar presentations


Presentation on theme: "System Programming Practical Session 8 C++ classes."— Presentation transcript:

1 System Programming Practical Session 8 C++ classes

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

3 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;   };

4 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;

5 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 }

6 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) {}

7 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.

8 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(….) {…}

9 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(); }

10 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++.

11 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)

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

13 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; };

14 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;

15 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); };

16 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();

17 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;

18 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.

19 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!

20 /**   * 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();

21 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); 

22 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 

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

24 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();    != origPtr; origPtr = origPtr->getNext()) {        next->setNext(new Link(*origPtr));        next = next->getNext();      }     return head;   }

25 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);

26 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

27 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; }


Download ppt "System Programming Practical Session 8 C++ classes."

Similar presentations


Ads by Google