C++笔记

字数 7706 · 2019-11-24

#c

C++ joins three separate programming categories: the procedural language; the object-oriented language; and generic programming.

In general, a class defines what data is used to represent an object and the operations that can be performed on that data.

C++98/C++03
C++11

The Mechanics of Creating a Program

  1. write the source code.
  2. Compile the source code.
  3. Link the object code with additional code.

The file containing the translated program is the object code for your program.

C++ programs normally use libraries.A C++ library contains object code for a collection of computer routines, called functions, to perform tasks such as displaying information onscreen or calculating the square root of a number. Linking combines your object code with object code for the functions you use and with some standard startup code to produce a runtime version of your program. The file containing this final product is called the executable code.

programing steps

In naming a source file, you must use the proper suffix to identify the file as a C++ file.This not only tells you that the file is C++ source code, it tells the compiler that, too.

The extension you use depends on the C++ implementation.

C++ Implementation Source Code Extension(s)
Unix C, cc, cxx, c
GNU C++ C, cc, cxx, cpp, c++
Microsoft Visual C++ cpp, cxx, cc

Unix Compiling and Linking
In C++, as in C, you can spread a program over more than one file. In such a case, you can compile a program by listing all the files on the command line, like this:

1
CC my.C precious.C

This recompiles the my.C file and links it with the previously compiled precious.o file.

1
CC my.C precious.o

Linux Compiling and Linking
Linux systems most commonly use g++, the GNU C++ compiler.

1
2
3
g++ spiffy.cxx
g++ my.cxx precious.cxx
g++ my.cxx precious.o

Command-Line Compilers for Windows Command Prompt Mode

An inexpensive route for compiling C++ programs on a Windows PC is to download a free command-line compiler that runs in Windows Command Prompt mode.

Free Windows downloads that include the GNU C++ compiler are Cygwin and MinGW; they use g++ as the compiler name.

  • Compile typically means compile the code in the file that is currently open.
  • Build or Make typically means compile the code for all the source code files in the project. This is often an incremental process.
  • Build All typically means compile all the source code files from scratch.

If your compiler closes the window, you’ll have a hard time seeing the output. To see the output, you must place some additional code at the end of the program:

1
2
3
4
cin.get(); // add this statement 
cin.get(); // and maybe this, too 
return 0;
}

XCode - Not only does it provide an IDE that supports several programming languages, it also installs a couple of compilers — g++ and clang.

1
2
3
4
5
6
7
8
9
#include <iostream>

int main() {
  using namespace std; // make definitions visible
  cout << "Come up and C++ me some time.";
  cout << endl; // start a new line
  cout << "You wont't regret it!";
  return 0;
}

Seeing cout instead of the printf() function might come as a minor shock. C++ can, in fact, use printf(), scanf(), and all the other standard C input and output functions, provided that you include the usual C stdio.h file.

It uses C++’s input facilities, which improve in many ways upon the C versions.

Typically, main() is called by startup code that the compiler adds to your program to mediate between the program and the operating system.

If your program is to use the usual C++ input or output facilities, you provide these two lines:

1
2
#include <iostream>
using namespace std;

C++, like C, uses a preprocessor. This is a program that processes a source file before the main compilation takes place.

1
#include <iostream> // a PREPROCESSOR directive

This directive causes the preprocessor to add the contents of the iostream file to your program.

This is a typical preprocessor action: adding or replacing text in the source code before it’s compiled.

In essence, the contents of the iostream file replace the #include <iostream> line in the program.

Files such as iostream are called include files or header files.

C++ compilers come with many header files, each supporting a particular family of facilities.

Now the h extension is reserved for the old C header files (which C++ programs can still use), whereas C++ header files have no extension.

There are also C header files that have been converted to C++ header files. These files have been renamed by dropping the h extension and prefixing the filename with a c. For example, the C++ version of math.h is the cmath header file.

Header File Naming Conventions

Kind of Header Convention Example Comments
C++ old style Ends in .h iostream.h Usable by C++ programs
C old style Ends in .h math.h Usable by C and C++ programs
C++ new style No extension iostream Usable by C++ programs, uses namespace std
Converted C c prefix, no extension cmath Usable by C++ programs, might use non-C features, such as namespace std

