Unit II- 3. Protein Super Secondary Structures & Toplogy Diagrams
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member...
-
Upload
candace-dickerson -
Category
Documents
-
view
221 -
download
0
Transcript of Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member...
Structures and ClassesVersion 1.0
Topics
StructuresClassesWriting Structures & ClassesMember FunctionsClass Diagrams
Objectives
At the completion of this topic, students should be able to:
Correctly use structures in a C++ programCorrectly use classes in a C++ programDesign and use programmer written structures & classes in a C++ programExplain the difference between a structure, class and an objectExplain what properties and behaviors areExplain the difference between the structure or class interface and thestructure or class implementationWrite member functions for a structure and classCreate accurate class diagrams using UML
Structures
In C++, the idea of a class has its roots in data type calledstructure. Structures were defined in the C language. Astructure is simply a way of collecting a set of differentdata types together, and treating the collection as a unit.i.e. a user defined datatype.
Structure Definition
struct CDAccount{ double balance; double interestRate; int term;};
the struct keyword tellsthe compiler that what followsis a structure type definition.
this is the name of the structure type. It isalso known as the structure tag. It is any validC++ identifier.
the data members of thestructure are contained in
a set of curly braces.
the structure type definition mustend with a semicolon.
#include <iostream>using namespace std;
struct CDAccount{ double balance; double interestRate; int term;};
int main ( ){ CDAccount myAccount; . . .
}
The structure type definition is written outside of any function. The structure type definition must appear before it is used in the program.
Once the structure type is defined, it can be used anyplace in the program, just like any of the pre-defined data types, to create an element (object) of that data type.
#include <iostream>using std::cin;using std::cout;
struct CDAccount{ double balance; double interestRate; int term;};
int main ( ){ CDAccount myAccount; . . .
}
In this case, myAccount is variable whosedata type is CDAccount. The variable (object) myAccount actually consists of three pieces of data:
myAccount
#include <iostream>using std::cin;using std::cout;
struct CDAccount{ double balance; double interestRate; int term;};
int main ( ){ CDAccount myAccount; . . .
}
myAccount
these smaller pieces of data are calledmember variables. We specify themas follows:
* myAccount.balance * myAccount.interestRate * myAccount.term
myAccount.balance
myAccount.interestRate
myAccount.term
myAccount.balance
this is called the dot operator
#include <iostream>using std::cin;using std::cout;
struct CDAccount{ double balance; double interestRate; int term;};
int main ( ){ CDAccount myAccount; . . .
}
myAccount
member variables are used just like any other variable …
myAccount.balance = 35.50; cout << myAccount.balance; . . .
myAccount.balance
myAccount.interestRate
myAccount.term
myAccount
myAccount.balance
myAccount.interestRate
myAccount.term
yourAccount
yourAccount.balance
yourAccount.interestRate
yourAccount.term
You can create many objects (variables), using thesame structure type definition.
CDAccount yourAccount, myAccount;
You can initialize a structure with an initializer list(NOTE: ALL data members MUST be public!)
CDAccount billsAccount = {35.00, .08, 12};
struct Members
• Member– data/variables (properties)– functions/methods (behaviors)
struct Data //class Data{ private: int _idata; char _cdata; public: void DisplayData() { cout << _idata << “ “ << _cdata << endl; }
};
Writing Classes
Key Concept
An object often models things in the real world
Real world objects have properties or attributes
An object’s properties describe its“state of being”
color = pink
height = 6”
width = 10”
the bank isempty!
depending upon the application, some propertiesare more important than others
Amount ofmoney in bank
An object also has behaviors
behaviors define how you interact with the object
Put money in! Take money out!
Count the money in the bank
An Object’s Properties and Behaviors Work Together
Put money in! Take money out!
Count the money in the bank
Amount of Moneyin the Bank
this is called cohesion
A Class is a blueprint that a programuses when it creates an object.
A class reserves no space in memory
When an object is created (instantiated) from the classblueprint, memory is reserved to hold the
object’s properties.
An object is known as an instance of the class.
Each object has it’s own space for data.
Put money in! Take money out!
Count the money in the bank
moneyInBank
data member
member function member function
member function
EncapsulationCoinBank object
howMuchMoney( )
moneyInBank
calling method
we should not allow codeoutside of the object to reachin and change the data directly.Instead, we call functions in theobject to do it for us.
data is declared as private
functions are declared as public
Example
note how this variableis declared inside the class,but outside of anyfunction.
where a variable is declareddefines its scope. In this casethe variable moneyInBankis called instance data. When an object of this class is created thevariable is created in that object.The variable exists as long as theobject exists. Each CoinBank objecthas its own copy of moneyInBank.
note that thedata is declaredas private.
this is called aaccess modifier
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
double howMuchMoney ( ); void addMoney (double);
void takeMoney (double);};
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
double howMuchMoney ( ); void addMoney (double);
void takeMoney (double);};
declaration of a data member. Datais almost always private.
the class definition lies between theopening and closing curly braces
the keyword class tells the compilerthat this is a class definition.
the class name
the private keyword defines the declarationsthat follow to be private. Anything declared asprivate cannot be seen from outside the object.
the public keyword defines the declarationsthat follow to be public. Anything declared aspublic can be seen from outside the object.
the class definition ends in a semicolon.
these are the function prototypes forthe member functions of this class.The member functions define thebehavior of the class. Notice thatmember functions are usually public.
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
double howMuchMoney ( ); void addMoney (double);
void takeMoney (double);};
Member Functions
• When a member function is called, the flow of control in the program transfers to the first statement in the function.
• Each statement in the function is then executed, one by one.
• When the last statement in the function is executed, the flow of control returns to the point where the function was called.
double CoinBank::howMuchMoney( ){ return moneyInBank;} void CoinBank::addMoney( double dollars ){ moneyInBank = moneyInBank + dollars;}
void CoinBank::takeMoney ( double dollars ){ moneyInBank = moneyInBank - dollars;}
Writing Member Functions
return type
class name scope resolutionoperator
function name
Using the CoinBank Classint main( ){ // create a CoinBank object and call it myBank CoinBank myBank;
myBank.addMoney (10.00); myBank.takeMoney(2.00); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Bank contains $" << myBank.howMuchMoney( ); system(“PAUSE”); return 0;}
declare a CoinBank variable named myBank.This declaration is like any other, it createsa variable of the type named.
send messages to myBank to invokemember functions of the object.
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
double howMuchMoney ( ); void addMoney (double);
void takeMoney (double);};
Class definitionCoinBank myBank;
myBank
moneyInBank
this statement takes the CoinBank classdefinition and uses it to createthe object myBank. When creatingthe object, storage is allocated forthe member data that is defined forobjects of this class. In this case,storage is allocated for the doublevariable moneyInBank.
Abstract Data Types
Programmer defined classes are known as abstract data types.We call a data type an abstract data type when the details of howdata is stored and how the operations are implemented are notvisible to programmers who use the data type.
Defining a class so that these details are not known is known as information hiding, data abstraction, or encapsulation.
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
double howMuchMoney ( ); void addMoney (double);
void takeMoney (double);};
moneyInBank
EncapsulationData members are always private. Programmers who use this class have no idea how the data is actually declared.The developer of the class is free to change the way thatmember data is declared without affecting programs thatuse this class.
Functions outside of the class have no accessto data that is declared as private in the class,except by calling member functions of the class.
int main( ){ // create a CoinBank object and call it myBank CoinBank myBank;
myBank.addMoney (10.00); myBank.takeMoney(2.00); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Bank contains $" << myBank.moneyInBank; cin.get( ); return 0;}
For Example, this statement is illegal.The compiler will return a message tellingyou that moneyInBank is not accessible.
<< myBank.howMuchMoney( );
Correct this by using a member function toget the amount of money in the bank.
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
double howMuchMoney ( ); void addMoney (double);
void takeMoney (double);};
moneyInBank
EncapsulationWith few exceptions, functions are declared as publicso that they can be accessed from code outside of theclass. However, the details of how the function isimplemented should not be of concern to anyoneusing the class.
The function prototypes listed in the class definition give other programmers the interfaceto the class. Given these function prototypes, anda few comments about the functions, anotherprogrammer knows what each function does, whatparameters to pass to the function, and what eachreturns.
Accessor and Mutator Functions
Accessor functions provide a way of reading private member data.For example, the function howMuchMoney( ) is an accessor function.
Mutator functions provide a way of changing private member data.For example, the function addMoney( ) is a mutator function.
Classes and I/O
In general, it is a good idea to make your classes independentof the environment in which your program runs. One area wherestudents often want to build in system dependencies is doing I/O.
A good rule of thumb is to never write member functions in your classes that are not cohesive sucha as reading from stdin and writing to stdout. Such classes become dependent on the environment in which they run. It is impossible to move such a class to a different environment (for example from a DOS Console environment to a Windows environment) without making significant changes to the class.
Class Diagrams
During the design phase of a program, designers need a precise, standardlanguage for describing classes, and the relationships between classes.
A number of different approaches to such a modeling language weredeveloped in the late 1980’s and early 1990’s. These culminated in astandard called UML (Unified Modeling Language) in the late 1990s.
CoinBank
In UML, a class diagram is usedto describe a class in a very preciseway.
A class diagram is a rectangle.
At the top of the rectangle is theclass name. A line separates theclass name from the rest of thediagram.
CoinBank
- moneyInBank: doubleFollowing the class name we writethe data members of the class. Aline separates the data membersfrom the rest of the diagram.
access modifier:+ public- private
data member name
data type
CoinBank
- moneyInBank: double
+ CoinBank ( )+ addMoney (:double): void+ takeMoney ( :double): void+ howMuchMoney( ): double
Following the data members, wewrite the member functions.
access modifier + public - private
function name
functionparameters
return type
Diagram to CodeGiven a class diagram, it is relatively easy
to write down the class definition.
CoinBank
- moneyInBank: double
+ CoinBank ( )+ addMoney (:double): void+ takeMoney ( :double): void+ howMuchMoney( ): double
class CoinBank{ private: double moneyInBank; public: CoinBank ( );
void addMoney (double);
void takeMoney (double); double howMuchMoney ( );
};
CoinBank Code
Practice
Design a class that represents “Integer” objects.
What are the data members of the class?
Design a class that represents “Integer” objects.
Suppose we want functions to set the integer value in the object retrieve the integer value in the object retrieve the reciprocal of the value in the object
Create the class diagramInteger
Create the class definitionclass Integer{
Create the class implementation
Write a main( ) to test it#include “integer.h”#include <iostream>using namespace std;
int main ( ){
Design a class that represents “Student” objects.You could use an object of this class to hold thestudent information you print out at the beginningof each of your programming projects.
What are the data members of the class?
Design a class that represents “Student” objects.
Suppose we want functions to set the name, course, and section values in the object retrieve the name, course and section values from the object
Create the class diagramStudent
Create the class definitionclass Student{
Create the class implementation
Write a main( ) to test it#include “student.h”#include <iostream>using namespace std;
int main ( ){