1 / 105

Structuring Your Data Using Classes

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 is declared Creating and using objects of a class Controlling access to members of a class Constructors and how to create them

gittel
Download Presentation

Structuring Your Data Using Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Structuring Your DataUsing Classes Chapter 8

  2. What We’ll Cover in Chapter 8 • Classes and how they are used • The basic components of a class • How a class is declared • Creating and using objects of a class • Controlling access to members of a class • Constructors and how to create them • The default constructor • References in the context of classes • The copy constructor and how it is implemented

  3. Data Types, ObjectsClasses and Instances • Basic variables don’t describe objects • Can’t describe a box in terms of int • Can make a struct of type Box • Length • Breadth • Height • Can create, manipulate, destroy as many boxes as you wish

  4. Data Types, ObjectsClasses and Instances • Structs in C different from structs in C++ • Structs in C++ almost identical to classes • Except for control to access to its members • More on that later • See class definition of a box on p. 280 • Data members • m_Length, m_Breadth, m_Height • m_ indicates it’s a data member

  5. Data Types, ObjectsClasses and Instances • Called the class CBox • The C indicates that it is a class • Always stick to naming conventions • Helps you in debugging • Helps those who come after you, too • public keyword • Clue to difference between structures and classes

  6. Keyword public • Allows access to these members from outside the class • Just like members of a struct • Members of structs public by default • In classes, can restrict access to members • Can declare an instance of class CBox • An instance is one specific item of the class • CBox bigBox;

  7. First Class • Objects and instances are same thing • Notion of class invented by an Englishman • Thought people would be happy knowing their place and staying within it • C++ invented by Bjarne Stroustrup • Danish • Learned class concepts while at Cambridge University in England • Appropriated the idea successfully for C++

  8. First Class • Very similar to English class system • Classes have • precise role • permitted set of actions • Different from English system • Somewhat socialist • Focuses on working classes • Working classes live on backs of classes that do nothing

  9. Operations on Classes • Can create data types to describe whatever you want • Can also define operations that act between your objects • See p. 281 • Very powerful concept • Not programming in terms of computers • Programming in terms of problem-related objects

  10. Terminology • Class • User-defined data type • Object-oriented programming • Programming style based on defining your own data types • Instantiation • Creating an instance of a class • Object • An instance of a particular class type • Encapsulation • Packaging data with the related functions

  11. Understanding Classes • A class • Contains data members to define the object • Contains functions that operate on data • Data elements • Single data elements • Arrays • Pointers • Arrays of pointers (of any kind) • Objects of other classes

  12. Defining a Class • Defined very similarly to a struct • Exception: public • All values relative to object are defined as members of the class • All member names local to the class • Can use same names elsewhere

  13. Access Control In a Class • Keyword public • Class members accessible anywhere within scope of class object • Keyword private • Class members accessible only within the class itself • More on this later • Difference between struct and class • Struct is public by default; class, private

  14. Declaring Objects of a Class • Declaration of objects just like other declarations • CBox box1; • CBox box2; • Two instances of type CBox • Can have different values • Two different boxes have two different sizes • Two different volumes

  15. Declaring Objects of a Class • See chart p. 284 • Data members of each object • Not initialized to anything • Will need to access them to do so • Othewise will contain junk values

  16. Accessing Data Membersof a Class • Accessed same way as members of a struct • Using direct member selection operator • box2.m_Height = 18.0; • Sets value of height of box 2 to 18.0 (inches) • Let’s look at an example on p. 284

  17. EX8_01.CPP • Do the includes • Declare class CBox • 3 members • Length • Height • Breadth • Then we go into main( )

  18. EX8_01.CPP • Declare two instances of type CBox • Declare and initialize variable boxVolume • Type double • Initial value 0.0 • Set values for first box • Set values for second box • Can use formulas and values from first box

  19. EX8_01.CPP • Calculate boxVolume for first box • Using standard math for volume • Output the volume for box 1 • Calculate sides sum for second box • Using standard math there, too • Output the size of variable type CBox • Using sizeof operator • Just like other data types

  20. EX8_01.CPP • Can see the output of this program • Page 286 • Notice that the data members are of type public • Can be accessed from outside the class • Class was declared globally so members accessible from anywhere in the program

  21. Member Functions of a Class • Member functions in a class can access members declared as private • In the words of Ted Koppel, • “Let’s take a look.”

  22. EX8_02.CPP • Same as example 01 • We add a member function • Includes done • Declare class box with its members • Declare member functionf • double Volume( ); • Returns value calculated by standard math • Same as in main( ) in example 01

  23. EX8_02.CPP • In main( ), everything similar to before • boxVolume = box1.Volume( ); • Assigns to boxVolume the value returned by member function Volume in instance box1 • Output statement calls box2.Volume( ) • Will get completely different value from that assigned to boxVolume • Two different boxes; two different volumes

  24. EX8_02.CPP • Names of class members automatically refer to current object • When box1.Volume( ) is run • Members m_Length, m_Height, m_Breadth all refer to those values for box1 • Output from example 02 is on p. 288 • Note that size of CBox doesn’t change with added function • Functions don’t change size of a class

  25. Positioning a MemberFunction Definition • Can place function declaration outside the class • Must include function prototype within the class • When function definition is coded, must tell compiler what class function is for • Use the double colon ( :: ) to do this • double CBox::Volume( )

  26. Inline Functions • Compiler expands these in the code • In place of the call to the function • Compiler ensures that problems of variable names and scope are avoided • Can define function as inline • inline double CBox::Volume( ) • Avoids overhead of calling the function • Passing variables, etc.

  27. Inline Functions • Can use the inline definition for regular functions as well • Just remember it’s best for short, simple functions

  28. Class Constructors • In EX8_02.CPP, manually initialized all members of box1 and box2 • Unsatisfactory because • Easy to overlook a data member • Lots of code needed for complex classes • Especially if several instances need initialization • Can’t access private members of the class • Must be initialized from within the class • Solution: Class Constructors!

  29. What is a Constructor? • A special function in a class • Called when a new object of the class is declared • Initializes objects as they are created • Ensures that data members hold valid values • Constructor name same as class name • CBox( ) is constructor for class CBox

  30. What is a Constructor? • Constructor has no return type • Not even void • Must not write a return type • Assigns initial values only • No return type necessary or permitted

  31. EX8_03.CPP • Class definition changed to include function CBox( ) • Function CBox( ) takes three parameters • One for each data member • Assigns three parameters to data members • In main( ), instantiation includes initial values, in sequence • box1 and cigarBox both initialized

  32. EX8_03.CPP • Output calls cigarBox.Volume( ) • Works because cigarBox is of type CBox • Returns value calculated from initial values • Output shows box1 volume same as before • cigarBox volume also works

  33. The Default Constructor • If we declare instance of CBox without giving initial values • CBox box2; • Error message will result • Need default constructor in case initial values not given • Worked before because we had not supplied a constructor

  34. The Default Constructor • When constructor provided, all declarations should match its input requirements • Unless we supply default constructor • Should always supply default constructor • In simplest terms, default constructor has no parameters, no content • It’s just there

  35. Default Constructor • Let’s include a default constructor to our program

  36. EX8_04.CPP • Inside the class, data members declared • Constructor function is there • Default constructor then provided • It doesn’t do anything but say it was called • But it allows for declarations without values • In main( ), box2 declared without values • Then box2 defined relative to box1

  37. EX8_04.CPP • At that point, box2.Volume( ) will work • Output on p. 294 shows where constructor is called • Then default constructor called • Box2 declared without initial values • All volume calls return valid information • Rest of program still working fine • Can overload constructors just like functions

  38. Assigning Default Valuesin a Constructor • Makes a little more sense than an empty function • Can declare default values same as with functions • In function header • In function prototype if function not within class • The changes listed at bottom of p. 294 • Will result in error messages

  39. Assigning Default Valuesin a Constructor • Why? Because either constructor can now be called for declaration of box2 • Compiler won’t know which one to use • Solution: delete the default constructor • Means that instances without values are automatically assigned default values • Preferable to uninitialized data members

  40. EX8_05.CPP • Includes are normal • Define class CBox • Data members • Constructor defined with default values • Values assigned to data members • Function Volume( ) included

  41. EX8_05.CPP • In main( ) • Instantiate box2 of type CBox • Output statement uses call to box2.Volume( ) • End program • Output demonstrates that values are initialized using the default values • m_Height, m_Length, m_Breadth all = 1

  42. A Side Trip – Stacks • Just like like the stack of plates at Ryan’s • Last one on is first one off • Can be used for data management • When most recent data is needed • Often used in memory management in programming • Functions that call other functions are placed on the stack while new function runs

  43. A Side Trip – Stacks • New function runs, then exits • (disappears) • Pull calling function from the stack • Continues execution • Works when function calls another function which then calls another function

  44. Hands-On Project • Using EX8_05.CPP as a starting point • Replace the class for a box with a class for a cylinder • Have two values (radius & length) • Make the necessary changes to the function Volume • Make it return the volume of the cylinder π r2* length = volume

  45. Using an Initialization ListIn a Constructor • Alternative to initializing members individually in a class constructor • Initialization list • See p. 296 • Initialization list goes after the function header • Separated by a colon ( : ) • Replaces individual assignment statements

  46. Using an Initialization ListIn a Constructor • This technique very important • Some data members of a class can only be initialized this way. • We will see this later on

  47. Private Members of a Class • Need to protect data members • Should only be modified from specific places • Data members should only be accessible (for change) by member functions • Normal functions (not member functions) cannot have access to private members • See diagram p. 297

  48. Private Members of a Class • Separation of the implementation of a class from its interface • Can have public member functions which can return values from private members • Allows outside access to the values but not access to changing them • Can modify implementation without changing the interface to rest of program

  49. EX8_06.CPP • Includes, blah, blah, blah • Class CBox is declared • Constructor is called as public • Has to be • Called at instantiation • Function Volume is public • Called from outside the class • Doesn’t change data values

  50. EX8_06.CPP • Data members now listed as private • Cannot be assigned values outside class • Cannot be viewed from outside the class • In main, declare two instances of CBox • One with initial values, one without • Call match.Volume( ) • Is okay: Volume is a public function in CBox • Two commented lines

More Related