C++ assignment

513 views

Published on

Published in: Education, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
513
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

C++ assignment

  1. 1. The C++ language allows you to create and use data types other than thefundamental data types. These types are called user-defined data types. There aretwo ways by which a user-defined data type can be created. The first is by using thekeyword struct, and the second is by using the keyword class. Data types definedusing the keyword struct are called structures.StructuresIn C++, a structure is a collection of variables that are referenced by a single name.The variable can be of different data types. They provide a convenient means ofkeeping related information together. Structure definition forms a template which isthen used to create structure variables. The variables that make up the structure arecalled structure elements.All the elements found in the structure are related to each other. For example, theinvoice number and the invoice amount found in an invoice would normally berepresented in a structure. The following code segment shows how a structuetemplate that defines an invoice number and invoice amount can be created. Thekeyword struct tells the compiler that a structure template is being declared.struct invoice{intiInvoice_no;float fInvoice_amt;};Notice that the structure declaration is terminated by a semi-colon. This is because astructure declaration is a statement. Also, the structure tag invoice identifies thisparticular data structure. At this point in the code, no variable has been declared;only the form of the data has been defined.To declare a variable, you need to use the following statement:invoice Inv1;
  2. 2. This defines a structure variable of type invoice, called Inv1. When you declare astructure, you are, in essence, defining a data type. Memory is not allocated for astructure until a variable of that type is created.The compiler automatically allocates sufficient memory to accommodate all theelements that make up the structure.You may also declare two or more variables at the time of declaring a structure. Forexample:struct invoice{intiInvoice_no;float fInvoice_amt;}Inv1,Inv2;will declare a structure type called invoice and declare the variable Inv1 and Inv2.If only one structure has to be declared in a program, then following definition wouldsuffice:struct{intiInvoice_no;float fInvoice_amt;}Inv1;The general form of a structure declaration is:struct<tag>{<type><variable1>;<type><variable2>;...
  3. 3. ...<type><variableN>;}<structvars>;where <tag> is the name of the structure declaration, effectively the name of thenew data type. The structure tag is then used to declare structure variables.<structvars> are the names of structure variables. Either the <tag> or the<structvars> can be omitted, but noth both.Data StructuresWe have already learned how groups of sequential data can be used in C++. But this is somewhatrestrictive, since in many occasions what we want to store are not mere sequences of elements all ofthe same data type, but sets of different elements with different data types.Data structuresA data structure is a group of data elements grouped together under one name. These data elements,known asmembers, can have different types and different lengths. Data structures are declared inC++ using the following syntax:structstructure_name {member_type1 member_name1;member_type2 member_name2;member_type3 member_name3;..} object_names;where structure_name is a name for the structure type, object_name can be a set of valid identifiersfor objects that have the type of this structure. Within braces { } there is a list with the datamembers, each one is specified with a type and a valid identifier as its name.The first thing we have to know is that a data structure creates a new type: Once a data structure isdeclared, a new type with the identifier specified as structure_name is created and can be used in therest of the program as if it was any other type. For example:1 struct product {2 int weight;3 float price;4 } ;5
  4. 4. 6 product apple;7 product banana, melon;We have first declared a structure type called product with two members: weight and price, each ofa different fundamental type. We have then used this name of the structure type (product) to declarethree objects of that type: apple, banana and melon as we would have done with any fundamentaldata type.Once declared, product has become a new valid type name like the fundamentalones int, char or short and from that point on we are able to declare objects (variables) of thiscompound new type, like we have done with apple,banana and melon.Right at the end of the struct declaration, and before the ending semicolon, we can use the optionalfieldobject_name to directly declare objects of the structure type. For example, we can also declarethe structure objects apple, banana and melon at the moment we define the data structure type thisway:1 struct product {2 int weight;3 float price;4 } apple, banana, melon;It is important to clearly differentiate between what is the structure type name, and what is an object(variable) that has this structure type. We can instantiate many objects (i.e. variables,like apple, banana and melon) from a single structure type (product).Once we have declared our three objects of a determined structure type (apple, banana and melon)we can operate directly with their members. To do that we use a dot (.) inserted between the objectname and the member name. For example, we could operate with any of these elements as if theywere standard variables of their respective types:1 apple.weight2 apple.price3 banana.weight4 banana.price5 melon.weight6 melon.priceEach one of these has the data type corresponding to the member they referto: apple.weight, banana.weight andmelon.weight are of type int,while apple.price, banana.price and melon.price are of type float.Lets see a real example where you can see how a structure type can be used in the same way asfundamental types:
  5. 5. 1 // example about structures Enter title: Alien 2 #include <iostream> Enter year: 1979 3 #include <string> 4 #include <sstream> My favorite movie is: 5 usingnamespacestd; 2001 A Space Odyssey (1968) 6 And yours is: 7 structmovies_t { Alien (1979) 8 string title; 9 int year; 10 } mine, yours; 11 12 voidprintmovie (movies_t movie); 13 14 int main () 15 { 16 string mystr; 17 18 mine.title = "2001 A Space Odyssey"; 19 mine.year = 1968; 20 21 cout<<"Enter title: "; 22 getline (cin,yours.title); 23 cout<<"Enter year: "; 24 getline (cin,mystr); 25 stringstream(mystr) >>yours.year; 26 27 cout<<"My favorite movie is:n "; 28 printmovie (mine); 29 cout<<"And yours is:n "; 30 printmovie (yours); 31 return 0; 32 } 33 34 voidprintmovie (movies_t movie) 35 { 36 cout<<movie.title; 37 cout<<" ("<<movie.year<<")n"; 38 }The example shows how we can use the members of an object as regular variables. For example, thememberyours.year is a valid variable of type int, and mine.title is a valid variable of type string.The objects mine and yours can also be treated as valid variables of type movies_t, for example wehave passed them to the function printmovie as we would have done with regular variables.Therefore, one of the most important advantages of data structures is that we can either refer to theirmembers individually or to the entire structure as a block with only one identifier.Data structures are a feature that can be used to represent databases, especially if we consider thepossibility of building arrays of them: 1 // array of structures Enter title: Blade Runner 2 #include <iostream> Enter year: 1982
  6. 6. 3 #include <string> Enter title: Matrix 4 #include <sstream> Enter year: 1999 5 usingnamespacestd; Enter title: Taxi Driver 6 Enter year: 1976 7 #define N_MOVIES 3 8 You have entered these movies: 9 structmovies_t { Blade Runner (1982) 10 string title; Matrix (1999) 11 int year; Taxi Driver (1976) 12 } films [N_MOVIES]; 13 14 voidprintmovie (movies_t movie); 15 16 int main () 17 { 18 string mystr; 19 int n; 20 21 for (n=0; n<N_MOVIES; n++) 22 { 23 cout<<"Enter title: "; 24 getline (cin,films[n].title); 25 cout<<"Enter year: "; 26 getline (cin,mystr); 27 stringstream(mystr) >> films[n].year; 28 } 29 30 cout<<"nYou have entered these movies:n"; 31 for (n=0; n<N_MOVIES; n++) 32 printmovie (films[n]); 33 return 0; 34 } 35 36 voidprintmovie (movies_t movie) 37 { 38 cout<<movie.title; 39 cout<<" ("<<movie.year<<")n"; 40 }Pointers to structuresLike any other type, structures can be pointed by its own type of pointers:1 structmovies_t {2 string title;3 int year;4 };56 movies_tamovie;7 movies_t * pmovie;
  7. 7. Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects ofstructure typemovies_t. So, the following code would also be valid: pmovie = &amovie;The value of the pointer pmovie would be assigned to a reference to the object amovie (its memoryaddress).We will now go with another example that includes pointers, which will serve to introduce a newoperator: the arrow operator (->): 1 // pointers to structures Enter title: Invasion of the body 2 #include <iostream> snatchers 3 #include <string> Enter year: 1978 4 #include <sstream> 5 usingnamespacestd; You have entered: 6 Invasion of the body snatchers (1978) 7 structmovies_t { 8 string title; 9 int year; 10 }; 11 12 int main () 13 { 14 string mystr; 15 16 movies_tamovie; 17 movies_t * pmovie; 18 pmovie = &amovie; 19 20 cout<<"Enter title: "; 21 getline (cin, pmovie->title); 22 cout<<"Enter year: "; 23 getline (cin, mystr); 24 (stringstream) mystr>>pmovie->year; 25 26 cout<<"nYou have entered:n"; 27 cout<<pmovie->title; 28 cout<<" ("<<pmovie->year <<")n"; 29 30 return 0; 31 }The previous code includes an important introduction: the arrow operator (->). This is a dereferenceoperator that is used exclusively with pointers to objects with members. This operator serves toaccess a member of an object to which we have a reference. In the example we used:
  8. 8. pmovie->titleWhich is for all purposes equivalent to: (*pmovie).titleBoth expressions pmovie->title and (*pmovie).title are valid and both mean that we areevaluating the membertitle of the data structure pointed by a pointer called pmovie. It must beclearly differentiated from: *pmovie.titlewhich is equivalent to: *(pmovie.title)And that would access the value pointed by a hypothetical pointer member called title of thestructure objectpmovie (which in this case would not be a pointer). The following panel summarizespossible combinations of pointers and structure members:Expression What is evaluated Equivalenta.b Member b of object aa->b Member b of object pointed by a (*a).b*a.b Value pointed by member b of object a *(a.b)Nesting structuresStructures can also be nested so that a valid element of a structure can also be in its turn anotherstructure. 1 structmovies_t { 2 string title; 3 int year;
  9. 9. 4 }; 5 6 structfriends_t { 7 string name; 8 string email; 9 movies_tfavorite_movie;10 } charlie, maria;1112 friends_t * pfriends = &charlie;After the previous declaration we could use any of the following expressions:1 charlie.name2 maria.favorite_movie.title3 charlie.favorite_movie.year4 pfriends->favorite_movie.year(where, by the way, the last two expressions refer to the same member).Defined data types (typedef)C++ allows the definition of our own types based on other existing data types. We can do this usingthe keywordtypedef, whose format is:typedefexisting_typenew_type_name ;where existing_type is a C++ fundamental or compound type and new_type_name is the name forthe new type we are defining. For example:1 typedefchar C;2 typedefunsignedint WORD;3 typedefchar * pChar;4 typedefchar field [50];In this case we have defined four data types: C, WORD, pChar and field as char, unsignedint, char* and char[50]respectively, that we could perfectly use in declarations later as any othervalid type:1 C mychar, anotherchar, *ptc1;2 WORD myword;3 pChar ptc2;4 field name;typedef does not create different types. It only creates synonyms of existing types. That means thatthe type ofmyword can be considered to be either WORD or unsigned int, since both are in fact thesame type.
  10. 10. typedef can be useful to define an alias for a type that is frequently used within a program. It is alsouseful to define types when it is possible that we will need to change the type in later versions of ourprogram, or if a type you want to use has a name that is too long or confusing.UnionsUnions allow one same portion of memory to be accessed as different data types, since all of them arein fact the same location in memory. Its declaration and use is similar to the one of structures but itsfunctionality is totally different:unionunion_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . .} object_names;All the elements of the union declaration occupy the same physical space in memory. Its size is theone of the greatest element of the declaration. For example:1 unionmytypes_t {2 char c;3 int i;4 float f;5 } mytypes;defines three elements:1 mytypes.c2 mytypes.i3 mytypes.feach one with a different data type. Since all of them are referring to the same location in memory,the modification of one of the elements will affect the value of all of them. We cannot store differentvalues in them independent of each other.One of the uses a union may have is to unite an elementary type with an array or structures ofsmaller elements. For example:1 unionmix_t {2 long l;3 struct {4 short hi;5 short lo;6 } s;7 char c[4];8 } mix;
  11. 11. defines three names that allow us to access the same group of 4 bytes: mix.l, mix.s and mix.c andwhich we can use according to how we want to access these bytes, as if they were a single long-typedata, as if they were twoshort elements or as an array of char elements, respectively. I have mixedtypes, arrays and structures in the union so that you can see the different ways that we can accessthe data. For a little-endian system (most PC platforms), this union could be represented as:The exact alignment and order of the members of a union in memory is platform dependant. Thereforebe aware of possible portability issues with this type of use.Anonymous unionsIn C++ we have the option to declare anonymous unions. If we declare a union without any name, theunion will be anonymous and we will be able to access its members directly by their member names.For example, look at the difference between these two structure declarations:structure with regular union structure with anonymous unionstruct { struct { char title[50]; char title[50]; char author[50]; char author[50]; union { union { float dollars; float dollars;int yen; int yen; } price; };} book; } book;The only difference between the two pieces of code is that in the first one we have given a name tothe union (price) and in the second one we have not. The difference is seen when we access themembers dollars and yenof an object of this type. For an object of the first type, it would be:1 book.price.dollars2 book.price.yenwhereas for an object of the second type, it would be:1 book.dollars2 book.yenOnce again I remind you that because it is a union and not a struct, themembers dollars and yen occupy the same physical space in the memory so they cannot be used tostore two different values simultaneously. You can set a value for price in dollars or in yen, but not inboth.
  12. 12. Enumerations (enum)Enumerations create new data types to contain something different that is not limited to the valuesfundamental data types may take. Its form is the following:enumenumeration_name { value1, value2, value3, . .} object_names;For example, we could create a new type of variable called colors_t to store colors with the followingdeclaration: enumcolors_t {black, blue, green, cyan, red, purple, yellow, white};Notice that we do not include any fundamental data type in the declaration. To say it somehow, wehave created a whole new data type from scratch without basing it on any other existing type. Thepossible values that variables of this new type color_t may take are the new constant values includedwithin braces. For example, once thecolors_t enumeration is declared the following expressions willbe valid:1 colors_tmycolor;23 mycolor = blue;4 if (mycolor == green) mycolor = red;Enumerations are type compatible with numeric variables, so their constants are always assigned aninteger numerical value internally. If it is not specified, the integer value equivalent to the firstpossible value is equivalent to 0 and the following ones follow a +1 progression. Thus, in our datatype colors_t that we have defined above,black would be equivalent to 0, blue would be equivalentto 1, green to 2, and so on.We can explicitly specify an integer value for any of the constant values that our enumerated type cantake. If the constant value that follows it is not given an integer value, it is automatically assumed thesame value as the previous one plus one. For example:1 enummonths_t { january=1, february, march, april,2 may, june, july, august,3 september, october, november, december} y2k;In this case, variable y2k of enumerated type months_t can contain any of the 12 possible values thatgo fromjanuary to december and that are equivalent to values between 1 and 12 (notbetween 0 and 11, since we have made january equal to 1).

×