A Brief Pocket Reference For C++ Programming: Program, 4 ED., And, Thus, It Can Be Considered A Brief Summary of The

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

A Brief Pocket Reference for C++ Programming

This pocket reference was created to help the author to refresh C++-
programming, presumably aiming at an intermediate programmer or advanced.
This pocket reference is mainly based on Deitel & Deitel’s C++: How To
Program, 4th ED., and, thus, it can be considered a brief summary of the
text. It’s free to distribute/modify. Any inquiry should be mailed to
joumon@cs.unm.edu.

o C++
- C++ is a, loosely speaking, OOP language with some data types
such as char, short, int, long, float, double, i.e. a combination
of C and OOP
- C++ has strengthened type-checking
- namespace is introduced

o Compile/Execute
1. edit a source file(s); i.e. at least one file should have
main() function somewhere
2. compile it(them), generating machine code, link, and load
3. execute a binary

ex)
> c++ main.cc
> ./a.out

o Syntax/Semantics/Algorithms
- syntax: grammar
- semantics: meaning
- algorithms: an efficient way to solve a problem

cf. syntax error/semantic error/run-time error or execution error/


debugging

o Basic C++ Program

// preprocessor
#include <iostream>

// namespace
using namespace std;

// typedefs and/or struct


typedef int bool;

// defines
#define PI 3.14

// function declarations come here


...

// class declarations come here


...
// method implementations come here
...

int main(int argc, char ** argv) {


// variables come here
...

// statements come here


...
}

// function implementations come here


...

o Name Space
- namespace is used to define scope, i.e. it is an abstract
container defining context for itentifiers
ex)
using namespace std;

o Constants
- See C-Pocket book for more details
- enum: used to enumerate some predefined data
ex)
enum Status {ON, OFF};
Status s; // cf. enum Status s; in C

o Function
- functions allow to modularize a program
- variables defined inside a function are local
- why functions?
1. divide-and-conquer makes development more manageable
2. software reusability
3. avoiding repeating code in a program
- requires the main function in a program
- use void if a function doesn’t receive any parameters or return
any data
- when a function implementation is made after a caller function,
function prototype, which tells the compiler the name of function,
should be declared
ex)
void foo(int, double); // function prototype
int main() {... foo(); ... }
void foo(int i, double d) { ... } // function implementation

o Storage Class
- auto, register, extern, mutable, static
- auto: local variable for the automatic storage class
- register: advise the compiler to use a register, if available,
and is used for the automatic storage class
- automatic storage class: variables are created when program
execution enters the block in which they are defined, they exist
while the block is active, and they are destroyed when the program
exits the block
- local variables shadow global variables
- static: can retain the value after the function returns to its
caller and used for the static storage class
- extern: global variables belong to this by default and used for
the static storage class
- static storage class
1) variables exist from the point at which the program
begins execution
2) the storage is allocated and initialized once when the
program begins execution
3) the scope of local variables is the block in which they
are defined
- mutable
1) data member is always modifiable, even in a const member
function or const object
2) used for the static storage class
- scope: there’re many scopes defined in C++
1) function scope: labels are the function scope, i.e. can
be used anywhere in the function, but cannot be referenced
outside the function: goto and switch
2) file scope: identifiers have the file cope if they are
defined outside any function, but their scope is through the
end of the file: global variables, function definitions, and
function prototypes
3) block scope: identifiers defined in a block has block
scope, i.e. valid only inside the block, but can be shadowed
by a nested block: local variables and parameters
4) function-prototype scope: identifiers used in the
parameter list in a prototype, i.e. the compiler ignores the
identifier and the identifier can be reused elsewhere
5) class scope, i.e. class data members and class data
functions belong to this: no member functions are file
scope, class members are immediately accessible by all of
that class’s member functions and can be referenced by name,
and class members are accessed through one of the handles of
an object, outside’s class scope
6) namespace scope
- linkage: determine whether an identifier is known only in the
current source file or in any file with proper declarations
- recursion is allowed, and it can be converted to iteration or
vice versa

o Inline Function
- inline: used to advise the compiler to generate a copy of the
function’s code in place, when appropriate, to avoid a function
call
- used for small functions and can be ignored by the compiler
ex)
an inline function

