Step1 - CSE 335 Step 1: Introduction to Eclipse and some...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 8
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CSE 335 Step 1: Introduction to Eclipse and some Object-Oriented Programming This is CSE 335 Step 1 The bulk of this step assignment is tutorial There Mo programming tasks at the end of the step assignment. The programming elements of this assignment are due Thursday, September 9, 2010 at 11 55pm. This is a fairly long tutorialthat Introduces a lot of information about using Eclipse and object oriented programming Be sure you don't wait till the last minute to start this step assignment This assignment is meant to be done in a computer lab or remotely on a department machine. The machines biack.cse.msu.edu, adriatic.cse.msu.edu, pacmc.cse.msu.edu, and arctic.cse.msu.edu are configured for this course, as are all machines in the labs. ityou want to work on your own machine, be sure you are using a Linux machine and be sure your program; WIII compile on one ofthese machines. See the Software Requirements page for detaib. We will be LBII‘IQ an integrated development environment (IDE) in this course called Eclipse Eclipse combines editing, compiling, and debugging into a single, uniform environment Starting Eclipse Start eclipse You can start eclipse from the command line using this command: eclipse & You should see this dialog box: Select a workspace Eclipse stores your projects in a folder called a workspace. Choose a workspace folder to use forthis session. Workspace: I user/chowenlworkspace fl Erowse... A workspace is an area where projects are stored. | suggest for Step 1 that you usethe default workspace, which WIII be the workspace directory on your machine under your home account [obinousiy not cbowen). I would not check the “Use this asthe default" option, Since we may Lse other workspaces later. Just hit 0k Initial Configuration Perform all ofthe steps in the page Configuring Eclipse. These steps need only be done one time, not every time you open Eclipse. Your First Project We' re going to create a first project. Select FiIeINethroject. In the dialog box, expand CIC++ and select C++ Project: “mm-«t — Ira-i Select a wizard -<> ‘7‘; q” in" ' l> BGeneral IV E CIC++ E, c Project c++ Project l> BCVS D Bjava D BExamples Hit Next In the nextdialog box, set the project name to Step1 and select “Hello World C++ Project“: c++ Project -0 Create C++ project of selected type r Project name: [Stepil Use default location Location: lluser/cbowen/workspace/Step1 Btowse I Choose file system: default Project type: Toolcl'iains: Hello Wortd C++ Project l TestProjectW'rthExtraRages 0 TestWidgetsLabei b B Shared Library b {3 Static Library 0 Executable tXL CIC++l 0 Static Libraryth CIC++J 0 Shared Libmry (XL CIC++) 0 Executable tXL UPC) 0 Static LiprarthL UPC) 0 Shared Library (XL UPC) p B Makefile project Youl options may be slightly ditTelerrt, but you should have the Hello World C++ Project option available, Hit Finish Theleale additional options available it you hit Next, but we're going to use the defaults for all of them You should see a dialog box like this. This kind of project is associated with the CIC++ perspective Do you want to ® open this perspective now? | m us-s_cs_ __.. 4__:_:4_ Click Yes A perspective is the leer interface for Eclipse it changes depending on the language you are working in Eclipse can be Lead With Java, C, CH, Python, and many other languages, Now, you should have an Eclipse screen On the lett side is the Project Explorer This lists all projects in your workspace You should see Step1 in it Click the arrow to the tell of Step1 to expand it Then expand all: You should see Sleptcpp Double click on it to bring Step1 ,cpp up in the editor Eile Edi: source Refacsor flavigate Search Project gun flindow flelp Nome» eaeifie w [(2. Project Explorer £5\ ‘=' E i ‘ a ¢a V i H Name mm M a v @Stepl // Author .. . . 1/ Version . I) ” Bmanes // Copyright : Your copyright notice D BDebug // Description : Hello World in CH. Ami-style P at! Includes cout << '! ! Hello World! !! << endl; H prints !!!Hello World!!! return 9; To compile your project, do Project/Build Project. Since we have set Burld Automatically, it should already be built. Interestingly enough, though we selected BSD style, it generated K&R Style. Please fix that by moving the mace alter main[) tolhe next line. Running A Project Select Run/Run AsJLocal ClC++ Application, Your program should run and !!!Hello World!!! should display in the Console Window at the bottom of Eclipse Problemsl @ 1ask5 l E Console SSK at: Properties! ill unintu- Cmai ll Local CICH Application does not appear under the Run As menu do the lollowirrg: In older to run our project, we need to create a launch configuration. 1, Select Project/Properties to bring up the project properties dialog box 2, 0n the lett side, select Run/Debug Settings, RuMDehug Selfian Project References Refactoring History Weary Settings Task Repository Task Tags validation Wiki'lbxt 3. 0n the light side, Click the New button. 4, In the Configuration Type dialog box, select C/CH- Application and hit 0k a m mam-mm fielect the type of configuration to create: E crc++ Application ® 5. In Edit Configuration, hit 0k Finally, hit 0k on the Properlia dialog box. Note the different tabs The Console is a terminal that is attached to your program as it runs This is where the output goes T isiust gett something running Thfie dialog boxa let you set rigs like argLInems passed to the program or diflerem ways to run the program From now on you should be able to run your program byJust doing RurilRun Our First Class We're going to create a simple application that manages a farm To do this, we‘re going to create several ditterence classes The first class we‘ll create is a class that will describe our farm. ' Create a new C++ class. Q I ‘ flource Folder: Stepllsrc I Browse... D Namespace: ‘ Browse . glass Name: CFann Ease 035535: Name l Access l Virtual l “B Down i im use Default Header lCFarniJi l Brgwse . Sourcg' [CFarmLpp ‘ Brgwsa © This has created two new files CFarm.cpp and CFarm.h. You should see then in Project Explorer. They should have also come up automatically in the editor. A constructor and destructor tor the class will be created automatically as well. were going to instantiate one object oltype CFarm in our program. Go to Step1 cm: and change the main lunctionto: return 0 ; In order to use the CFarm class, we need to include the header file CFarmh. Add this line to the beginning of Step1.cpp: #include "Ci'arrn. h" Be sure this runs. it should output this Instantiating Farm All Done A Simple User Interface We‘re gomg to create a very srmple user Interface In thrs program Change mam thrs trme to' l int main“ bool done = false; while ( Edone) cout << "Instantiating Pam" << endl; CFarm farm; // This loops continuously until we are done l H Output user instructions caut << endl; U Get option from the user int option; cin >> option; // Handle invalid if(!cin) { i nput option = 1000; cin.clear(); cin.ignore() F // Discard bad input } // Handle the possible user options switch (option) ‘ case 1: cout << "Adding cow" << endl; break; a a a a 3;“ break ; default: cout << "Invalid option" << endl; break: return 0 ; You should take a moment and read through the code. Be sure you knowwhat eVery line does You may not he as famrlrarwrth the error check on cin lt srmply ensures rnvalid input wrll get the defauh ODUOH A Cow Class Now we‘re going to create a class to store cows. Do FIIe/New/Class. Set the class name to CCow. Now, we need membervarraples to descrrpe our cow We‘ll use name, type, and ml/kllmdUCNO/l Name IS a strth that re the name ofthe cow Type can be pull, From now on, l‘rnjusl going to say “create a class named 000w" and you‘re on your own ,, x..- and... e- m... enum Type (Bull, BeefCow, MilkCow}; In your program. Now add these prwate mempervarraoles' private: // The cow's name std: :string mName; // The type of code: Bull, BeefCow, or MilkCow Type mType; // The milk production for a cow in gallons per day double mlfllkProductiDn: Note the first letter m to rhdrcate a member varraples, the use of Camel Case as perthe class handbook, and a comment desmtnng everyvanaple and gwrng the values ofthe varraples Be sure to add thrs line to the peglnnrng ofCCowh: using namespace std ; We commonly referto these data rtems as propemes ofthe class. Smce we‘re going to need to access them ou'tsrde the class, we need access functrons, commonly called genera and setters Add these puplrcfunctrons to CCowh' // Access functions for the cow name void SetName(const std: :string an) (mName = n;} std: :string GetN'ameO (return mNamerl // Access functions for the cow type, which I/ can be Bull, BeefCow, or MilkCow void SetType(Type t) lmType = t;l Type GetTypeO (return mTyperl // Access functions for the mill: production I/ in gallons per day void SetMilkPraduction(double m) {mMillcProducticn = m;} double GetMilkProductionO {return mMilkProduction:l When thrs functron rs called, we wrll prompt the user for the Informatlon that descnpes a cow. We‘ll create an empty functron for now. Select Source/Implement Method. lt wrll ask you to save changes, so do that. When the refactormg dralog box comes up, be sure OptarnCowlnformatIon IS checked and select Frmsh: aRefadoring ' 7 ‘ i Implement Method Select Methods to implement: @ void obtainCowrnfonnationU: case 1: ( cout << "Adding cow" << endl; CCaw *oaw = new CanU: caw-WbtainCowInformation() ; ) break; Add this line to the headers for Stepi.cpp to include the headerfor our new class: #include "CCole" The code in the case above is bound to raise some questions First, why the braces in the case? l'm defining a local variable cow of type CCow ‘. You can‘tdefine local variables in the case statement unless you put the contents into a block Try removtng the braces and see what happens. So, what does CCow ‘cow = new CCowO, do? “*“ means pointer The variable cow in this caSe is oftype CCow ‘, meaning a potnterto a CCow object. The variable contains an address in memory for the Obielft. The operation "new CCowD," allocated a new object of type CCow In memory and returns a pointer to the object So, we‘ve created a cow object in memory and the variable cow points to that OBJECT The problem With this is that cow object is a local variable it Will be destroyed when we exit the procedure itwas created tn We‘re going to keep our cows, so We need to allocate them tn the heap, the memory available foryour program to uSe that stays around while your program runs until you delete it When ya“ aHuca‘e somemmg w‘m new‘ you nee“ w free we memgww‘m defers. at same palm Tm program does notdo that, so it has a memory leak, meaning the memory for cow is allocated, but never freed. Memory leaks are reain bad, since they use up memoryfor something that is no longer needed Since cow ts a pointer to an object, not the obyem itSetf, we uSe 7: to access the member function This program is tn Violation of Commandment 5, i will clean up alter myset‘f But, that‘s okay, because we‘re not done, yet. Remember " " for objects, “7>“ for pointers to objects So, cow—>ObtainCowlnformation(); runs the procedure DbtainCowlnformationo Debugging I want to know that this is working before i proceed. Always try to check everything you possibly can as you are writing code We‘re going to Set a breakpoint at the caSe statement and run our program in the debugger. First, we set a breakpoint at the beginning ofthe code in the caSe statement To the left ofthe statement you‘ll see an orange Vertical bar. Doubleeclick on that bar to set a breakpoint. You can doubleeclick again to clear it. You‘ll see a symbol to indicate a breakpoint has been set Here‘s what it should look like: switchwption) Double-click Here dream; lfyou haVe trouble getting the breakpoint to set, trydoing Proyert/Build Proyemfirst Sometimes ttdoes not know the correm code location for the breakpoint, yet Choose the menu option Run/Debug As/Local CIC++ Application (in the future you'll be able to Just do Run/Debug) It may take a bit oftime to launch the debugger, particularly forthe firsttime. Look at the status in the lower right corner oftne wtndow. You'll get this dialog box 5 Confirm Perspective Switch Ci t El /~\ This kind at launch is configured to open the Debug perspective when it suspends. This Debug perspective is designed to support application debugging. It incorporates views for displaying the debug stack, variables and breakpoint management. no um. want rn nnan rhie norenarriun nnuu? A DEfSpEflll/E in Eclipse is what the user interface looks like Since Debugging is a different task, is has a different perspective Click Yes here You'll see the user interface drastically change. The debuggerwtll automatically break at the first line of main. You should see that by an arrow next to the line and the line highlighted: ")4", Ilurilczlauhc )Lu. :int mainl) { 9 cnut << "Instantiating Farris“ << endl: CFarrit farm,- Jt' *n . i In the Debug bar, click the Resume button it looks like this it: Debug 23 FL The console should now askyou to select an option. Enter t and return. The program should now now broken at your breakpoint Good, we knowthe menu works okay CBS! 1; 9.; taut: << "Adding cow" << endl; (Cow 'cow = new ccowti; cow->0btaincow1nformationl ); } break; There are two buttons we're gotng to use a lot: step into and step over. Step into wtll execute one statement and Will step into any called function. Step overwtll execute one statement, included the called function. You‘ll use Step over most ofthe time and Step into when you wantto know what a function is doing Here‘s what the buttons look like: ti; Debug 23 Step Into * if? [9 5:. ‘3” wanted to be sure was happening You can press step over one time to return Finally, press Resume and use the 99 option to exit your program. You probably noticed that EclipSe leaves you in the Debug perspemive To change back to the CIC++ pelSpEfllVE, selectWindow/Dpen Perspemive/C/C++ Obtai nCowl nformation At last, we‘re going to create the function to obtain the cow Information Make this the body of CCow:ObtainCowlnlormation: cout << endl,‘ cout << "Input information about the cow" << endl; // Obtain the name. This is easy, since it‘s just a // wettest "angle errors. hool valid = false; while ( !valid) l cout << "1: Bull" << endl,‘ cout << "2: Beef Cow" << endl; cout << "3: Mill: Cow” << endl; cout << "Enter selection and return: "; int option; cin >> option; i£(!cin) ( // We have an error. Clear the input and try again cin. clearO i cin.ignore() ; continue; } switch (option) { case 1: mTy'pe = BeefCow; valid = true; break; case 3: mTy-pe = MilkCow; valid = true; break; ) l if(mTy-pe = MilkCow) l valid = false; while ( !valid) { cout << "Entire milk production in gallons per day: ",- Gin >> mMilkProd'uctian? if(cin) else l [I If not a milk now, we have no milk production mMilkProduction = O,- You Will need to add #incliide <iostream> to use cin and the ios1ream operators Again, read dyer all of this code carefully, Note the use of loops to ensure Valid data input Just to be sure, [hi iswhat the major files for this step should look like at this point. CFarm Now let‘s create the farm inventory, We created a cow Now we want to add it to the farm, Go to CFarmh and add this member Variable, Private : #include <list> #include " CCow . h" We‘re using a linked |is1 to keep track of our cows. Note that the items in the linked list are pointers to cows, not adual cow objeds. Add this fundion to CFarm to add a cow to the inventory, void Ci‘arin::1§dd1§nimal(CCow *cow) l mInventory _ push_badlc (cow) ; l Finally, we‘ll add code to add the cow to the inventory when it‘s created. Go to Step‘l .cpp and add this line of code right afler cow»ObtainCovwnlormationu: farm.AuidA.nimal (cow) i Run this and be sure it works of course, you can can't be sure it‘s adually putting things into the inventory We don‘t have code to print the inventory, yet, So, we need to be sure the cow objects are deleted when the farm is destroyed. The function CFarm..~CFarm is called a destructor. tt is executed when the object is destroyed. The farm is destroyed as the program shuts down (when main exists specifically). So, we need to delete our cows in that function Here is a simple loop that does that Ci'arin: :-Ci'arm() l l/ M long as there are animals in the // inventory, we delete the first one and // remove it's pointer from the head of the list. while ( !mInventory. empty“ ) ( delete mInventory..Eront() ,' mInventory.pop_front () ,' There are a variety of other waystodo this as Well, You can iterate over the objects in the list and delete each item, then empty the list meals-15M .‘hAJpMfi-aimnu- i, l cout << mName << ": switch (m'l'ype) i case Bull: cout << "Bull" << endl; break 7 case BeefCow: cout << "Beef Cow" << endlr break? case MilkCow: cout << "Milk Cow/" << mflilkPrcduction << " GPD" << endl; break; Real simply display funtftionality, Note how the enum‘s are used in the case statements, \ fc:r(list<Cch *>: :iterator i=mInventozy.begin()r i != mInventory.end(); i++) i (’i) —>DisplayAnimal () ; ) You should know what an iterator is, but do you know why we do vii»? An iterator is a pointer to an item in the list What are the items in our llSt7 They are pointers to CCow OBJECTS So, i is a pointer to a pointer to a CCow The ‘ in front ofi means "whati is pointing at“, So, ifi is a pointer to a pointerto a CCow, ‘i is a pointer to a CCow We can then use .> To access functions in the object we have pointed to, Finally, add this line to case 9 in Steplcpp: farm . Display I nventary () ,' You should now be able to add cows to the inventory and list the Inventory Just to be sure, is what the malorfiles forthis step should look like at this point /: * CChicken.h : * Definition of the class CChicken, which defines a single chicken. */ #ifndef CCHICJCEN_H_ #define CCHICKEN_H_ #include <s tring> class CChicken ( public: CChickenU ; virtual ~CChicken0 : // Access functions for the chicken ID void SetIiflcanst std: :string fin) lmId = n;} =i—A--=+r+mn m:|—T;—ll\ [rat-“w. m'I'rl-t private: // The chicken's ID std: :string mId; ) 7 #endif /* CCHICJCEN_IH_ */ * CChicken. cpp * Implementation of the class CChicken, which describes a chicken. * Our chickens only have ID numbers. *I #include "CChicken.h" #include <iostream> using namespace std ; . CChicken: :~CChicken() l // TODO Auto—generated destructoz stub } void CChioken: :ObtainChickenI nfcrmation () i cout << endl; cout << "Input information about the chicken" << endl; // Obtain the ID. This is easy, since it's just: a // string. ccut << "Id: ": cin >> mId; } void CChicken: :DisplayAnimal (J ( case 3: { cout << "Adding chicken" << endl; CChicken ’chicken = new CChickenO; chicken—mbtainchickenlnfarmation() ; // fazm.Add.Animal(chicken) ; } break; Notice the option to add the animal to the farm lS commented out. The paiarneterto the function AodAnimal is type CCow ‘ right now, so we can‘t add a chicken. But, we're going to fixthat shonly. Polymorphism Here‘s the problem: lwant to keep an inventory ofanimals However, animals have different specifications, What can loo? l could create a separate inventory for chickens, out that gets old pretty quick ifwe add pigs, llamas, or any otheranimals, And, after all, they are all animals. So, I would like to have an inventory of anrmais instead of an inventory of cows and another inventory of chickens, etc. We‘re going to use one ofthe most important characteristics of objectroriented programming languages: polymorphism Polymorphism in this case means that a cow can be known as a cow or as an animal Likewise, a chicken can be known as a chicken or an animal class CCow to: class CCaw : public CAnimal You Will need to #include “CAnimal.h“. Do the same for the class CChicken. class CChicken : public CAnimal Now we saytnat CCow is denveo' from CAnimal. We also say that CAnimal is a base class or supercrass for CCow and CCnicken. A cow is an animal, so any object oftype CCow can also pe referred to as an opyect oftype CAnimal Go to Stepi cpp After the line CCow ‘cow = new CCowO; add this line CAnimal *animal = cow,- lfyoutryto do this animal—mbtainCowI nfomatian () ; you Will get an error. Only a CCow knows now to do this function, not a CAnimal. Virtual functions Your CCow and CChicken Classes both have a function called DisplayAnimalO This funmion is called to display the information about an animal. Let‘s assume We Will always have a DisplayAnimalOfunction for every possible animal it‘s different for each, because the animals are different. But, it is something that every animal should do Go to CAnimal and add this public memberfunction: virtual void DisplayAnimalO H This is called a Vll'ttlai function. Right now it‘s an empty function that does nothing But, pecause it‘s a Virtual function, itWill be overridden by any class derived from CAnimal that also implements a DisplayAnimal function We have that for both cows and chickens. to: std: :list<CAnimal *> mInventory; Change the parameter in AddAnimal from CCow 'to CAnimal ’ You‘ll need to change it in both the header and implementation ( cpp) You‘ll also need to change the CFarm Displaylnventoryo loop. Change CFarm::Displaylnventory()to void CFarm: :DisplayInv-entcry () l for(1ist<CAnima1 *>: :iterator i=m1nventory.begin(); :‘L != m1nventary.end(); i++) l (*i) ->DisplayAnimal () F l l You can now uncomment that statement farm.AddAninial(chicken); in Steplcpp. You should be able to run the program now, add cows and chickens, and see all ofthem in the inventory Use the debugger to set a breakpoint on the first line ofCCow::DisplayAnimal() and CChicken::DisplayAnimalO Run the program and enter a cow and a chicken Then select display When the debugger breaks on CCow DisplayAnimall), look in the Variables Window You should see “this”, which is the opyectyou are running the procedure on Expand “this”. You can see the variable values in the Window You‘ll also see CAnimal, since it is what CCow is derived from. l M=Variab|es 23 Go Breakpuints Registers EltModules A; r (2: Name Type Value v this ‘ CCow * const 0x804d008 CAnimaI CAnimaI if...) D mNarne 3string {...} mType CCow::Type CCow::Bull mMilkProduction 3 double : o This is how you can tell what the values ofthe membervariables are at anytime You can expand mName, then iMidataplus to see the cow name. Your Programming Tasks Your tasks, and what you Will turn in, are i.Add a new animal: Alpaca The values thatdescribe an alpaca are: Name 7The name ofthe alpaca Breed -An alpaca can be a Sun or a Huacaya Type 7An alpaca can be a macho, hempra, gelding, or cria. Spitting 7We have an integer spitting rating for each alpaca in the range 0 to 10 Be sure you only accept values in the right range. 0 means the alpaca does not spit, while a 10 means apocalyptic levels of spitting. 2. Add a menu option called "Count the male animals“. A bull is a male cow. Both machos and geldings are male alpacas. Assume all chickens are females. Hiril' Add a Virtual function called fsMale to CAriimaf Before you turn in your assignment, i suggest you check all items in the Step 1 : lTECHlSl ...
View Full Document

Page1 / 8

Step1 - CSE 335 Step 1: Introduction to Eclipse and some...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online