1.1k likes | 1.28k Views
C++ Data Types and Data Abstractions. C++ Data Types. Namespaces Built-in data types Literal constants Variables Pointers References The C++ string Type The const Qualifier. What is “using namespace std;”. #include <iostream> using namespace std; void main ( ) { int start = 5;
E N D
C++ Data Types • Namespaces • Built-in data types • Literal constants • Variables • Pointers • References • The C++ string Type • The const Qualifier
What is “using namespace std;” #include <iostream> using namespace std; void main ( ) { int start = 5; int end = 19; if (start < end ) { cout << “A”; } // end if cout << “B”; } // end main
Namespaces • The problem: When two variables (or functions) in global scope have the same identifier (name), we get a compile-time error. • To avoid such name collisions, programmers need to use unique identifiers in their own code. • In C, if you use multiple third-party libraries and there is a name collision, you have three choices: • Get the source code to the libraries and modify and recompile it, • ask one of the library publishers to rename their identifiers, or • decide not to use one of the libraries. • Often, none of these options are available.
Namespaces • To tackle this problem, C++ introduced namespaces. • All identifiers declared within a defined block are associated with the block’s namespace identifier. • All references to these identifiers from outside the block must indicate the namespace identifier. • One example is the namespace std, in which Standard C++ defines its library’s identifiers, such as the cout stream object.
Namespaces • You can access objects in the namespace std in the following way using the scope resolution operator “::” • #include <iostream> • int main() • { • std::cout << “Hello World!”; • return 0; • }
Namespaces • Or, you can use the using namespace statement to omit the corresponding namespace references: #include <iostream> using namespace std; int main() { cout << “Hello World!”; return 0; }
Namespaces • This is how you define your own namespaces: • #include <iostream> • namespace MyNames • { • int value1 = 10; • int value2 = 20; • int ComputeSum() • { • return (value1 + value2); • } • } • int main() • { • std::cout << MyNames::ComputeSum() << std::endl; • }
Namespaces • If you use multiple using namespace statements, you may get a compile-time error due to ambiguity: • #include <iostream> • namespace MyNames • { • int value1 = 10; • int value2 = 20; • } • namespace MyOtherNames • { • int value1 = 30; • int value2 = 40; • } • using namespace std; • using namespace MyNames; • using namespace MyOtherNames; • int main() • { • value1 = 50; • }
Namespaces • You can also define nested namespaces: • #include <iostream> • namespace MyNames • { • int value1 = 10; • int value2 = 20; • namespace MyInnerNames • { • int value3 = 30; • } • } • int main() • { • std::cout << MyNames::value1 << std::endl; • std::cout << MyNames::MyInnerNames::value3 << std::endl; • }
Numeric Data Types • Type charrepresents individual characters and small integers (1 byte). • Types short, int, and long represent integer values (half a machine word, 1 machine word, 1 or more machine words) • Types float, double, and long double represent floating point values (1 machine word, 2 machine words, 3 or 4 machine words)
Numeric Data Types • Type char, short, int, and long are also called integral types. • Integral types can be signedor unsigned. • Example: The value of an 8-bit unsigned char ranges from 0 to 255, while the range for an 8-bit signed char is from –128 to 127.
Literal Constants • Literal constants are values that occur in a program. • Example: • int main() • { • int students = 21; • double pi = 3.1416; • } • Here, 21 is a literal constantof typeint, and 3.1416 is a literal constant of type double.
Literal Constants • We can use prefixes to write literal integer constants in decimal, octal, or hexadecimal notation. • Examples: Decimal (no prefix): 15 • Octal (prefix 0 [zero]): 015 • = 13 (decimal) • Hexadecimal (prefix 0x [zero-x]): 0x15 • = 21 (decimal)
Literal Constants • By default, the C++ compiler assumes that all literal integer constants are of type int and all literal floating point constants are of type double. • You can specify different types by appending a letter to the literal integer constant. Examples: 2344U (unsigned) 1555L (long) 166UL (unsigned long) 3.1416F (float) 6.2831L (long double)
Literal Constants • Another built-in (or primitive) C++ data type is the type bool. • Its only literals are true and false. • Note that the type bool does not exist in C. • In C, we represent the Boolean values true and false by the integers 1 and 0.
Literal Constants • We use single quotation marks to write literal character constants. • Examples: ‘x’, ‘4’, ‘:’, ‘ ‘ (space) • Nonprintable characters and some special characters can be represented by escape sequences. • Examples: • ‘\n’ (newline), ‘\a’ (bell), ‘\t’ (tab) • ‘\\’ (backslash), ‘\’’ (single quote), ‘\”’ (double quote)
Literal Constants • Generalized escape sequences are indicated by a backslash followed by up to three digits. • The value of the digits in the sequence is interpreted as the corresponding literal constant in the ASCII character set. Examples: \7 (bell) \14 (newline) \65 (‘5’)
Literal Constants • A character literal can be preceded by an L, for example: L’a’ • This is called a wide-character literal and has type wchar_t. • Such wide-character literals support language character sets like Chinese and Japanese, which cannot be represented within the 256 character ASCII set.
Literal Constants • A literal string constant is composed of zero or more characters enclosed in double quotation marks. Examples: “” (null string) “x” “hello” “Hi,\nHow are you?\n”
Literal Constants • A string literal can be written across multiple lines. You can use a backslash as the last character on a line to indicate that the string continues on the next line. Example: “This is an \ excellent \ multi-line string literal.”
Variables • Variables provide us with named memory storage that we can • write to, • read from, and • manipulate • throughout the course of our program. • Each variable has a specific type, which determines • the size and layout of its associated memory, • the range of values that can be stored, and • the set of operations that can be applied to it. • Variables are also referred to as objects.
Variables • There are two values associated with a variable: • Its data value, which is stored at some memory address. It is also called the rvalue (read value) of the variable. • Its address value, indicating the location in memory where its data value is stored. This value is also referred to as the variable’s lvalue (location value).
Pointers • A pointer holds the memory address of another object. • Through the pointer we can indirectly manipulate the referenced object. • Pointers are useful for • Creating linked data structures such as trees and lists, • management of dynamically allocated objects, and • as a function parameter type for passing large objects such as arrays.
Pointers • Every pointer has an associated type. • The type of a pointer tells the compiler how to interpret the memory content at the referenced location and how many bytes this interpretation includes. • Examples of pointer definitions: int *pointer; int *pointer1, *pointer2; string *myString;
Pointers • The dereference operator (*) dereferences a pointer variable so that we can manipulate the memory content at the location specified by the pointer. • The address-of operator (&) provides the memory address (a pointer) of a given object.
Pointers • Example: Correct or incorrect? • int var1=333, var2=444, *pvar1, *pvar2; • pvar1 = var1; • incorrect. *int int • pvar2 = &var2; • correct. *int = *int • *pvar1 = var2; • correct. int = int • *pvar2 = *pvar1 + 100; • correct. int = int
Pointers • Notice that in pointer definitions the ‘*’ symbol indicates the pointer type and is not the dereference operator. • Example: • int var; • int *pvar1 = var; • Incorrect! During initialization a pointer can only be assigned an address: • int var; • int *pvar1 = &var; • Correct!
References • References (aliases) can be used as alternative names for objects. • In most cases they are used as formal parameters to a function. • A reference type is defined by following the type specifier with the address-of operator. Example: int val1 = 333; int &refVal1 = val1;
References • A reference must be initialized. • Once defined, a reference cannot be made to refer to another object. • All operations on the reference are actually applied to the object to which the reference refers. • Example: • int val1 = 333; • int &refVal1 = val1; • val1++; • refVal1 += 100; • cout << “Result: ” << refVal1; • Result: 434
Pass-by-value CALLING BLOCK FUNCTION CALLED sends a copy of the contents of the actual parameter SO, the actual parameter cannot be changed by the function. 31
Pass-by-reference sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED can change value of actual parameter 32
The C++ string Type • To use the C++ string type, you must include its associated header file: • #include <string> • Different ways to initialize strings: • string myString(“Hello folks!”); • string myOtherString(myString); • string myFinalString; // empty string • The length of a string is returned by its size() operation (without the terminating null character): cout << myString.size(); • = 12
The C++ string Type • We can use the empty() operation to find out whether a string is empty: • bool isStringEmpty = myString.empty(); • Use the equality operator to check whether two strings are equal: • if (myString == myOtherString) • cout << “Wow, the strings are equal.”; • Copy one string to another with the assignment operator: myFinalString = myOtherString;
The C++ string Type • Use the plus operator to concatenate strings: • string s1 = “Wow! ”, s2 = “Ouch! ”; • const char *s3 = “Yuck! ” • s2 += s1 + s3 + s2; • cout << s2; • = Ouch! Wow! Yuck! Ouch!
The const Qualifier • The const type qualifier transforms an object into a constant. Example: const double pi = 3.1416; • Constants allow you to store parameters in well- defined places in your code • Constants have an associated type. • Constants must be initialized. • Constants cannot be modified after their definition. • Constants replace the #define “technique” in C.
The const Qualifier • Sometimes you may want to define for your object a set of states or actions. • For example, you could define the following states for the Student Counselor: • observeStudent • shoutAtStudent • followStudent • rechargeBattery
The const Qualifier • Using the const qualifier, you could define the following constants: • const int observeStudent = 1; • const int shoutAtStudent = 2; • const int followStudent = 3; • const int rechargeBattery = 4; • A function SetRobotState could then be defined as follows: bool SetRobotState(int newState) { … int currentState = newState; return executionSuccessful; }
Enumeration Types • However, mapping states onto integers has certain disadvantages: • You cannot restrain the range of values that are passed to SetRobotState. • There is no useful typing – if you define individual sets of states for multiple objects, each object could formally be set to any of these states, not only its individual ones. • This problem can be solved with enumeration types.
Enumeration Types • Enumeration types can be defined as follows: • enumrobotState { observeStudent = 1, shoutAtStudent, • followStudent, • rechargeBattery }; • This way we defined a new type robotState that can only assume four different values. • These values still correspond to integers. For example, • cout << followStudent; • gives you the output ‘3’.
Enumeration Types • We are now able to restrain the values that are passed to SetRobotState to the four legal ones: • bool SetRobotState(robotState newState) • { • … • robotState currentState = newState; • return executionSuccessful; • } • Any attempt to call SetRobotState with an integer value or a value of a different enumeration type will cause an error at compile time.
C++ Data Types floating address float double long double pointer reference simple structured integral enum array struct union class char short int long bool
Structured Data Types • Chapter 11
C++ Data Types floating address float double long double pointer reference simple structured Skipping for now… integral enum array struct union class char short int long bool
Structured Data Type • A structured data type is a type in which each value is a collection of component items. • The entire collection has a single name each component can be accessed individually
C++ Structured Type • Often we have related information of various types that we’d like to store together for convenient access under the same identifier, for example . . .
thisAnimal .id 2037581 .name “giant panda” .genus “Ailuropoda” .species “melanoluka” .country “China” .age 18 .weight 234.6 .health Good
anotherAnimal .id 5281003 .name “llama” .genus “Lama” .species “peruana” .country “Peru” .age 7 .weight 278.5 .health Excellent
struct AnimalType • enum HealthType { Poor, Fair, Good, Excellent } ; • struct AnimalType// declares a struct data type • {// does not allocate memory • long id ; • string name ; • string genus ; • string species ; struct members • string country ; • int age ; • float weight ; • HealthType health ; • } ; • AnimalType thisAnimal ; // declare variables of AnimalType • AnimalType anotherAnimal ; 49
struct type Declaration • SYNTAX • struct TypeName • { • MemberList • } ; • MemberList SYNTAX • DataType MemberName ; • DataType MemberName ; • . • . • .