#include <iostream>
using namespace std;

inline void hello(void) {


cout << “Hello, world!”;
}

int main() {
cout << “Wow, “ << hello();
cout << endl;
return 0;
}

o Pass-by-reference
- C++ supports pass-by-reference as well as pass-by-value
- use & operator
- need to be initialized when declared, i.e. it’s an error
otherwise

#include <iostream>
using namespace std;

void change (int &);


int main() {
int i = 3;
int j = 5;
int &x = j;
//int &y; // error
cout << i << endl; // i is 3
change(i);
cout << i << endl; // i is 5
cout << x << endl; // x is 5
return 0;
}

void change (int & i) {


i = 5;
return ;
}

o Default Arguments
- can specify default arguments
- if an omitted argument is not the rightmost one, then all
arguments to the right of that argument also must be omitted
ex)

#include <iostream>
using namespace std;

void foo(int i = 1, double j = 1.0, char c = ‘ ‘);


int main() {
cout << foo(2) << endl; // set i
cout << foo(2, 3.0) << endl; // set i & j
cout << foo(2, 3.0, ‘a’) << endl; // set i, j, & c
return 0;
}

void foo(int i, double j, char c) {


return c + i * (int) j;
}

o Unary Scope Resolution Operator


- use :: to access a global variable when a local variable shadows
the global one
ex)
const double PI = 3.14;
...
void foo(void) {
float PI = static_cast<float> ::PI;
cout << :: PI <<endl;
return;
}

o Function Overloading
- C++ enables several functions of the same name to be defined, as
long as the functions have different sets of parameters
- type-safe linkage ensures that the proper overloaded function is
called and that the types of the arguments conform to the types of
the parameters

o Array
- if the array size is omitted, then the compiler determines
- array is simulated pass-by-reference when passed to a function
as a parameter
- use const if you want no modification to an array, i.e. it’s a
compiler error if any medication is made
- in practice, pass the array size together with an array
- multi-dimension arrays are allowed

o Precedence Rules

unary :: () [] -> .
++ -- static_cast<type>(operand)
++ -- + - ! & *
binary (arithmetic) * / %
+ -
binary (shift) << >>
binary (relationship) < > >= <=
binary (equality) == !=
binary (logics) &
^
|
&&
||
tenary ?:
assign = += -= *= /= %= >>= <<= &= ^= |=
list ,

- unary > binary (asrel) > tenary > assign > list

o Pointer
- contain memory address
ex)
int x = 3;
int * xptr;
xptr = &x;
*xptr = 1; // x is 3 and *xptr is 3
- when passing a pointer to a function
1) nonconstant pointer to nonconstant data, i.e. data can be
modified by dereferenced pointer and pointer can be modified
to pointer to other data: never include const
ex)
void foo(char *) { ... }
int main() {
char str[] = “hello”;
foo(str);
...
}
2) nonconstant pointer to constant data, i.e. data cannot be
modified but pointer can be modified to point to other data
ex)
void foo(const int * i) { *i = 3 } // error when modifying i
int main() {
int x = 5;
foo(&x);
...
}

3) constant pointer to nonconstant data, i.e. pointer always


points to the same location, but the data at the location
can be modified
ex)
int main() {
int x = 5;
int * cont xptr = &x;
int y = 10;
xptr = &y; // error
...
}
4) constant pointer to constant data, i.e. pointer points to
the same location and the data at the location cannot be
modified
ex)
int main() {
int x = 5, y;
const int * const ptr = &x;
*ptr = 7; // error because *ptr is const; no new
//value
ptr = &y; // error because ptr is const; no new
//address
- for more pointer operations, see C Pocket-book

o Function Pointer
- a pointer to a function contains the address of the function in
memory
- for more function pointers, see C Pocket-book

o Const
1. const int x = 96; // x needs to initialize when declared, i.e.
// x is an integer constant
2. const int * x; // x: a variable pointer to a constant integer
3. int const * x; // same as 2
4. int * const x; // x: a constant pointer to a variable integer
5. const int * const x; // x: a constant pointer to a constant
integer
6. int const * const x; // same as 5
7. const char * foo(); // cannot modify the return value of foo()
8. class aClass {
int aMember;
...
void aMethod() const;// doesn’t allow aMethod() to modify
// class variables
...
}
9. const aClass x(...); // x: a constant object of aClass class
10. class aClass {
const int aMember; // need to be initialize in constructor
...
...
}
aClass::aClass(..., int x)
: aMember(x) { // aMember: a constant member
...
}

o String
- array of characters
- by default, the access type is public

o Structure vs Class
- structure: aggregated data type
ex)
Struct foo {
int x;
int y;
}
...
int main() {
foo f;
f.x = 3;
f.y = 4;
...
}
- class: models objects that have attributes/actions
ex)
class foo {
public:
foo(); // constructor
~foo(); // destructor
int getX(); int getY();
void setX(int); void setX(int);
private:
int x;
int y;
};

