CS410 – Software Engineering Lecture #11: C++ Basics IV

Slides:



Advertisements
Similar presentations
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Advertisements

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.
1 Classes Provide Constructors Mechanism to specify object creation Client can use objects similar to native types Constructor is member function with.
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.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
Classes: A Deeper Look Systems Programming.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 1 Today’s Topics The operators new and deleteThe operators new and delete The scope.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
March 6, 2014CS410 – Software Engineering Lecture #10: C++ Basics IV 1 Structure Pointer Operator For accessing members in structures and classes we have.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
More C++ Features True object initialisation
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Learners Support Publications Constructors and Destructors.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
CS410 – Software Engineering Lecture #12: C++ Basics V
Yan Shi CS/SE 2630 Lecture Notes
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
References as Function Arguments
CISC181 Introduction to Computer Science Dr
Constructor & Destructor
Pointers Revisited What is variable address, name, value?
This pointer, Dynamic memory allocation, Constructors and Destructor
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
CS212: Object Oriented Analysis and Design
Popping Items Off a Stack Lesson xx
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and destructors
Constructors and Destructors
7 Arrays.
9-10 Classes: A Deeper Look.
Java Programming Language
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
A Deeper Look at Classes
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Overloading the << Operator
CS410 – Software Engineering Lecture #6: Advanced C++ I
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
SPL – PS3 C++ Classes.
Presentation transcript:

CS410 – Software Engineering Lecture #11: C++ Basics IV The this Pointer The keyword this denotes a self-referential pointer to a class object. It cannot be used in static member functions. Example: class Point { public: void init(double u, double v) { x = u; y = v; } Point inverse() { x = -x; y = -y; return (*this); } Point* where_am_I() { return this; } Private: double x, y; }; October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