Namespaces
If you use iostream instead of iostream.h, you should use the following namespace directive to make the definitions in iostream available to your program:

1
using namespace std

Namespace support is a C++ feature designed to simplify the writing of large programs and of programs that combine pre-existing code from several vendors and to help organize programs.

1
2
3
using std::cout; // make cout available
using std::endl; // make endl available
using std::cin; // make cin available

In C++, any series of characters enclosed in double quotation marks is called a character string.

And what is cout? It’s a predefined object that knows how to display a variety of things, including strings, numbers, and individual characters.

A First Look at Operator Overloading
If you’re coming to C++ from C, you probably noticed that the insertion operator (<<) looks just like the bitwise left-shift operator (<<). This is an example of operator overloading, by which the same operator symbol can have different meanings.
C itself has some operator overloading. For example, the & symbol represents both the address operator and the bitwise AND operator. The * symbol represents both multiplication and dereferencing a pointer. The important point here is not the exact function of these operators but that the same symbol can have more than one meaning, with the compiler determining the proper meaning from the context.
C++ extends the operator overloading concept by letting you redefine operator meanings for the user-defined types called classes.

endl is a special C++ notation that represents the important concept of beginning a new line.

C++ Statements

A C++ program is a collection of functions, and each function is a collection of statements.

1
int carrots;

This statement provides two kinds of information: the type of memory storage needed and a label to attach to that storage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
  using namespace std;
  int carrots;
  cout << "How many carrots do you have?" << endl; 
  cin >> carrots;
  cout << "Here are two more. ";
  carrots = carrots + 2;
  cout << "Now you have " << carrots << " carrots." << endl;
  return 0;
}

// How many carrots do you have?
// > 20
// Here are two more. Now you have 22 carrots.
1
cin >> carrots;

Looking at this statement, you can practically see information flowing from cin into carrots.

C++ functions come in two varieties: those with return values and those without them.

C and C++ divide these two features —- prototype and definition —- for library functions. The library files contain the compiled code for the functions, whereas the header files contain the prototypes.
You should place a function prototype ahead of where you first use the function.

Some languages reserve the term function for functions with return values and use the terms procedure or subroutine for those without return values, but C++, like C, uses the term function for both variations.

The function call assigns the value 3 to the n variable defined in the simon() header:

1
simon(3);
  • You can place the using namespace std; above the function definitions in a file, making all the contents of the std namespace available to every function in the file.
  • You can place the using namespace std; in a specific function definition, making all the contents of the std namespace available to that specific function
  • Instead of using using namespace std; you can place using std::cout; in a specific function definition and make a particular element, such as cout, available to that function
  • using using std::cout above function definitions.
  • You can omit the using directives and declarations entirely and use the std:: prefix whenever you use elements from the std namespace: std::cout << "I’m using cout and endl from the std namespace" << std::endl;

C++ statement types include the following:

  • Declaration statement — A declaration statement announces the name and the type of a variable used in a function.
  • Assignment statement — An assignment statement uses the assignment operator (=) to assign a value to a variable.
  • Message statement — A message statement sends a message to an object, initiating some sort of action.
  • Function call — A function call activates a function.When the called function ter- minates, the program returns to the statement in the calling function immediately following the function call.
  • Function prototype — A function prototype declares the return type for a function, along with the number and type of arguments the function expects.
  • Return statement — A return statement sends a value from a called function back to the calling function.

To store an item of information in a computer, the program must keep track of three fundamental properties:

  • Where the information is stored
  • What value is kept there
  • What kind of information is stored

Names beginning with two underscore characters or with an underscore character followed by an uppercase letter are reserved for use by the implementation—that is, the compiler and the resources it uses. Names beginning with a single underscore character are reserved for use as global identifiers by the implementation.

In ANSI C, two names that have the same first 63 characters are considered identical, even if the 64th characters differ.

If you want to form a name from two or more words, the usual practice is to separate the words with an underscore character, as in my_onions, or to capitalize the initial character of each word after the first, as in myEyeTooth. (C veterans tend to use the underscore method in the C tradition, whereas those raised in the Pascal tradition prefer the capitalization approach.)

C++’s basic integer types, in order of increasing width, are char, short, int, long, and, with C++11, long long. Each comes in both signed and unsigned versions.