foo::foo() { x = y = 0;}
int foo::setX(int x) {this->x = x;}
int foo::getX() { return x;}
...
int main() {
foo f;
f.setX(3);
f.getX();
...
}
- member functions can be overloaded
- if a local variable shadows a class data member, then the class
data member can be accessed by ::
- by default, the class access type is private
- private: can be accessed by member functions and friends
- public: may be accessed by any function in the program that
holds a handle on an object of that class
- make helper functions private
- it’s poor and dangerous for a member function to return a
reference type
- the assignment operator(=) can be used to assign an object to
another object of the same type; i.e. such assignment is performed
by memberwise assignment
- can have other objects as member fields

o Constructor
- used to initialize an object
ex)
class foo {
foo(int = 0, int = 0); // default constructor
...
int x; int y;
};

o Destructor
- destroyed when program execution leaves

o Friend Function/Class
- a friend function of a class is defined outside that class’s
scope, yet has the right to access the non-public member of the
class
- stand-alone functions or entire classes may be declared to be
friends of another class
- can enhance performance
ex)
class aClass { ... };
class anotherClass { friend class aClass;...}; // makes
// all functions of anotherClass as friends of class aClass

ex)
class foo {
friend void set(foo &, int);

public:
foo()
:x(0)
{}

void print () const { cout << x << endl;}


private:
int x;
}

void set(foo &f, int x) // error if set() is not a friend


{ f.x = x; }
int main() {
foo f;
f.print();
set(f, 3);
...
}

o This Pointer
- every object has access to its own address through this
- this is declared const; for nonconstant member function of class
foo, the this pointer has type foo * const, but for constant
member function of the class foo, this pointer has the data type
of const foo * const
ex)
this->member;
(*this).member;
return (*this); // for conscading such as foo.x().y()....z()
- every non-static member function has access to this

o Dynamic Memory (De)Allocation


- use new and delete
ex)
foo * f = new foo(); // allocate
delete f; // deallocate

o Static Class Member


- static class variable is shared among all objects
- each static member must be initialized once at file scope
- public static member function must be provided to access static
member variables
ex)
class foo {
public:
foo();
~foo();
void print() const;
static int count();
private:
static int x;
}

...
int foo::x = 0; // initialize
int foo::count() {
retrun x;
}
foo::foo() { ++x; }
~foo::foo() {--x; }
...
int main() {
foo f;
foo g;
cout << foo::count() << endl; // usage
delete f;
cout << foo::count() << endl; //usage
...
}

o Data Abstract/Information Hiding


- information hiding: to hide implementation details from the
clients of the classes
- data abstraction: to describe functionality of a class
independent of its implementation

o Operator Overloading
- most C++ operators can be overloaded, but precedence cannot be
changed by overloading
- when overloading (), [], -> or any of the assignment operators,
they should be declared as class members; others can be declared
non-member functions
- leftmost (or only) operand should be an object of the operator’s
class, and, otherwise, overloading function should be declared non-
member function
- non-member overloading should be friend
ex)
class foo {
friend ostream& operator<<(ostream&, const foo&);
friend istream& operator>>(istream&, foo&);
private:
int x;
};
ostream& operator<<(ostream& output, const foo&f) {
output << f.x ;
return output;
}
istream& operator>>(istream& input, foo&f) {
input >> f.x;
return x;
}
int main() {
foo f;
...
cin >> f;
cout << f;
...
}
- unary operator can be overloaded as a non-static member function
without argument or a non-member function with one argument