static and const Members The const and static member function implementation can be understood terms of this pointer access. An ordinary member function is invoked as x.fcn(i, j, k). It has an explicit argument list i, j, k and an implicit argument list that includes the members of x (accessible through the this pointer). A static member function does not get the implicit arguments. A const member function cannot modify its implicit arguments. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors and Destructors A constructor is a member function whose name is the same as the class name. It constructs values of the class type. This process involves initializing data members and, frequently, allocating free store by using new. A destructor is a member function whose name is the class name preceded by the ~ character. It finalizes objects of the class type. Typically, a destructor deallocates store assigned to the object by using delete. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors and Destructors can take arguments, can be overloaded. A constructor is invoked whenever its associated type is used in a definition, call-by-value is used to pass a value to a function, the return value of a function must create a value of associated type. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors and Destructors cannot take arguments, cannot be overloaded. A destructor is invoked implicitly whenever an object goes out of scope. Constructors and destructors do not have return types and cannot use return expression statements. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Classes with Constructors Example: A data type ModInt for storing numbers that are computed with a modulus. class ModInt { public: ModInt(int i); // constructor declaration void assign(int i) { v = i % modulus; } void print() const {cout << v << ‘\n’; } const static int modulus; private: int v; }; ModInt::ModInt(int i) { v = i % modulus; } // constructor definition const int ModInt::modulus = 60; October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Classes with Constructors void main() { ModInt a(5); ModInt b(62); a.print(); b.print(); } What does the output look like? 5 2 October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Classes with Constructors What happens if we declare a variable c as follows: ModInt c; Since this class has only one constructor, and this constructor needs one int argument, this declaration causes a compile-time error. The declaration above requires a default constructor. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

The Default Constructor A constructor requiring no arguments is called the default constructor. It can be a constructor with an empty argument list or one whose arguments all have default values. It has the special purpose of initializing arrays of objects of its class. In the ModInt example, it would be useful to define a default value of v to be 0. To achieve this, we could add the following default constructor: ModInt() { v = 0; } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

The Default Constructor main () { ModInt s1, s2; ModInt d[5]; ModInt s1.print(); ModInt s2.print(); ModInt d[3].print(); } Output: October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

The Default Constructor If a class does not have a constructor, the system provides a default constructor. If a class has constructors but no default constructor, array allocation causes a syntactic error. In our ModInt example, the following constructor could serve as both a general initializer and a default constructor: ModInt(int i = 0) { v = i % modulus; } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructor Initializers A special syntax is used for initializing class members. Constructor initializers for class members can be specified in a comma-separated list that follows the constructor parameter list. The previous example can be recoded as: ModInt(int i = 0): v(i % modulus) {} Notice that initialization replaces assignment. The individual members must be initializable as member-name (expression list). October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors as Conversions Constructors of a single parameter are used automatically for conversion unless declared with the keyword explicit. For example, T1::T1(T2) provides code that can be used to convert a T2 object to a T1 object. Let us take a look at the following class PrintChar, whose purpose is to print invisible characters with their ASCII designation (for example, the code 07 is alarm or bel). October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors as Conversions class PrintChar { public: PrintChar(int i = 0) : c(i % 128) {} void print() const { cout << rep[c]; } private: int c; static const char* rep[128]; }; const char *PrintChar::rep[128] = {“nul”, “soh”, “stx”, …, “}”, “~”, “del”}; October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors as Conversions int main() { PrintChar c; for (int i = 0; i < 128; i++) c = i; // or: c = static_cast<PrintChar>(i); c.print(); cout << endl; } This program prints out the first 128 ASCII characters or their printable representations. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Structure Pointer Operator For accessing members in structures and classes we have used the member operator ‘.’. Now we introduce the structure pointer operator ‘->’, which provides access to the members of a structure via a pointer. If a pointer variable is assigned the address of a structure or class object, a member of the object can be accessed by the ‘->’ operator. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Structure Pointer Operator Example: int main() { MyClass a, *b; a.SetValue(9); b->SetValue(5); (*b).SetValue(7); } Member access is correct in all three cases. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

Constructors and Destructors Now we are going to talk about two examples for classes with constructors and destructors: a singly linked list a two-dimensional array overloaded operators and user-defined conversions October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List We are going to develop a singly linked list datatype. This is the prototype of many useful dynamic abstract data types (ADTs) called self-referential structures. Self-referential structures have pointer members that refer to objects of their own type. Such structures are the basis of many useful container classes. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List We want to be able to perform the following list operations: Prepend: adds an element to the front of the list First: returns the first element in the list Print: prints the list contents Del: deletes the first element in the list Release: destroys the list October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List struct SListElem { char data; SListElem *next; }; class SList public: SList(): h(0) {} // 0 denotes empty list ~SList() { Release(); } void Prepend(char c); void Del(); SListElem *First() const { return h; } void Print() const; void Release(); private: SListElem *h; // head of SList October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List void SList::Prepend(char c) { SListElem *temp = new SListElem; // create new element assert( temp != 0); temp->next = h; // link to SList temp->data = c; h = temp; // update head of SList } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List void SList::Del() { SListElem *temp = h; if (temp != 0) h = h->next; // let head point to 2nd element delete temp; // delete 1st element } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List void SList::Print() const { SListElem *temp = h; while (temp != 0) // detect end of Slist cout << temp->data << " -> "; temp = temp->next; // temp proceeds to next element } cout << "NULL\n"; October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List void SList::Release() { while (h != 0) // as long as there are elements... Del(); // ... delete them. } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

CS410 – Software Engineering Lecture #11: C++ Basics IV A Singly Linked List int main() { SList MyList; MyList.Prepend('S'); MyList.Prepend('T'); MyList.Prepend('A'); MyList.Prepend('R'); MyList.Del(); MyList.Print(); } Output: R -> A -> T -> S -> NULL October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array We are now going to implement a dynamic and safe two-dimensional array. We will use a pointer-to-pointer-to-base type structure for this implementation. October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array class Matrix { public: Matrix(int sizeX, int sizeY); ~Matrix(); int GetSizeX() const { return dx; } int GetSizeY() const { return dy; } long &Element(int x, int y); // return reference to an element void Print() const; private: long **p; // pointer to a pointer to a long integer int dx, dy; }; October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array Matrix::Matrix(int sizeX, int sizeY) : dx(sizeX), dy(sizeY) { assert(sizeX > 0 && sizeY > 0); p = new long*[dx]; // create array of pointers to long integers assert(p != 0); for (int i = 0; i < dx; i++) p[i] = new long[dy]; // for each pointer, create array of long integers assert(p[i] != 0); for (int j = 0; j < dy; j++) p[i][j] = 0; } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array Matrix::~Matrix() { for (int i = 0; i < dx; i++) delete [] p[i]; // delete arrays of long integers delete [] p; // delete array of pointers to long integers } long &Matrix::Element(int x, int y) assert(x >= 0 && x < dx && y >= 0 && y < dy); return p[x][y]; October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array void Matrix::Print() const { cout << endl; for (int y = 0; y < dy; y++) for (int x = 0; x < dx; x++) cout << p[x][y] << "\t"; } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array int main() { Matrix MyMatrix(3, 5); MyMatrix.Element(1, 1) = 88; MyMatrix.Element(2, 2) = 11; MyMatrix.Element(2, 4) = MyMatrix.Element(1, 1) + MyMatrix.Element(2, 2); cout << MyMatrix.Element(2, 4) << endl; MyMatrix.Print(); } October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV

A Two-Dimensional Array Output: 99 0 0 0 0 88 0 0 0 11 0 0 0 0 0 99 October 11, 2016 CS410 – Software Engineering Lecture #11: C++ Basics IV