It would be convenient if each type were always some particular width for all systems — for example, if short were always 16 bits, int were always 32 bits, and so on. But life is not that simple.
No one choice is suitable for all computer designs. C++ offers a flexible standard with some guaranteed minimum sizes, which it takes from C. Here’s what you get:

  • A short integer is at least 16 bits wide.
  • An int integer is at least as big as short.
  • A long integer is at least 32 bits wide and at least as big as int.
  • A long long integer is at least 64 bits wide and at least as big as long.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <limits>

int main() {
  using namespace std;
  
  cout << "int is " << sizeof(int) << " bytes." << endl;
  cout << "short is " << sizeof(short) << " bytes." << endl;
  cout << "long is " << sizeof(long) << " bytes." << endl;
  cout << "long long is " << sizeof(long long) << " bytes." << endl;
  
  cout << endl;

  cout << "Maximum values:" << endl;
  cout << "\tint:" << INT_MAX << endl;
  cout << "\tshort:" << SHRT_MAX << endl;
  cout << "\tlong:" << LONG_MAX << endl;
  cout << "\tlong long:" << LLONG_MAX << endl;

  cout << endl;
  cout << "Bits per byte: " << CHAR_BIT << endl;
  // ...
  return 0;
}

Symbolic Constants from climits:

Symbolic Constant Represents
CHAR_BIT Number of bits in a char
CHAR_MAX Maximum char value
CHAR_MIN Minimum char value
SCHAR_MAX Maximum signed char value
SCHAR_MIN Minimum signed char value
UCHAR_MAX Maximum unsigned char value
SHRT_MAX Maximum short value
SHRT_MIN Minimum short value
USHRT_MAX Maximum unsigned short value
INT_MAX Maximum int value
INT_MIN Minimum int value
UINT_MAX Maximum unsigned int value
LONG_MAX Maximum long value
LONG_MIN Minimum long value
ULONG_MAX Maximum unsigned long value
LLONG_MAX Maximum long long value
LLONG_MIN Minimum long long value
ULLONG_MAX Maximum unsigned long long value

The climits file contains lines similar to the following:

1
#define INT_MAX 32767

The #define directive works like a global search-and-replace command in a text editor or word processor.

However, the #define directive is a C relic. C++ has a better way of creating symbolic constants (using the const keyword), so you won’t be using #define much. But some header files, particularly those designed to be used with both C and C++, do use it.

C++ has an initialization syntax that is not shared with C:

1
2
int owls = 101; // traditional C initialization, sets owls to 101 
int wrens(432); // alternative C++ syntax, set wrens to 432

Caution
If you don’t initialize a variable that is defined inside a function, the variable’s value is indeterminate. That means the value is whatever happened to be sitting at that memory location prior to the creation of the variable.

1
2
3
4
5
6
int emus{7}; // set emus to 5, from C++98
int rheas = {12}; // set rheas to 12, C++11


int rocs = {}; // set rocs to 0 
int psychics{}; // set psychics to 0

Note that unsigned by itself is short for unsigned int.

iostream provides the dec, hex, and oct manipulators to give cout the messages to display integers in decimal, hexadecimal, and octal formats, respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
int chest = 42;
int waist = 42;
int inseam = 42;
cout << "Monsieur cuts a striking figure!" << endl;
cout << "chest = " << chest << " (decimal for 42)" << endl; 
cout << hex; // manipulator for changing number base
cout << "waist = " << waist << " (hexadecimal for 42)" << endl; 
cout << oct; // manipulator for changing number base
cout << "inseam = " << inseam << " (octal for 42)" << endl; 
return 0;
}

Note that code like the following doesn’t display anything onscreen, instead, it changes the way cout displays integers.

1
cout << hex;
1
2
// using cout.put() to display a char constant 
cout.put('!');
Character Name ASCII Symbol C++ Code ASCII Hex Code
Alert BEL \a 0x7
Backspace BS \b 0x8
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
  cout << "\aOperation \"HyperHype\" is now activated!\n";
  cout << "Enter your agent code:________\b\b\b\b\b\b\b\b";
  long code;
  cin >> code;
  cout << "\aYou entered " << code << "...\n";
  cout << "\aCode verified! Proceed with Plan Z3!\n";
  return 0;
}

