1 Chapter 7 Defining Your Own Data Types. 2 What Is a struct ?  A structure is a user-defined type You define it using the keyword struct so it is often.

Slides:



Advertisements
Similar presentations
Kernighan/Ritchie: Kelley/Pohl:
Advertisements

Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
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];
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 10.
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Classes: A Deeper Look Systems Programming.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
Structuring Your Data Using Classes Chapter 8. What We’ll Cover in Chapter 8 Classes and how they are used The basic components of a class How a class.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
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.
1 Chapter 8 Destructor & Operator Overloading. 2 Destructor  A destructor is a function that is called when an object is no longer required. A constructor.
Learners Support Publications Classes and Objects.
Overview of Previous Lesson(s) Over View .NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows.  It.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
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.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
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.
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:
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
論語 先進第十一 暮春者,春服既成 冠者五六人,童子六七人 浴乎沂,風乎舞雩,詠而歸 ㄧˊ 〔~河〕水名,源出中國山東省,至江蘇省入海。
Pointers and References
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
Pointers, Dynamic Data, and Reference Types
Classes and Objects.
7 Arrays.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
黃鶴樓 ~ 崔顥 昔人已乘黃鶴去, 此地空餘黃鶴樓。 黃鶴一去不復返, 白雲千載空悠悠。 晴川歷歷漢陽樹, 芳草萋萋鸚鵡洲。
Pointers, Dynamic Data, and Reference Types
Video: The Sound of Raining
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

1 Chapter 7 Defining Your Own Data Types

2 What Is a struct ?  A structure is a user-defined type You define it using the keyword struct so it is often referred as a struct.  Compared to the data types we have seen, some real world objects must be described by several items: Time – hh:mm:ss Point – (x,y) Circle – (x, y, r)

3 Defining a struct struct POINT { float x; float y; };  Note: This doesn ’ t define any variables.  It only creates a new type. Each line defining an element in the struct is terminated by a semicolon A semicolon also appears after the closing brace.

4 Creating Variables of Type POINT POINT p1, p2;  If you also want to initializing a struct: POINT p1 = { 1.0, 2.0 };

5 Accessing the Members of a struct  Member selection operator (.) p1.x = 3.0; p2.y += 2.0;

6 Figure 7-1 on P.334

7 Ex7_01.cpp  Hut2 = Hut1; Hut2.Left = Hut1.Left; Hut2.Top = Hut1.Top; Hut2.Right = Hut1.Right; Hut2.Bottom = Hut1.Bottom;  Putting the definition of the struct at global scope allows you to declare a variable of type RECTANGLE anywhere in the.cpp file.  Pass by reference

8 Intellisense Assistance with Structures

