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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 Classes Provide Constructors Mechanism to specify object creation Client can use objects similar to native types Constructor is member function with.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
CS Advanced C++ Exception Handling Topic #5.
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];
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Classes: A Deeper Look Systems Programming.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
Operator Overloading and Type Conversions
 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.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Case Study - Fractions Timothy Budd Oregon State University.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
More C++ Features True object initialisation
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
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.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
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.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
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.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
Advanced Programming in C
CS410 – Software Engineering Lecture #12: C++ Basics V
Eine By: Avinash Reddy 09/29/2016.
Pointers and Dynamic Arrays
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.
CS410 – Software Engineering Lecture #11: C++ Basics IV
Constructor & Destructor
Chapter 15 Pointers, Dynamic Data, and Reference Types
Operator overloading Dr. Bhargavi Goswami
The vector Container Type
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
A Deeper Look at Classes
CS410 – Software Engineering Lecture #6: Advanced C++ I
(4 – 2) Introduction to Classes in C++
SPL – PS3 C++ Classes.
Introduction to Classes and Objects
Presentation transcript:

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 resolution operatorThe scope resolution operator Nested classesNested classes Static and const membersStatic and const members The “this” pointerThe “this” pointer Constructors and destructorsConstructors and destructors

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 2 The Operators new and delete The unary operators new and delete are available to manipulate free store.The unary operators new and delete are available to manipulate free store. They are more convenient than the C functions malloc(), calloc(), and free().They are more convenient than the C functions malloc(), calloc(), and free(). Free store is a system-provided memory pool for objects whose lifetime is directly managed by the programmer.Free store is a system-provided memory pool for objects whose lifetime is directly managed by the programmer. This adds responsibility to the programmer and can easily lead to problems such as memory leaks.This adds responsibility to the programmer and can easily lead to problems such as memory leaks. On the other hand, manipulating free store is an efficient and flexible way to handle data structures such as trees and lists.On the other hand, manipulating free store is an efficient and flexible way to handle data structures such as trees and lists.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 3 The Operators new and delete The programmer creates an object using new, and destroys the object using delete.The programmer creates an object using new, and destroys the object using delete. The operator new is typically used in the following forms:The operator new is typically used in the following forms: new type-namenew type-name new type-name initializernew type-name initializer new type-name [expression]new type-name [expression] In each case, there are at least two effects:In each case, there are at least two effects: An appropriate amount of store is allocated from free store to contain the named type.An appropriate amount of store is allocated from free store to contain the named type. The base address of the object is returned as the value of the new expression.The base address of the object is returned as the value of the new expression.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 4 The Operators new and delete Example:… int *p, *q; p = new int(5); p = new int(5); q = new int[10]; q = new int[10];… In this code, the pointer variable p is assigned the address of the store obtained,the pointer variable p is assigned the address of the store obtained, The location pointed at by p is initialized to the value 5,The location pointed at by p is initialized to the value 5, the pointer variable q is assigned the base address of an int array of size 10.the pointer variable q is assigned the base address of an int array of size 10.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 5 The Operators new and delete Notice the following things: When memory is unavailable, the operator new can either throw a bad_alloc exception or return the value 0.When memory is unavailable, the operator new can either throw a bad_alloc exception or return the value 0. If no initializer is provided, the content of the allocated memory is undefined.If no initializer is provided, the content of the allocated memory is undefined. Arrays cannot be initialized using the new operator.Arrays cannot be initialized using the new operator. Objects created by the new operator always need to be destroyed by the delete operator as soon as they are not used by the program any more.Objects created by the new operator always need to be destroyed by the delete operator as soon as they are not used by the program any more.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 6 The Operators new and delete The operator delete destroys an object created by new.The operator delete destroys an object created by new. This returns its allocated storage to free store for reuse.This returns its allocated storage to free store for reuse. The operator delete is used in the following forms:The operator delete is used in the following forms: delete expressiondelete expression delete [] expressiondelete [] expression The first form is used when the corresponding new expression has not allocated an array.The first form is used when the corresponding new expression has not allocated an array. The second form (empty brackets) is used when the original allocation was an array.The second form (empty brackets) is used when the original allocation was an array. The return type of delete is void (no return value).The return type of delete is void (no return value).

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 7 The Operators new and delete Example: Dynamic allocation of an array int main() { int *data; int *data; int size; int size; cout << “\nEnter array size: “; cout << “\nEnter array size: “; cin >> size; cin >> size; assert(size > 0); assert(size > 0); data = new int[size]; data = new int[size]; assert(data != 0); assert(data != 0); for (int j = 0; j < size; j++) for (int j = 0; j < size; j++) cout << (data[j] = j) << ‘\n’; cout << (data[j] = j) << ‘\n’; delete [] data; delete [] data; return 0; return 0;} Starting the program: Enter array size:

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 8 The Scope Resolution Operator The concept of classes adds new scope rules to those of the kernel language.The concept of classes adds new scope rules to those of the kernel language. You remember that one point of classes is to provide an encapsulation technique.You remember that one point of classes is to provide an encapsulation technique. It makes sense that all names declared within a class be treated within their own scope as distinct from external names, function names, and other class names.It makes sense that all names declared within a class be treated within their own scope as distinct from external names, function names, and other class names. This creates the need for the scope resolution operator.This creates the need for the scope resolution operator.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 9 The Scope Resolution Operator The scope resolution operator is the highest- precedence operator in the C++ language.The scope resolution operator is the highest- precedence operator in the C++ language. It comes in two forms:It comes in two forms: ::j (unary operator – refers to external scope)::j (unary operator – refers to external scope) MyClass::j (binary operator – refers to class scope)MyClass::j (binary operator – refers to class scope) Its unary form is used to access a name that has external scope and has been hidden by local or class scope.Its unary form is used to access a name that has external scope and has been hidden by local or class scope.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 10 The Scope Resolution Operator Example: int count = 0; void how_many(double w[], double x, int &count) { for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) count += (w[i] == x); // local count count += (w[i] == x); // local count ++ ::count; // global count tracks calls ++ ::count; // global count tracks calls}

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 11 The Scope Resolution Operator To better understand this program fragment, we change the parameter int &count to int &cnt: int count = 0; void how_many(double w[], double x, int &cnt) { for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) cnt += (w[i] == x); // local count cnt += (w[i] == x); // local count ++count; // global count tracks calls ++count; // global count tracks calls}

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 12 The Scope Resolution Operator Binary scope resolution is used to clarify names that are reused within classes.Binary scope resolution is used to clarify names that are reused within classes. For example, we need scope resolution to define member functions:For example, we need scope resolution to define member functions: class Student {public: void PrintName(); void PrintName();private: string studentName; string studentName;}; void Student::PrintName() { cout << studentName; cout << studentName;}

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 13 Nested Classes Like blocks and namespaces, classes are scopes and can nest.Like blocks and namespaces, classes are scopes and can nest. Nesting allows local hiding of names and local allocation of resources.Nesting allows local hiding of names and local allocation of resources. This is often desirable when a class is needed as part of the implementation of a larger construct.This is often desirable when a class is needed as part of the implementation of a larger construct.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 14 Nested Classes Example: char c; // external scope ::c class X // outer class declaration X:: {public: char c; // X::c char c; // X::c class Y // inner class declaration X::Y:: class Y // inner class declaration X::Y:: { public: public: void foo(char e) { X t; ::c = t.X::c = c = e; } void foo(char e) { X t; ::c = t.X::c = c = e; } private: private: char c; // X::Y::c char c; // X::Y::c }; };}; t.X::c is the same as t.c

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 15 static and const Members Using the modifier static in declaring a data member means that the data member is independent of any given class variable.Using the modifier static in declaring a data member means that the data member is independent of any given class variable. The data member is part of the class but separate from any single class object.The data member is part of the class but separate from any single class object. You remember that nonstatic data members are created for each instance of the class.You remember that nonstatic data members are created for each instance of the class. Using static data allows class data to be scoped to the class but still require only one object for its storage.Using static data allows class data to be scoped to the class but still require only one object for its storage. Without static data members, data required by all instances of a class would have to be global.Without static data members, data required by all instances of a class would have to be global.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 16 static and const Members Since static members are independent of a particular instance, they can be accessed in the form class-name :: identifier Example: class Point {public: static int how_many; static int how_many;}; Point::how_many = 0; …++Point::how_many;

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 17 static and const Members A static member function has the modifier static precede the return type inside the class declaration. Example: class Foo { static int foo_function(); static int foo_function();}; int Foo::foo_function() {…}

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 18 static and const Members A data member declared with the const modifier cannot be modified after initialization.A data member declared with the const modifier cannot be modified after initialization. syntactically, a const member function has the modifier follow the argument list inside the class declaration.syntactically, a const member function has the modifier follow the argument list inside the class declaration.Example: class Foo { int foo_function() const; int foo_function() const;}; int Foo::foo_function() const {}

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 19 static and const Members The const and static member function implementation can be understood terms of this pointer access.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).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).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 static member function does not get the implicit arguments. A const member function cannot modify its implicit arguments.A const member function cannot modify its implicit arguments.

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

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 21 Constructors and Destructors A constructor is a member function whose name is the same as the class name.A constructor is a member function whose name is the same as the class name. It constructs values of the class type.It constructs values of the class type. This process involves initializing data members and, frequently, allocating free store by using new.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.A destructor is a member function whose name is the class name preceded by the ~ character. It finalizes objects of the class type.It finalizes objects of the class type. Typically, a destructor deallocates store assigned to the object by using delete.Typically, a destructor deallocates store assigned to the object by using delete.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 22 Constructors and Destructors Constructors can take arguments,can take arguments, can be overloaded.can be overloaded. A constructor is invoked whenever its associated type is used in a definition,its associated type is used in a definition, call-by-value is used to pass a value to a function,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.the return value of a function must create a value of associated type.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 23 Constructors and Destructors Destructors cannot take arguments, cannot take arguments, cannot be overloaded. 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.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 24 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;

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 25 Classes with Constructors void main() { ModInt a(5); ModInt b(62); a.print();b.print();} What does the output look like? 52

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 26 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.

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 27 The Default Constructor A constructor requiring no arguments is called 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 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. 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; }

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 28 The Default Constructor main () { ModInt s1, s2; ModInt d[5]; ModInt s1.print(); ModInt s2.print(); ModInt d[3].print(); }Output:000

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 29 The Default Constructor If a class does not have a constructor, the system provides a 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. 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; }

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 30 Constructor Initializers A special syntax is used for initializing class members. 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. 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: The previous example can be recoded as: ModInt(int i = 0): v(i % modulus) {} ModInt(int i = 0): v(i % modulus) {} Notice that initialization replaces assignment. Notice that initialization replaces assignment. The individual members must be initializable as member-name (expression list). The individual members must be initializable as member-name (expression list).

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 31 Constructors as Conversions Constructors of a single parameter are used automatically for conversion unless declared with the keyword explicit.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.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).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).

March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 32 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”};

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