Using universal character names is similar to using escape sequences. A universal character name begins either with \u or \U.The \u form is followed by 8 hexadecimal digits, and the \U form by 16 hexadecimal digits.These digits represent the ISO 10646 code point for the character.

1
2
cout << "Let them eat g\u00E2teau.\n";
// Let them eat gâteau.

The bool Type
The ANSI/ISO C++ Standard has added a new type (new to C++, that is), called bool.
In the past, C++, like C, has not had a Boolean type. C++ interprets nonzero values as true and zero values as false.

1
bool is_ready = true;
1
const int Months = 12; // Months is symbolic constant for 12

Like ANSI C, C++ has three floating-point types: float, double, and long double.

Significant figures are the meaningful digits in a number.

In effect, the C and C++ requirements for significant digits amount to float being at least 32 bits, double being at least 48 bits and certainly no smaller than float, and long double being at least as big as double.

You can look in the cfloat or float.h header files to find the limits for your system.

1
2
// dump include path from g++
g++ -E -x c++ - -v < /dev/null 

C++ empowers you to force type conversions explicitly via the type cast mechanism.
you can use either of the following expressions:

1
2
(long) thorn // straight C
long(thorn) //  pure C++
1
cout << int('Q'); // displays the integer code for 'Q'

the static_cast<> operator, can be used for converting values from one numeric type to another.

1
2
3
bats = (int) 19.99 + (int) 11.99; // old C syntax 
coots = int (19.99) + int (11.99); // new C++ syntax
cout << static_cast<int>(ch) << endl; // using static_cast

auto Declarations in C++11

1
2
std::vector<double> scores; 
std::vector<double>::iterator pv = scores.begin();

C++11 allows you to write this instead:

1
2
std::vector<double> scores; 
auto pv = scores.begin();

Compound Types

Array

An array is a data form that can hold several values of the same type.

1
short months[12]; // creates array of 12 short
1
int yamcosts[3] = {20, 30, 5}; // create, initialize array

If you don’t initialize an array that’s defined inside a function, the element values remain undefined.That means the element takes on whatever value previously resided at that location in memory.

1
float hotelTips[5] = {5.0, 2.5};

If you partially initialize an array, the compiler sets the remaining elements to zero.

1
long totals[500] = {0}; // let the compiler initialize the remaining elements to zero.

If you leave the square brackets ([]) empty when you initialize an array, the C++ compiler counts the elements for you.

1
2
3
4
short things[] = {1, 5, 3, 8}; // The compiler makes things an array of four elements.

int num_elements = sizeof things / sizeof (short);

C++11 Array Initialization

First, you can drop the = sign when initializing an array:

1
double earnings[4] {1.2e4, 1.6e4, 1.1e4, 1.7e4}; // okay with C++11

Second, you can use empty braces to set all the elements to 0:

1
float balances[100] {}; // all elements set to 0

String

C-style strings have a special feature: The last character of every string is the null character.This character, written \0, is the character with ASCII code 0, and it serves to mark the string’s end.

1
char cat[8] = {'f', 'a', 't', 'e', 's', 's', 'a', '\0'}; // a string!

use a quoted string, called a string constant or string literal, as in the following:

1
char fish[] = "Bubbles"; // let the compiler count

Quoted strings always include the terminating null character implicitly.

Any two string constants separated only by whitespace (spaces, tabs, and newlines) are automatically joined into one.

1
2
3
cout << "I'd give my right ar"
"m to be a great violinist.\n";
// I'd give my right arm to be a great violinist.

The cin technique is to use whitespace — spaces, tabs, and newlines - to delineate a string.

1
2
// Reading String Input a Line at a Time
cin.getline(name, 20); // reads no more than 19 characters, leaving room to the null 

get() leaves newline in the input queue.

1
2
3
cin.get(name, ArSize); // read first line
cin.get(); // read newline
cin.get(dessert, Arsize); // read second line

getline() is a little simpler to use, but get() makes error checking simpler (check if get() return newline).

1
2
3
4
5
6
int year;
cin >> year;
cin.get(); // the newline generated by the Enter key in the input queue
cout << "What is its street address?\n"; 
char address[80];
cin.getline(address, 80);

string Class

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string> 

int main() {
  using namespace std;
  string str1;
  string str2 = "panther";
  cin >> str1; // str1 resized to fit input
  cout << str2;
  cout << "The third letter in " << str2 << " is "<< str2[2] << endl; // use array notation
}