9 The struct RECT  There is a pre-defined structure RECT in the header file windows.h, because rectangles are heavily used in Windows programs. struct RECT { int left;// Top left point int top;// coordinate pair int right;// Bottom right point int bottom;// coordinate pair };

10 Using Pointers with a struct  RECT* pRect = NULL; Define a pointer to RECT  pRect = &aRect; Set pointer to the address of aRect

11 A struct can contain a pointer struct ListElement { RECT aRect;// RECT member of structure ListElement* pNext;// Pointer to a list element };

12 Linked List

13 Accessing Structure Members through a Pointer  RECT aRect = { 0, 0, 100, 100};  RECT* pRect = &aRect;  (*pRect).Top += 10; The parenthesis to de-reference the pointer are necessary (P.77)  pRect->Top += 10; Indirect member selection operator

14 Exercise  Define a struct Sample that contains two integer data items.  Write a program which declares two object of type Sample, called a and b.  Set values for the data items that belong to a, and then check that you can copy the values into b by simple assignment.

15 Dynamic Memory Allocation (P.194)  Sometimes depending on the input data, you may allocate different amount of space for storing different types of variables at execution time int n = 0; cout << "Input the size of the vector - "; cin >> n; int vector[n]; error C2057: expected constant expression

16 Why Use Pointers? (P.176)  Use pointer notation to operate on data stored in an array  Allocate space for variables dynamically.  Enable access within a function to arrays, that are defined outside the function

17 Free Store (Heap)  To hold a string entered by the user, there is no way you can know in advance how large this string could be.  Free Store - When your program is executed, there is unused memory in your computer.  You can dynamically allocate space within the free store for a new variable.

18 The new Operator  Request memory for a double variable, and return the address of the space double* pvalue = NULL; pvalue = new double;  Initialize a variable created by new pvalue = new double(9999.0);  Use this pointer to reference the variable (indirection operator) *pvalue = ;

19 The delete Operator  When you no longer need the (dynamically allocated) variable, you can free up the memory space. delete pvalue;  Release memory pointed to by pvalue pvalue = 0;  Reset the pointer to 0  After you release the space, the memory can be used to store a different variable later.

20 Allocating Memory Dynamically for Arrays  Allocate a string of twenty characters char* pstr; pstr = new char[20]; delete [] pstr;  Note the use of square brackets to indicate that you are deleting an array. pstr = 0;  Set pointer to null

21 Dynamic Allocation of Multidimensional Arrays  Allocate memory for a 3x4 array double (*pbeans)[4]; pbeans = new double [3][4];  Allocate memory for a 5x10x10 array double (*pBigArray)[10][10]; pBigArray = new double [5][10][10];  You always use only one pair of square brackets following the delete operator, regardless of the dimensionality of the array. delete [] pBigArray ;

22 HWHW: Linked List

23 Final Exam  Date: January 13 (Wednesday)  Time: 14:10-17:00  Place: TC-113  Scope: Chapter 2-7 of Ivor Horton's Beginning Visual C CLR programming is excluded.  Open book  Turn off computer & mobile phone

24 Objects  A struct allows you to define a variable representing a composite of several fundamental type variables.  An object provides more advanced features: Encapsulation Polymorphism Inheritance

25 Class  A class is a (user-defined) data type in C++. It can contain data elements of basic types in C++, or of other user-defined types. Just like a struct. The keyword struct and class are almost identical in C++. Let ’ s see an example.

26 Example: class CBox class CBox { public: double m_Length; double m_Width; double m_Height; };  When you define CBox as a class, you essentially define a new data type. The variables m_Length, m_Width, m_Height which you define are called data members of the class. MFC adopts the convention of using the prefix C for all class names. MFC also prefixes data members of classes with m_.

27 What Does Class Offer More?  A class also can contain functions. So, a class combines both the definition of the elementary data, and the methods of manipulating these data.  In this book, we call the data and functions within a class data members member functions

28 Defining a Class class CBox { public: double m_Length; double m_Width; double m_Height; };

29 Accessing Control in a Class  There are public and private data members in a class. Public members can be accessed anywhere. Private members can only be accessed by member functions of a class. See Figure 7-6 on P.351.

30 Figure 7-6

31 Declaring Objects of a Class CBox box1; CBox box2;

32 Accessing the Data Members of a Class  box2.m_Height = 18.0; direct member selection operator  Ex7_02.cpp The definition of the class appears outside of the function main(), so it has global scope. You can see the class showing up in the Class View tab.

33 Member Functions of a Class  A member function of a class is a function that its definition or its prototype is within the class definition. It operates on any object of the class It has access to all the members of a class, public or private.  Ex7_03.cpp on P.339 box2.Volume() There ’ s no need to qualify the names of the class members when you accessing them in member functions. The memory occupied by member functions isn ’ t counted by the sizeof operator.

34 Positioning a Member Function Definition (1)  For better readability, you may put the definition of a member function outside the class definition, but only put the prototype inside the class. class CBOX { public: double m_Length; double m_Width; double m_Height; double Volume(void); };

35 Positioning a Member Function Definition (2)  Now because you put the function definition outside the class, you must tell the compiler that this function belongs to the class CBox. scope resolution operator ( :: ) // Function to calculate the volume of a box double CBox::Volume() { return m_Length*m_Width*m_Height; }

36 HW3  Modify Ex7_01.cpp, so that the yard, the pool, and two huts belong to the type CIRCLE instead of RECTANGLE.

37 Class Constructors  A class constructor is a special function which is invoked when a new object of the class is created. You may use the constructor to initialize an object conveniently.  It always has the same name as the class. The constructor for class CBox is also named CBox().  It has no return type. You must not even write it as void.

38 Ex7_04.cpp on P.343  Constructor Definition CBox(double lv, double bv, double hv) { cout << endl << “Constructor called.”; m_Length = lv; m_Width = bv; m_Height = hv; }  Object initialization CBox box1(78.0, 24.0, 18.0); CBox cigarBox(8.0, 5.0, 1.0);  Observe that the string “ Constructor called ” was printed out twice in the output.

39 The Default Constructor  Try modifying Ex7_04.cpp by adding the following line: CBox box2;// no initializing values  When you compile this version of the program, you get the error message: error C2512: ‘ CBox ’ no appropriate default constructor available  Q: Compare with Ex7_02.cpp. Why the same line “ CBox box2 ” introduced no troubles at that time?

40 The Default Constructor (2)  In Ex7_02.cpp, you did not declare any constructor, so the compiler generated a default no-argument constructor for you.  Now, since you supplied a constructor CBox(), the compiler assumes that you will take care of everything well.  You can define a default constructor which actually does nothing: CBox() {}

41 Ex7_05.cpp  The default constructor only shows a message.  See how the three objects are instantiated. CBox box1(78.0, 24.0, 18.0); CBox box2; CBox cigarBox(8.0, 5.0, 1.0);  Pay attention to the 6 lines of output messages.

42 HW5  Modify Ex7_06.cpp so that the definition of the Default Constructor is placed outside the body of the class definition.

43 Assigning Default Parameter Values  Recall that we may assign default values for function parameters (P.278).  Put the default values for the parameters in the function header. int do_it(long arg1=10, long arg2=20);  You can also do this for class member functions, including constructors.  Ex7_06.cpp on P.348

44 Using an Initialization List in a Constructor  Instead of using explicit assignment, you could use a different technique: initialization list: // Constructor definition using an initialisation list CBox(double lv = 1.0, double bv = 1.0, double hv = 1.0): m_Length(lv), m_Width(bv), m_Height(hv) { cout << endl << "Constructor called."; }

45 Private Members of a Class

46 Ex7_07.cpp on P.351  The definition of the CBox class now has two sections. public section  the constructor CBox()  the member function Volume() private section  data members m_Length, m_Width, m_Height

47 The Copy Constructor  See the output of Ex7_09.cpp. The default constructor is only called once.  How was box2 created?  A copy constructor creates an object of a class by initializing it with an existing object of the same class.  Let us wait until the end of this chapter to see how to implement a copy constructor.

48 Arrays of Objects of a Class  Ex7_11.cpp on P.363  CBox boxes[5];  CBox cigar(8.0, 5.0, 1.0);

49 Static Data Member of a Class  When you declare data members of a class to be static, the static data members are defined only once and are shared between all objects of the class.  For example, we can implement a “ counter ” in this way.

50 How do you initialize the static data member?  You cannot initialize the static data member in the class definition The class definition is simply a blueprint for objects. No assignment statements are allowed.  You don ’ t want to initialize it in a constructor Otherwise the value will be destroyed whenever a new object is created.

51 Counting Instances  Write an initialization statement of the static data member outside of the class definition: int CBox::objectCount = 0;  Ex7_12.cpp on P.366 static int objectCount; Increment the count in constructors. Initialize the count before main().  The static data members exist even though there is no object of the class at all.

52 Static Member Functions of a Class  The static member functions exist, even if no objects of the class exist.  A static function can be called in relation to a particular object: aBox.Afunction(10);  or with the class name: CBox::Afunction(10);

53 Pointers to Class Objects  Declare a pointer to CBox CBox* pBox = 0;  Store address of object cigar in pBox pBox = &cigar;  Call the function Volume() cout Volume(); cout << (*pBox).Volume();  In Ex7_10.cpp, the pointer this refer to the current object (P.358).

54 References to Class Objects  Remember, a reference acts as an alias for the object.  Define reference to object cigar CBox& rcigar = cigar;  Output volume of cigar cout << rcigar.Volume();

55 Implementing a Copy Constructor  Consider writing the prototype of a Copy Constructor like this: CBox(CBox initB);  What happens when this constructor is called? CBox myBox = cigar;  This generates a call of the copy constructor as follows: CBox::CBox(cigar);  This seems to be no problem, until you realize that the argument is passed by value. You end up with an infinite number of calls to the copy constructor.

56 Implementing a Copy Constructor (2)  Use a reference parameter CBox::CBox(const CBox& initB) { m_Length = initB.m_Length; m_Width = initB.m_Width; m_Height = initB.m_Height; }  If a parameter to a function is a reference, no copying of the argument occurs when the function is called.  Declare it as a const reference parameter to protect it from being modified from within the function.