UDTs (User-Defined Types):
A data type is a set of values together with a set of operations on those values. User-defined types are collections of data, which describe an object's attributes and state. In C++, there are many examples of objects, including user-defined variables. Every object has a type, like variables of native types (short, char, float, etc.). For example, a class can be defined called MyClass, then objects can be instantiated of type MyClass, like native variables can be of type short, char, etc. However, since the compiler has no fundamental understanding of user-defined types, programmers have to define these data types.
User-Defined Types
- Classes
- Enumerations
- typedef definitions
- Structures (or records)
Class: Review Chapter 9 of the text book for a more detailed review of classes.
A class specified by the keyword class, is a user defined type that contains both data members and member functions...
// Fig. 3.1: fig03_01.cpp // Define class GradeBook with a member function displayMessage; // Create a GradeBook object and call its displayMessage function. #include <iostream> using namespace std; // GradeBook class definition class GradeBook { public: // function that displays a welcome message to the GradeBook user void displayMessage() { cout << "Welcome to the Grade Book!" << endl; } // end function displayMessage }; // end class GradeBook // function main begins program execution int main() { GradeBook myGradeBook; // create a GradeBook object named myGradeBook myGradeBook.displayMessage(); // call object's displayMessage function } // end main
// Fig. 3.11: GradeBook.h // GradeBook class definition. This file presents GradeBook's public // interface without revealing the implementations of GradeBook's member // functions, which are defined in GradeBook.cpp. #include <string> // class GradeBook uses C++ standard string class using namespace std; // GradeBook class definition class GradeBook { public: GradeBook( string ); // constructor that initializes courseName void setCourseName( string ); // function that sets the course name string getCourseName(); // function that gets the course name void displayMessage(); // function that displays a welcome message private: string courseName; // course name for this GradeBook }; // end class GradeBook
// Fig. 3.12: GradeBook.cpp // GradeBook member-function definitions. This file contains // implementations of the member functions prototyped in GradeBook.h. #include <iostream> #include "GradeBook.h" // include definition of class GradeBook using namespace std; // constructor initializes courseName with string supplied as argument GradeBook::GradeBook( string name ) { setCourseName( name ); // call set function to initialize courseName } // end GradeBook constructor // function to set the course name void GradeBook::setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName // function to get the course name string GradeBook::getCourseName() { return courseName; // return object's courseName } // end function getCourseName // display a welcome message to the GradeBook user void GradeBook::displayMessage() { // call getCourseName to get the courseName cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessage
/ Fig. 3.13: fig03_13.cpp // GradeBook class demonstration after separating // its interface from its implementation. #include <iostream> #include "GradeBook.h" // include definition of class GradeBook using namespace std; // function main begins program execution int main() { // create two GradeBook objects GradeBook gradeBook1( "CS101 Introduction to C++ Programming" ); GradeBook gradeBook2( "CS102 Data Structures in C++" ); // display initial value of courseName for each GradeBook cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() << endl; } // end main
Enumeration Data Type:
Using Enumeration Data Type:An enumeration, specified by the keyword enum, is a set of integer constants associated by identifiers--called enumerators. Enumerations provide a manner to implement names (or identifiers), in place of integer constants. Enumerator values begin at zero (0), if a value for the initial enumerator was not provided. Enumerators may be used wherever an int value is utilized. If no user specified value is assigned, compilers will assign the following integer value after the integer value assigned to the preceding enumerator.
enum typeName {value1, value2 ...}; //indentifiers value1 and value2 called enumerators
enum csStudent {Bill, Jen, Steve, Larry}; enum mathStudent {Mary, Doug, Jen, Clay}; //illegal, value Jen can't be used in same program, in same block
//defines vehicle as an enumeration type, with values: auto, truck, motorcycle, snowmobile, and boat enum vehicle {auto, truck, motorcycle, snowmobile, boat}; vehicle myVehicle; //variable of type vehicle declared vehicle yourVehicle; //another variable of type vehicle declared
enum vehicle {"auto", "truck", ...}; //illegal, can't use quotes enum number {1, 2, 3}; //illegal, can't begin identifier name with number enum number {one, two, three}; //legal value
vehicle myVehicle, yourVehicle; //variables of type vehicle declared myVehicle = Car; //assigns Car to myVehicle yourVehicle = myVehicle; //copies contents of variable myVehicle into yourVehicle //Or... //Creating enumeration type, and declaring variables of that type in one step: enum vehicle {auto, truck, motorcycle, snowmobile, boat} myVehicle, yourVehicle;
yourVehicle = myVehicle + 2; //illegal: theirVehicle = myVehicle + yourVehicle; //illegal: myVehicle++; //illegal: myVehicle--; //illegal:
yourVehicle = static_cast<vehicle>(yourVehicle + 1);
//Creating anonymous enumeration data type, and declaring variables of that type in one step: enum {auto, truck, motorcycle, snowmobile, boat} myVehicle, yourVehicle;
//This program demos enumeration data types #include <iostream> using std::cout; using std::cin; using std::endl; //initialize constants //initialize global variables //prototype functions int main() { //initialize local variables enum bookType {Math, CSC, English, History, Physics, Philosophy}; bookType book; book = English; cout<<"book = "<< book <<" (ONLY outputs DEFAULT value DIRECTLY.)" << endl; book = static_cast<bookType>(book + 1); cout<<"book = "<< book <<" (increment, still ONLY outputs DEFAULT value DIRECTLY.)" << endl; //must decrement for next block of code to work properly... book = static_cast<bookType>(book - 1); cout<<"The enumeration value currently selected is "; switch (book) { case Math: cout << "Math"; break; case CSC: cout << "CSC"; break; case English: cout << "English"; break; case History: cout << "History"; break; case Physics: cout << "Physics"; break; case Philosophy: cout << "Philosophy"; } cout << "\nPress Enter key to exit..."; cin.get(); // make DOS window stay open, sometimes... return 0; }Sample Run:
book = 2 (ONLY outputs DEFAULT value DIRECTLY.) book = 3 (increment, still ONLY outputs DEFAULT value DIRECTLY.) The enumeration value currently selected is English Press Enter key to exit...Enumeration Program
Using typedef Statement:
Summary of typedef Definitions:As a shortcut to long, repetitious variable declarations, and as an error preventative measure, C++ allows the creation of an alias or synonym--by using the keyword typedef, which stands for type definition. Type definitions are also useful when data types may change in later revisions of programs. With a type definition, a synonym or alias is created. Realize that typedef does not create a new type--it is important to understand the distinction. The syntax for a type definition is typedef, followed by the existing type, then the alias or synonym, ending with a semicolon. For example:
//typedef defined... //USHORT synonym for unsigned short int typedef unsigned short int USHORT;The typedef definition creates an alias or synonym called USHORT that can be used rather than unsigned short int://data type of weight is unsigned short int USHORT weight = 160;
ANSI/ISO Standard C++:
ANSI/ISO standard C++ was officially approved in July 1998.
- Most compilers compatible with ANSI/ISO standard C++
- Standard C++ and ANSI/ISO standard C++ are "mostly" the same, but...
- ANSI/ISO Standard C++ has some features not available in Standard C++
Using Namespaces:
Syntax of namespace Statement:ANSI/ISO Standard C++ has some features not available in Standard C++. ANSI/ISO Standard C++ (July, 1998) included the namespace mechanism--Standard C++ did not have it. For example, when a header file, such as iostream, is included in a program, global identifiers in the header file also become global identifiers in the program. If a global identifier in a program has the same name as one of the global identifiers in the header file, the compiler will generate a syntax error (such as identifier redefined). The same problem can occur if a program uses libraries from other compiler vendors. To overcome this problem, these third party compiler vendors usually begin their global identifiers with a special symbol--for example, an underscore character (_). To avoid problems associated with identifier conflicts and linking errors, it is a good policy not to begin identifier names with the underscore character (_) even though it is permissable. ANSI/ISO standard C++ uses namespaces to assist with the problem of overlapping global identifier names.
ANSI/ISO Standard C++ resolves the problem of overlapping global identifier names with the namespace mechanism.
The scope of a namespace member is local to the namespace. Though, a namespace member can be accessed outside the namespace in one of three ways:Each time it is accessed: 1) namespace_name::identifier Simplified (place using statement after the namespace declaration): 2) using namespace namespace_name (access all namespace members) 3) using namespace namespace_name::identifier (access specific namespace member)After the using statement, you do not have to put the namespace_name and the scope resolution operator before the namespace member to access a namespace member.
namespace namespace_name { members... }
namespace myNamespace { const double PI=3.14; int count=0; void printReport(); }
//To access each namespace member: myVar = myNamespace::PI; myVar = myNamespace::count; myNamespace::printReport();
//Simplify accessing specific namespace member: using myNamespace::PI; myVar = PI;
//Simplify accessing all namespace members: using namespace myNamespace; myVar = count;
Using string Data Type:
string name = "John Doe";
string str1 = "Hi"; string str2; str2=str1 + " there!"; //str2 contains "Hi there!"
myStr.length();
string firstName; string name; string str; firstName = "John"; name = firstName + " Doe"; str = "Hello World."; cout << firstName.length() << endl; //prints 4 cout << name.length() << endl; //prints 8 cout << str.length() << endl; //prints 12size() Function:
myStr.size();
myStr.find(strExp);
string str = "It is sunny, isn't it?"; cout << str.find("is") << endl; //prints 3 cout << str.find("s") << endl; //prints 4 cout << str.find("it") << endl; //prints 19substr() Function:
myStr.substr(strExp1,strExp2);
string str = "It is sunny, isn't it?"; cout << str.substr(0, 5) << endl; //prints It is cout << str.substr(6, 5) << endl; //prints sunny cout << str.substr(3, 2) << endl; //prints isswap() Function:
myStr1.swap(myStr2);
//string initialization string myStr1 = "Stop"; string myStr2 = "Go"; myStr1.swap(myStr2);