Using a string object both more convenient and safer than using an array.

C++11 String Initialization

1
2
3
4
char first_date[] = {"Le Chapon Dodu"}; 
char second_date[] {"The Elegant Plate"}; 
string third_date = {"The Bread Bowl"}; 
string fourth_date {"Hank's Fine Eats"};

The string class makes some operations simpler than is the case for arrays.

1
2
3
4
5
6
7
string str1;
string str2 = "panther";
str1 = str2; // Assignment
string str3;
str3 = str1 + str2; // Concatenation

int len1 = str1.size();

with character arrays:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstring>

int main() {
  using namespace std;
  char charr1[20] = "penguin";
  char charr2[20];
  strcpy(charr2, charr1);
  char charr3[20] = "buzzard";
  strcat(charr3, charr2);
  cout << charr1 << " " << charr2 << " " << charr3 << endl;
  // penguin penguin buzzardpenguin
  int len = strlen(charr1);
  return 0;
}
1
2
cin.getline(charr, 20);
getline(cin,str);

C++11

1
2
3
4
5
6
7
8
9
10
11
12
13
wchar_t title[] = L"Chief Astrogator"; // w_char string 
char16_t name[] = u"Felonia Ripova"; // char_16 string 
char32_t car[] = U"Humber Super Snipe"; // char_32 string

string stru = u8"你好"; // UTF-8

cout << R"(Jim "King" Tutt uses "\n" instead of endl.)" << '\n'; // raw string
// Jim "King" Tutt uses "\n" instead of endl.

