C++ Summary
· general differences from C:
o using namespace std OR std::
o
const
§ before declaring a
variable -> no change after
initialization
·
this works inside parameters also
§ after a method ->
no change to "this" object's variables
o bool type
o pass by reference
§ & before variable name in method header definition – nothing else
o
definition of constants
§ #define <name to
use in program> <value> :
·
ex: #define NO 0
·
can use this to embed a function:
o
ex: #define sqr(x) ((x)*(x))
§ enum day {SUN = 1, MON, TUE, WED, THUR, FRI, SAT};
·
will start at 1 and end at 7
·
create variable as day mydayvar
o structures
§ define as: struct mydatatype { int x; int y;};
§ create variable as mydatatype mydata;
o
inline functions
o
keyword inline before return type in method header makes it run
faster
o Class structure
class classname (optional : public baseclass -> inherit base public and protected methods and variables)
{
public:
public declarations – anyone can see
constructors:
· function name is classname,
· have no return type
· return an object of the class
·
shortcut: use colon and then either method call or list of
variable(value) comma separated
o
Ex Employee::Employee(string
first) : baseEmp(), fname(first)
· explicitly call constructor of base class
pointer variables or
dynamic memory allocation requires RULE OF THREE :
destructors: function name is ~classname, have no return type and destroy the object it is
called upon
copy assignment: classname& operator =(const classname& orig) build
"this" from orig and return *this.
copy constructor: classname(const classname &orig) – create a new object
functions definition:
· all functions can be overloaded; call will match function name and parms
· can set default values with = : ex: myfunc(int count=10) – 10 is default value if no parm is passed to function.
· access class variables with this-> or (*this). or just the variable name
· use classname::methodname if not inside method
· virtual at beginning means use derived (child's) object's method of the actual object being referenced, not of the variable type. For example, if a shape has a virtual area method and a pointer to a shape holds a triangle, the triangle method will be used.
· overload operators with "operator + " (plus being the operator) instead of method name.
· to use method of actual object type, can dynamically cast to inherited type:
o
dynamic_cast < inherited type
*> pointer to base type
o example: dynamic_cast <HourlyEmployee> a[1]; (where a[1] is a pointer to an Employee that contains a real HourlyEmployee object.
};
More facts on inheritance http://home.adelphi.edu/~pe16132/csc270/assignment/InheritanceFunctioning.html
Access Modifiers:
§ private: only this class with its member functions and friends can see
§ protected: only this class with its member functions and inherited classes and friends can see
§ public: open to everyone
Creating a class variable
· Classname variable; -- default constructor
· Classname variable(constructor variable values) -- constructor
Separate Interface from Implementation:
H file holds classname and all includes, and one time definition control:
·
#ifndef X.H
·
#defineX.H
·
…
·
#endif
CPP file holds single methods:
#include "classname.h"
classname:: before methods from .h or closed class.
Separate main
· Using cin and cout: include <iostream> for io instead of <stdio.h>
o cout :
§ << separates parts
§ endl is new line
§ format flags
· cout.setf(formatter)
o
ios::showpoint
o
ios::fixed
· cout.precision(#)
· cout.width(#) – only applies to the very next variable used.
§ cout.put(char) ex: cout.put('a')
§ cout.putback() – to input stream, not output
o cin:
§ >> separates parts
§ accepts variables, not pointers
§ cin.getline(cstring, max length) OR getline(cin, string, ending char such as '\n')
· stops at and does not include ending char.
§ cin.get(cstring, length) length of 1 default OR
§ cin.peek() returns next
character without removing from stream.
§ cin.ignore() –flushes buffer, Can put a length and char to stop at
· include <cstdlib> for standard features
o exit ()
· Include <cstring> for string functions like in c (same as <string.h>)
o Cannot use std::string as parameters (unless you convert them to cstring first)
o strcpy(s, t) – copies t into s
o strncpy(s,t,n) – copies n characters of t into s
o strcat(s,t) – concatenates t onto the end of s
o strlen(s) – length of s (not including \0)
o strcmp(s,t) – compares the two: 0 if s == t; <0 if s < t, >0 if s > t
· include <cctype> for char type functions like in c
o toupper(c) – returns the character in uppercase as an int – throw into character variable
o isupper(c) – returns true if c is uppercase
o
isalpha(c) – returns true
if c is a letter
o
isdigit(c) – returns true
if c is a digit
o
isalum(c) – returns true
if c is alphanumeric
o
isspace(c) – returns true
if c is a space
o
ispunct(c) – returns true
if c is a printable character other than number, letter or space
o
isprint(c) – returns true
if c is a printable character
o
isgraph(c) – returns true
if c is a printable character other than whitespace
o
iscrtl(c) – returns true
if c is a control character
· include <string> (same as std::string) using namespace std
o = assigns and + concatenates and == tests
o 2 ways to create
§ string str = "a string"
§ string str("a string")
o str.length – returns length as a property
o str[#] – lets you get straight to character index as though it were an array (no protection on out of bounds)
o str.at(#) – returns character in str at I (does have bounds checking)
o str.substr(position, length); - returns substring
o str.insert(position, str2); put str2 into str starting at position
o
str.replace(position, length to
be replaced, replacement string)
o str.find(str1, position) –returns index of str1 in str (position optional)
o str.c_str() – returns a cstring
o
Helpful: getline(cin, str) : std::getline (std::cin,name);
- input up to, not including null from cin to str
· Moving between string types
o
Note: Microsoft MFC also has a
class named CString
o Converting between cstring and string
§ Sample cstring and string:
· char aCString[] = “This is my C-string.”;
· std::string stringVariable; (if using namespace std, can leave off std::)
§ CString to String
· stringVariable = aCString;
· std::string stringVariable2 (aCString);
· NOT: strcpy(stringVariable, aCString);
§ String to CString
·
strcpy(aCString, stringVariable.c_str());
· NOT: aCString = stringVariable;
· NOT: strcpy(ACString, stringVariable);
·
Vectors:
·
dynamic arrays: http://www.cplusplus.com/doc/tutorial/dynamic/
o
define as a pointer to the type, not as an array: int * arr
§ you become
responsible for memory management using malloc/free
or new / delete
§ fixed array would be
int arr[20];
o
add elements with the new keyword, which allocates memory as well
as creating the value:
§ arr = new int [3]; points arr at the start of an array of 3 ints.
§ adds onto heap, not
stack
o
delete memory by using delete on the pointer
§ delete arr deletes arr[0]
§ delete[ ] arr deletes entire arr
§ neither deletes or
even changes the address of the pointer
§ delete what you
create with new
§ don't mix with malloc – free what you malloc
o
proper use
§ myPointer = new int;
§ delete myPointer; // free the memory new int
gave you
§ myPointer = NULL; //move dangling ptr to NULL
o
2D arrays – pointer to pointer:
§ int * * arr2d // make it a 2 *3 array:
§ arr2d = new int[2]; // num rows
§ arr2d[i] = new int[3]; // num cols
·
Exceptions
o
Create a class describing the error
§ inherit from <stdexcept> to get runtime_error
and its "what" method
o
Throw when method finds an error
§ construct an object
of the error class to throw
§ ex: throw NegativeNumber("erasers")
§ If not caught, program
exits
o
Catch class name or base class
§ catch the error classname and provide a name for the variable caught:
§ ex: catch (Exception
&e);
·
File I/O
·
uses streams – fstream, ifstream and ofstream inherit
from iostream
·
library <fstream>
·
ifstream defaults to in (or
specify ios::in)
·
ofstream defaults to out (or
specify ios::out)
·
fstream defaults to i/o (or
specify ios::in | ios::out)
·
open binary with ios::binary
·
open append with ios::app
·
opening the file:
o
Declare a variable of type fstream; then
ask it to open a file
o
Ex:
§
ofstream myfile;
§
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
·
Get status:
o
myfile.is_open() : returns true if
open
o
myfile.eof() : returns true if
file at end and open for reading
o
myfile.bad() : return true if any
read or write fails
o
myfile.good() : opposide of bad
·
File write and read cursor control
|
read (get) |
write (put) |
where |
tellg() |
tellp() |
set |
seekg(position) seekg(offset, direction) |
seekp(position) seekp(offset, direction) |
directions: ios::beg (beginning of file); ios::cur (current position); ios::end
(end of file)
·
binary read and write helper:
o
read (buf, size);
o
write(buf, size);
·
Close when done with myfile.close();