Each class you create becomes a new type you can use to declare variables and create objects.
C++ is an extensible programming language (p. 74)—you can define new class types as needed.
Account
ObjectClasses cannot execute by themselves.
A main
function can “drive” an object by calling its member functions—without knowing how the class is implemented. In this sense, main
is referred to as a driver program (p. 75).
Typically, you cannot call a member function of a class until you create an object of that class.
The compiler knows about fundamental types that are “built into” C++.
A new type that you create is known as a user-defined type (p. 76).
New classes, when packaged properly, can be reused by other programmers.
Reusable code (such as a class definition) is placed in a file known as a header (p. 76) that you include (via #include
) wherever you need to use the code.
By convention, a header for a user-defined type has a .h
filename extension.
In an #include
directive, a user-defined header is placed in double quotes (""
), indicating that the header is located with your program, rather than with the C++ Standard Library headers.
Files ending in .cpp
are known as source-code files (p. 76).
Account
’s getName
Member FunctionTo call a member function for a specific object, you specify the object’s name, followed by a dot operator (.; p. 76), then the member function name and a set of parentheses. Empty parentheses indicate that the function does not require any additional information to perform its task.
A member function can return a value from the object on which the function is called.
string
with getline
Functions that are not members of a class are called global functions (p. 77).
An object of C++ Standard Library class string (p. 77) stores character string values. Class string
is defined in the <string> header (p. 77) and belongs to namespace std
.
C++ Standard Library function getline (p. 77), from the <string>
header, reads characters up to, but not including, a newline, which is discarded, then places the characters in a string
.
Account
’s setName
Member FunctionA member-function call can supply arguments (p. 78) that help the function perform its task.
Account
Class DefinitionA class’s data members maintain data for each object of the class, and its member functions manipulate the class’s data members.
class
and the Class BodyA class definition begins with keyword class (p. 79) followed immediately by the class’s name.
A class’s body is enclosed in an opening left brace and a closing right brace.
A class definition terminates with a required semicolon.
Typically, each class definition is placed in a separate header with the .h
filename extension.
Class names, member function names and data member names are all identifiers. By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter. This naming convention is known as camel case, because the uppercase letters stand out like a camel’s humps. Also by convention, class names begin with an initial uppercase letter, and member function and data member names begin with an initial lowercase letter.
name
of Type string
Each object of a class has its own copy of the class’s data members.
An object’s data members exist before a program calls member functions on an object, while they are executing and after the member functions complete execution.
Data members are declared inside a class definition but outside its member functions’ bodies.
The default value for a string
is the empty string
(i.e., ""
; p. 80).
Headers should never contain using
directives or using
declarations.
setName
Member FunctionA function’s return type (p. 79; which appears to the left of the function’s name) specifies the type of data the function returns to its caller after performing its task.
The return type void (p. 80) indicates that when a function completes its task, it does not return (i.e., give back) any information to its calling function (p. 80).
Parameters (p. 80) specify additional information the function needs to perform its task.
When you call a function, each argument value in the call’s parentheses is copied into the corresponding parameter in the member function definition.
Parameters are declared in a parameter list (p. 81) located in required parentheses following a function’s name. Each parameter must specify a type followed by a parameter name.
Multiple parameters in a function definition are separated by commas.
The number and order of arguments in a function call must match the number and order of parameters in the function definition’s parameter list.
Every function body is delimited by an opening left brace and a closing right brace. Within the braces are one or more statements that perform the function’s task(s).
When program execution reaches a function’s closing brace, the function returns to its caller.
Variables declared in a particular function’s body are local variables (p. 81), which can be used only in that function. When a function terminates, the values of its local variables are lost.
A function’s parameters also are local variables of that function.
The argument types in the member function call must be consistent with the types of the corresponding parameters in the member function’s definition.
getName
Member FunctionWhen a member function that specifies a return type other than void
is called and completes its task, it must return a result to its caller.
The return statement (p. 82) passes a value back to a function’s caller.
A member function that does not, and should not, modify the object on which it’s called is declared with const (p. 82) to the right of its parameter list.
private
and public
Access specifiers are always followed by a colon (:
).
A private
data member is accessible only to its class’s member functions.
Most data-member declarations appear after the private
access specifier.
Variables or functions listed after the public (p. 83) access specifier (and before the next access specifier, if there is one) are “available to the public.” They can be used by other functions in the program, and by member functions of other classes.
By default, everything in a class is private
, unless you specify otherwise.
Once you list an access specifier, everything from that point has that access until you list another access specifier.
Declaring data members private
is known as data hiding (p. 82). private
data members are encapsulated (hidden) in an object and can be accessed only by member functions of the object’s class.
Account
UML Class DiagramUML class diagrams (p. 83) can be used to summarize a class’s attributes and operations.
In the UML, each class is modeled in a class diagram as a rectangle with three compartments.
The top compartment contains the class name centered horizontally in boldface type.
The middle compartment contains the class’s attribute names, which correspond to the data members of a class.
A private attribute lists a minus sign (–
) access modifier before the attribute name.
Following the attribute name are a colon and the attribute type.
The bottom compartment contains the class’s operations (p. 84), which correspond to the member functions in a class.
The UML models operations by listing the operation name preceded by an access modifier. A plus sign (+
) indicates a public operation in the UML.
An operation that does not have any parameters specifies empty parentheses following the operation name.
The UML indicates the return type of an operation by placing a colon and the return type after the parentheses following the operation name.
For a void
return type a UML class diagram does not specify anything after the parentheses of the operation.
The UML models a parameter by listing the parameter name, followed by a colon and the parameter type in the parentheses after the operation name.
Account
Class: Initializing Objects with ConstructorsEach class can define a constructor (p. 84) for custom object initialization.
A constructor is a special member function that must have the same name as the class.
C++ requires a constructor call for every object that’s created.
Like member functions, a constructor can specify parameters—the corresponding argument values help initialize the object’s data members.
Account
Constructor for Custom Object InitializationNormally, constructors are public
.
A constructor’s parameter list specifies pieces of data required to initialize an object.
A constructor uses a member-initializer list (p. 86) to initialize its data members with the values of the corresponding parameters.
Member initializers appear between a constructor’s parameter list and the left brace that begins the constructor’s body.
The member-initializer list is separated from the parameter list with a colon (:
).
Each member initializer consists of a data member’s variable name followed by parentheses containing the member’s initial value.
Each member initializer in a constructor is separated from the next by a comma.
The member initializer list executes before the constructor’s body executes.
A constructor that specifies a single parameter should be declared explicit (p. 86).
A constructor does not specify a return type, because constructors cannot return values.
Constructors cannot be declared const
(because initializing an object modifies it).
Account
Objects When They’re CreatedWhen you create an object, C++ calls the class’s constructor to initialize that object. If a constructor has parameters, the corresponding arguments are placed in braces, {
and }
, to the right of the object’s variable name.
When you create an object without placing braces to the right of the object’s variable name, C++ implicitly calls the class’s default constructor (p. 87).
In any class that does not explicitly define a constructor, the compiler provides a default constructor (which always has no parameters).
The default constructor does not initialize the class’s fundamental-type data members, but does call the default constructor for each data member that’s an object of another class.
A string
’s default constructor initializes the object to the empty string
.
An uninitialized fundamental-type variable contains an undefined (“garbage”) value.
If a class defines a constructor, the compiler will not create a default constructor for that class.
Account
UML Class Diagram with a ConstructorLike operations, the UML models constructors in the third compartment of a class diagram.
To distinguish a constructor from the class’s operations, the UML requires that the word “constructor” be enclosed in guillemets (≪ and ≫ ; p. 88) and placed before the constructor’s name.
It’s customary to list constructors before other operations in the third compartment.
Through the use of set and get member functions, you can validate attempted modifications to private
data and control how that data is presented to the caller.
A client (p. 88 ) of a class is any other code that calls the class’s member functions.
Any client code can see a public
data member and do whatever it wanted with it, including setting it to an invalid value.
Set functions can be programmed to validate their arguments and reject any attempts to set the data to bad values.
A get function can present the data to a client in a different form.
Tightly controlling the access to and presentation of private
data can greatly reduce errors, while increasing the usability, robustness and security of your programs.
balance
You can initialize fundamental-type data members in their declarations. This is known as an inclass initializer (p. 90 ) and was introduced in C++11.
deposit
Member Function with ValidationA set function can perform validity checking before modifying a data member.