// place additional characters between the opening " and (
// the default delimiters of "( and )" have been replaced with "+*( and )+*".
cout << R"+*("(Who wouldn't?)", she whispered.)+*" << endl;
// "(Who wouldn't?)", she whispered.
1
2
# with c++11
g++ -std=c++11 test.cpp

Structure

structure declaration:

1
2
3
4
5
struct inflatable {
  char name[20]; 
  float volume; 
  double price;
};

Each individual item in the list is called a structure member。

1
2
struct inflatable goose; // keyword struct required in C 
inflatable vincent; // keyword struct not required in C++
1
2
3
4
5
inflatable guest = {
  "Glorious Gloria", // name value 
  1.88, // volume value 
  29.99 // price value
}; // guest is a structure variable of type inflatable

C++11 Structure Initialization

empty braces result in the individual members being set to 0.

1
2
3
// C++11, The = sign is optional
inflatable mayor {}; //  mayor.volume and mayor.price being set to 0
// and all the bytes in mayor.name being set to 0:

Also you can use the assignment operator (=) to assign one structure to another of the same type. Doing so causes each member of one structure to be set to the value of the corresponding member in the other structure, even if the member is an array. This kind of assignment is called memberwise assignment.

You can combine the definition of a structure form with the creation of structure variables.

1
2
3
4
struct perks {
  int key_number;
  char car[12];
} mr_smith, ms_jones; // two perks variables

Another thing you can do with structures is create a structure with no type name.

1
2
3
4
5
struct // no tag 
{
  int x; // 2 members
  int y;
} position; // a structure variable

initializing an array of structs:

1
2
3
4
inflatable guests[2] = {
  {"Bambi", 0.5, 21.99}, // first structure in array
  {"Godzilla", 2000, 565.99} // next structure in array 
};

Bit Fields in Structures

C++, like C, enables you to specify structure members that occupy a particular number of bits. This can be handy for creating a data structure that corresponds, say, to a register on some hardware device.

1
2
3
4
5
6
struct torgle_register {
unsigned int SN : 4; // 4 bits for SN value
unsigned int : 4; // 4 bits unused
bool goodIn : 1; // valid input (1 bit)
bool goodTorgle : 1; // successful torgling
};

Bit fields are typically used in low-level programming.

Union

A union is a data format that can hold different data types but only one type at a time.

That is, whereas a structure can hold, say, an int and a long and a double, a union can hold an int or a long or a double.

1
2
3
4
5
union one4all {
  int int_val;
  long long_val; 
  double double_val;
};
1
2
3
4
5
one4all pail; 
pail.int_val = 15; // store an int
cout << pail.int_val; 
pail.double_val = 1.38; // store a double, int value is lost 
cout << pail.double_val;

The size of the union is the size of its largest member.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct widget {
  char brand[20]; 
  int type; 
  union id {
    long id_num;
    char id_char;
  } id_val;
};
// ...
widget prize;
// ...
if (prize.type == 1)
  cin >> prize.id_val.id_num;
else
  cin >> prize.id_val.id_char;

An anonymous union has no name; in essence, its members become variables that share the same address. Naturally, only one member can be current at a time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct widget {
  char brand[20]; 
  int type; 
  union // anonymous union
  {
    long id_num; // type 1 widgets
    char id_char[20]; // other widgets
  };
}; 
// ...
widget prize;
// ...
if (prize.type == 1)
  cin >> prize.id_num; 
else
  cin >> prize.id_char;

Because the union is anonymous, id_num and id_char are treated as two members of prize that share the same address.

Enumeration

The C++ enum facility provides an alternative to const for creating symbolic constants.

1
enum spectrum {red, orange, yellow, green, blue, violet, indigo};

This statement does two things:

  • It makes spectrum the name of a new type; spectrum is termed an enumeration,
    much as a struct variable is called a structure.
  • It establishes red, orange, yellow, and so on, as symbolic constants for the integer values 0–7.These constants are called enumerators.

By default, enumerators are assigned integer values starting with 0. You can override the default by explicitly assigning integer values.

1
spectrum band = blue;

Only the assignment operator is defined for enumerations. In particular, arithmetic operations are not defined:

1
2
3
band = orange; // valid
++band; // not valid
band = orange + red; // not valid

However, some implementations do not honor this restriction.

Enumerators are of integer type and can be promoted to type int, but int types are not converted automatically to the enumeration type:

1
2
3
int color = blue; // valid, spectrum type promoted to int
band = 3; // invalid, int not converted to spectrum
color = 3 + red; // valid, red converted to int

Again, some implementations do not enforce this restriction.

You can set enumerator values explicitly by using the assignment operator:

1
enum bits{one = 1, two = 2, four = 4, eight = 8};

The assigned values must be integers.

You also can define just some of the enumerators explicitly:

1
2
enum bigstep{first, second = 100, third};
// third would have the value 101.

You can create more than one enumerator with the same value:

1
enum {zero, null = 0, one, numero_uno = 1};

Originally, the only valid values for an enumeration were those named in the declaration. However, C++ has expanded the list of valid values that can be assigned to an enumeration variable through the use of a type cast. Each enumeration has a range, and you can assign any integer value in the range, even if it’s not an enumerator value, by using a type cast to an enumeration variable.

1
2
3
enum bits{one = 1, two = 2, four = 4, eight = 8}; 
bits myflag;
myflag = bits(6); // valid, because 6 is in bits range

The range is defined as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// ...
max_value = max(enum_values);
upper = 2 ^ 0;
while (upper < max_value) {
  upper = upper ^ 2;
}
upper = upper -1; // 127 etc.

min_value = min(enum_values);
if (min_value >= 0) {
  lower = 0;
} else {
  lower = - 2 ^ 0;
  while (lower > min_value) {
    lower = lower ^ 2;
  }
  lower = lower + 1; // -127 etc.
}

The idea is that the compiler can choose how much space to use to hold an enumeration.

C++11 extends enumerations with a form called the scoped enumeration.

Pointer

Three fundamental properties of which a computer program must keep track when it stores data.

  • Where the information is stored
  • What value is kept there
  • What kind of information is stored
1
2
// one strategy for accomplishing these ends
int val = 1;

You just apply the address operator, represented by &, to a variable to get its location.

Pointers and the C++ Philosophy
Object-oriented programming differs from traditional procedural programming in that OOP emphasizes making decisions during runtime instead of during compile time.

TYhe name of the pointer represents the location. Applying the * operator, called the indirect value or the dereferencing operator, yields the value at the location.

1
int * p_updates;

We say that p_updates points to type int. We also say that the type for p_updates is pointer-to-int or, more concisely,int *.

pointer

Traditionally, C programmers have used this form:

1
int *ptr;

This accentuates the idea that the combination *ptr is a type int value. Many C++ programmers, on the other hand, use this form:

1
int* ptr;

This emphasizes the idea that int* is a type, pointer-to-int.