Summary CPP
Summary CPP
C++ Summary
Structures
struct name {
type1 element1;
type2 element2;
...
} object_name;
// instance of name
name variable;
// var. of type name
variable.element1; // ref. of element
name* varp;
// pointer to structure
varp->element1; // member of structure
reached with a pointer
Console Input/Output
C++ console I/O
cout<<
console out, printing to screen
cin>>
console in, reading from keyboard
cerr<<
console error
clog<<
console log
cout<<Please enter an integer: ;
cin>>i;
cout<<num1: <<i<<\n<<endl;
Control Characters
\b backspace
\f form feed
\r return
\ apostrophe
\n newline
\t tab
\nnn character # nnn (octal)
\ quote
\NN character # NN (hexadecimal)
Functions
Passing Parameters by Value
function(int var);
// passed by value
Variable is passed into the function and can be
changed, but changes are not passed back.
Pass by Reference
function(int &var);
// pass by reference
Variable is passed into the function and can be
changed, changes are passed back.
Overloading Functions
Functions can have the same name as long as the
parameters are of different types. The return value
cannot be the only difference.
// takes and returns integers
int divide (int a, int b) {
return (a/b); }
// takes and returns floats
double divide (double a, double b) {
return (a/b); }
divide(10,2); // returns 5
divide(10.0,3.0); // returns 3.33333333
Namespaces
namespace identifier {
namespace-body;
}
namespace
first { int var = 5; }
namespace second { double var = 3.1416; }
int main () {
}
using namespace allows for the current nesting
level to use the appropriate namespace
using namespace identifier;
namespace
first { int var = 5; }
namespace second { double var = 3.1416; }
int main () {
using namespace second;
cout << var << endl;
cout << (var*2) << endl;
return 0;
}
Exceptions
try {
// code to be tried...
statements;
// if fails, exception is set
throw exception; // direct exception generation
}
catch ( type exception) {
// code in case of exception
statements;
}
catch() { }
Inheritance
class Person{
string name;
int birthYear;
public:
Person(string name, int birthYear) {
this->name=name;this->birthYear=birthYear;
}
void print() {cout<<name<<' '<<birthYear<<' ';}
void setBirthYear(int birthYear){
this->birthYear= birthYear;
}
};
class Employee: public Person{
int employmentYear;
public:
Employee(string name, int birthYear,
int employmentYear):Person(name, birthYear){
this->employmentYear= employmentYear;
}
void print(){ Person::print();
cout<<employmentYear<<endl;
}
void setEmploymentYear(int employmentYear){
this->employmentYear=employmentYear;
}
};
Class Syntax
int main() {
class classname {
public:
classname( parms); // constructor
~ classname(); // destructor
type member1;
type member2;
protected:
type member3;
...
private:
type member4;
} objectname;
// instance of classname
public
protected
private
in base classs
protected
private
protected
protected
private
Class Example
class CSquare { // class declaration
public:
void Init(float h, float w);
float GetArea(); // functions
private:
// available only to CSquare
float h,w;
};
void CSquare::Init(float hi, float wi){
h = hi; w = wi; }
float CSquare::GetArea() {
return (h*w); }
// example declaration and usage
CSquare theSquare;
theSquare.Init(8,5);
float area = theSquare.GetArea();
// or using a pointer to the class
CSquare *theSquare=new CSquare( );
theSquare->Init(8,5);
float area = theSquare->GetArea();
delete theSquare;
Class TypeCasting
Templates
Function templates
Definition of a function template:
template <class T>
T GetMax (T a, T b) {
return (a>b?a:b); // return the larger
}
void main () {
int a=9, b=2, c;
float x=5.3f, y=3.2f, z;
c=GetMax(a,b);
z=GetMax(x,y);
}
Class templates
template <class T>
class Pair {
T x,y;
public:
Pair(T a, T b) { x=a; y=b; }
Pair(Pair<T>& p) { x=p.x; y=p.y; }
T GetMax();
};
int main () {
Pair <int> theMax (80, 45);
cout << theMax.GetMax();
return 0;
}
char c;
while(f>>c) // Read while not error
{
cout<<c; // Process c
}
File I/O
Stream Pointers
ofstream f;
// create file handle
f.open(output.txt)
// open file
f <<Hello World\n<<a<<b<<c<<endl;
Deallocate Memory
Syntax: delete pointer; or delete[] pointer;
delete ptr; // delete a single int
delete [] ptr // delete array
Class Reference
Friend Classes/Functions
class CSquare;
// declare CSquare
class CRectangle {
int width, height;
public:
void convert (CSquare a);
};
class CSquare {
// we want to use the
private:
// convert function in
int side;
// the CSquare class, so
public:
// use the friend keyword
void set_side (int a) { side=a; }
friend class CRectangle;
};
void CRectangle::convert (CSquare a) {
width = a.side; // access private member of
height = a.side; // a friend class
}
CSquare sqr;
CRectangle rect;
sqr.set_side(4);
rect.convert(sqr);
// convert can be
// used by the
// rectangle class
Friend Classes/Functions
File Handles
A file must have a file handle (pointer to the file) to
access the file.
Opening Files
After declaring a file handle, the following syntax
can be used to open the file
void open(const char * fname, ios::mode);
fname should be a string, specifying an absolute
or relative path, including filename. ios:: mode
can be any number of the following:
ate
Initial position: end of file
app
Output is appended at the end
trunk
Existing file is erased
binary
Binary mode
in
out
out |
trunc
out |
app
in | out
Binary Files
buffer is a location to store the characters,
numbytes is the number of bytes to written or
read.
write(const char * buffer, numbytes);
read(char * buffer, numbytes);
Output Formatting
streamclass f;
// declare file handle
f.flags(ios_base:: flag) // set output flags
possible flags:
dec fixed hex oct scientific internal left right
uppercase boolalpha showbase showpoint
showpos skipws unitbuf
adjustfield left | right | internal
basefield dec | oct | hex
floatfield scientific | fixed
f.fill()
get fill character
f.fill(ch)
set fill character ch
f.precision( numdigits) sets the precision for
floating point numbers to numdigits
f.put( c)
put a single char into output stream
f.setf( flag) sets a flag
f.setf( flag, mask) sets a flag w/value
f.width() returns the current number of
characters to be written
f.width(n) sets the number of chars to be written
Closing a File
A file can be closed by calling the handles close
function f.close();
Allocate Memory
Syntax: pointer = new type [ size];
int *ptr;
// declare a pointer
ptr = new int;
// create a new instance
ptr = new int [5];
// new array of ints
class CSquare;
// declare CSquare
class CRectangle {
int width, height;
public:
void convert (CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side (int a) { side=a; }
friend class CRectangle;
friend void Change(CSquare s);
};
void CRectangle::convert (CSquare a) {
width = a.side; // the private member side of
height = a.side; // CSquare is accessed here
}
void Change(CSquare s)
{
s.side += 5; // the private member side of
// CSquare is accessed here
}
4.