o Inheritance
- base/derived class
ex)
class Student : public Person { ... };
- public inheritance: private members are not accessible directly
from the derived class, even though private members are inherited
- friend functions are not inherited
- private members are accessible only within the body of the base
class and the friends of the base class
ex)
public foo {
public:
foo() {x = 0;};
~foo();
void set(int y) { x = y;}
private;
int x;
}

public goo: public foo {


public:
goo();
~goo();
void set(int);
private:
int y;
}
...
goo::goo()
:foo(0) { // use foo’s public constructor to set x
//x = 0; // error because x is private in foo
y = 0;
}
...
- protected: can be accessed by members and friends of the base
class and by members and friends of any classes derived from the
base class

o Polymorphism
- invoking base-class functions from derived-class object
ex)
class foo {...};
class goo: public foo { ... };
// assume foo and goo have print() and goo overrides

...
int main() {
foo f;
foo * fptr;
goo g;
goo * gptr;

f.print(); // calls foo’s print()


g.print(); // calls goo’s print()
fptr = &f;
fptr->print(); // calls foo’s print()
fprt = &g;
fprt->print(); // calls foo’s print()
...
}
- aiming derived-class pointers at base-class objects
ex)
same as the previous example
...
foo f; goo g;
goo * gptr;
//gptr = &f; // error because foo is not goo
- derived-class member function calls via base-calls pointers
ex)
same as the previous example
...
foo f; goo g;
foo * fptr;
fptr = &g;
fptr->print(); // calls foo’s print()
//fptr->printGoo(); // assume printGoo() is goo’s method
// then, it’s an error

o Virtual Functions
- the type of the object being pointed to, not the type of the
handle, determines which version of a virtual function to invoke
ex)
same as the previous example, but change as follows:
public foo {
...
virtual void print() const; // virtual function
...
}
public goo: public foo {
...
virtual void print() const; // virtual function
...
}
...
f.print(); // calls foo’s print()
g.print(); // calls goo’s print()
fptr = &f;
fptr->print(); // calls foo’s print()
fptr = &g;
fptr->print(); // calls goo’s print(); polymorphism

o Abstract Class
- class that will never be instantiated can provide an appropriate
base class from which other derived class can inherit
- class is made abstract by declaring one or more of its virtual
functions to be pure, where pure virtual function is one with an
initializer of = 0 in its declaration
ex)
virtual void print() const= 0;
- pure virtual functions normally don’t provide implementations
- every derived class must override and implement all virtual
functions
- we cannot instantiate abstract class, but can use it to declare
pointers and references that can refer to objects of any concrete
classes derived from the abstract class

o Template
- when overloading is used, if the program logic and operations are
identical for each data type, then function template can be used
ex)
a template example
template <class T> // or template <typename T>
T max(T u, T v) {
if (u > v) return u;
else return v;
}

int main() {
max (1, 2);
max (1.0, 2.0);
max (‘a’, ‘b’);
return 0;
}

- class template can also be used


ex)
template <class T>
class foo {
public:
foo(const T&, const T&);
~foo();
T max(const T&, const T&);
private:
T x;
T y;
};

template <class T>


foo<T>::foo(const T& xval, const T& yval) {
x = xval; y = yval;
}
...
int main() {
...
foo<double> f(1.0, 2.0);
...
}
- also possible to use nontype parameters, which can have default
arguments and are treated as consts
ex)
template <class T, int k>; //nontype parameter
...
foo<double, 10> f(1.0, 2.0); // used to instantiate a
10-//element foo class template specialization of double
values
- a type parameter can specify default type
ex)
template<class T = double>;
- class template can be derived from a class-template
specialization
- class template can be derived from a non-template class
- class-template specialization can be derived from a class-
template specialization
- non-template class can be derived from a class-template
specialization

o Miscellaneous Functions/Libraries/Features
- iostream/iomanip/cstdlib/...
- fixed()/showpoint()/setprecision()/setw()/rand()/cin.get()/...
- input/output streams
- exception handling uses try {} catch() {} blocks
- CGI
- STL

You might also like