1.05k likes | 1.19k Views
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
E N D
Structuring Your DataUsing 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 • The default constructor • References in the context of classes • The copy constructor and how it is implemented
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
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
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
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;
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++
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
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
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
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
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
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
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
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
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
EX8_01.CPP • Do the includes • Declare class CBox • 3 members • Length • Height • Breadth • Then we go into main( )
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
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
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
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.”
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
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
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
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( )
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.
Inline Functions • Can use the inline definition for regular functions as well • Just remember it’s best for short, simple functions
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!
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
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
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
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
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
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
Default Constructor • Let’s include a default constructor to our program
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
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
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
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
EX8_05.CPP • Includes are normal • Define class CBox • Data members • Constructor defined with default values • Values assigned to data members • Function Volume( ) included
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
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
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
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
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
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
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
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
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
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