You are on page 1of 2

cout << first::var << endl;

C++ Summary cout << second::var << endl;


return 0;
Inheritance
class Person{
} string name;
Structures using namespace allows for the current nesting int birthYear;
struct name { level to use the appropriate namespace public:
type1 element1; Person(string name, int birthYear) {
type2 element2; using namespace identifier;
this->name=name;this->birthYear=birthYear;
... namespace first { int var = 5; } }
} object_name; // instance of name namespace second { double var = 3.1416; } void print() {cout<<name<<' '<<birthYear<<' ';}
name variable; // var. of type name void setBirthYear(int birthYear){
variable.element1; // ref. of element int main () {
this->birthYear= birthYear;
name* varp; // pointer to structure using namespace second; }
varp->element1; // member of structure cout << var << endl; };
reached with a pointer cout << (var*2) << endl;
return 0; class Employee: public Person{
}
Console Input/Output int employmentYear;
public:
C++ console I/O Exceptions Employee(string name, int birthYear,
cout<< console out, printing to screen int employmentYear):Person(name, birthYear){
cin>> console in, reading from keyboard try { this->employmentYear= employmentYear;
cerr<< console error // code to be tried... }
clog<< console log statements; // if fails, exception is set
cout<<“Please enter an integer: ”; throw exception; // direct exception generation void print(){ Person::print();
cin>>i; } cout<<employmentYear<<endl;
cout<<“num1: ”<<i<<“\n”<<endl; catch ( type exception) { }
// code in case of exception void setEmploymentYear(int employmentYear){
Control Characters statements; this->employmentYear=employmentYear;
\b backspace \f form feed \r return } }
\’ apostrophe \n newline \t tab catch(…) { } };
\nnn character # nnn (octal) \” quote
\NN character # NN (hexadecimal) Class Syntax int main() {
Person p("Garfield", 1965);
class classname {
Functions public:
p.print(); // Garfield 1965
cout<<endl;
Passing Parameters by Value classname( parms); // constructor
Employee e("Ubul", 1964, 1965);
function(int var); // passed by value ~ classname(); // destructor
e.print(); // Ubul 1964 1965
Variable is passed into the function and can be type member1;
return 0;
changed, but changes are not passed back. type member2;
}
protected:
Passing Parameters by Constant Value type member3; Visibility Of Members After Inheritance
function(const int var); ... in base classs
Variable is passed into the function but cannot be private: public protected private
changed inside the function. type member4; inheritance
} objectname; // instance of classname public public protected -
Pass by Reference protected protected protected -
function(int &var); // pass by reference // constructor (initializes variables) private private private -
Variable is passed into the function and can be classname:: classname( parms) { }
changed, changes are passed back.
// destructor (deletes variables) Advanced Class Syntax
Pass by Constant Reference classname::~ classname() { }
Class TypeCasting
function(const int &var); public members are accessible from anywhere reinterpret_cast < newtype>( expression);
Variable cannot be changed in the function. where the class is visible dynamic_cast < newtype>( expression);
Default Parameter Values private members are only accessible from static_cast < newtype>( expression);
int add(int a, int b=2) { members of the same class or of a friend class const_cast < newtype>( expression);
int r; // b is 2, if protected members are accessible from
r=a+b; // no second parameter was given members of the same class, members of the
return r; derived classes and a friend class
} constructors may be overloaded just like any Templates
other function. You can define two identical Function templates
Overloading Functions constructors with difference parameter lists Definition of a function template:
Functions can have the same name as long as the
parameters are of different types. The return value Class Example template <class T>
cannot be the only difference. class CSquare { // class declaration T GetMax (T a, T b) {
public: return (a>b?a:b); // return the larger
// takes and returns integers void Init(float h, float w); }
int divide (int a, int b) { float GetArea(); // functions
return (a/b); } private: // available only to CSquare void main () {
float h,w; int a=9, b=2, c;
// takes and returns floats float x=5.3f, y=3.2f, z;
double divide (double a, double b) { };
c=GetMax(a,b);
return (a/b); } void CSquare::Init(float hi, float wi){ z=GetMax(x,y);
divide(10,2); // returns 5 h = hi; w = wi; } }
divide(10.0,3.0); // returns 3.33333333 float CSquare::GetArea() { Class templates
return (h*w); }
template <class T>
// example declaration and usage class Pair {
Namespaces CSquare theSquare; T x,y;
namespace identifier { theSquare.Init(8,5); public:
namespace-body; float area = theSquare.GetArea(); Pair(T a, T b) { x=a; y=b; }
} // or using a pointer to the class Pair(Pair<T>& p) { x=p.x; y=p.y; }
CSquare *theSquare=new CSquare( ); T GetMax();
namespace first { int var = 5; } };
namespace second { double var = 3.1416; } theSquare->Init(8,5);
float area = theSquare->GetArea();
int main () { delete theSquare;
template <class T> writing, the device is not the console, it is the file. Deallocate Memory
T Pair<T>::GetMax() cout is replaced with the file handle. Syntax: delete pointer; or delete[] pointer;
{ delete ptr; // delete a single int
ofstream f; // create file handle
T ret; delete [] ptr // delete array
f.open(“output.txt”) // open file
ret = x>y?x:y; // return larger
f <<“Hello World\n”<<a<<b<<c<<endl;
return ret;
} Reading From a File (Text Mode)
The operator >> can be used to read from a file. It Class Reference
int main () {
works similar to cin. Fields are separated in the Friend Classes/Functions
Pair <int> theMax (80, 45);
file by spaces. class CSquare; // declare CSquare
cout << theMax.GetMax();
class CRectangle {
return 0; ifstream f("c:\\adat.txt"); // Open file int width, height;
}
public:
How to create a class template from a class: char c; void convert (CSquare a);
• Replace "class Pair" with "template <class while(f>>c) // Read while not error };
T> class Pair" starting the class definition {
cout<<c; // Process c class CSquare { // we want to use the
• Replace the exact type with the template private: // convert function in
}
parameter name within class and method int side; // the CSquare class, so
definitions, eg.: int Q T I/O State Flags
Flags are set if errors or other conditions occur. public: // use the friend keyword
• For methods defined outside the class void set_side (int a) { side=a; }
definition replace The following functions are members of the file
object friend class CRectangle;
int Pair::GetMax() {} Q template <class };
T> T Pair<T>::GetMax() {} handle.bad() returns true if a failure occurs in
• Replace the class name with the class name reading or writing void CRectangle::convert (CSquare a) {
decorated with the template parameters handle.fail() returns true for same cases as width = a.side; // access private member of
wherever the class is used as parameter or bad() plus if formatting errors occur height = a.side; // a friend class
return value: handle.eof() returns true if the end of the file }
Pair(Pair& p) { x=p.x; y=p.y; } Q reached when reading CSquare sqr;
Pair(Pair<T>& p) { x=p.x; y=p.y; } handle.good() returns false if any of the above CRectangle rect; // convert can be
were true sqr.set_side(4); // used by the
rect.convert(sqr); // rectangle class
File I/O Stream Pointers
File I/O is done from fstream, ofstream, and handle.tellg() returns pointer to current location Friend Classes/Functions
ifstream classes. when reading a file class CSquare; // declare CSquare
handle.tellp() returns pointer to current location class CRectangle {
#include <fstream.h> // read/write file when writing a file int width, height;
#include <ofstream.h> // write file to seek a position in reading a file: public:
#include <ifstream.h> // read file handle.seekg( position); void convert (CSquare a);
File Handles handle.seekg( offset, direction); };
A file must have a file handle (pointer to the file) to to seek a position in writing a file: The CSquare class with the friend keyword
access the file. handle.seekp( position); authorizes the CRectangle class and the Change
ifstream infile; // create handle called infile handle.seekp( offset, direction); global function to access its private and protected
ofstream outfile; // a handle for writing direction can be one of the following: members:
fstream f; // handle for read/write ios::beg beginning of the stream class CSquare {
Opening Files ios::cur current position of the stream pointer private:
After declaring a file handle, the following syntax ios::end end of the stream int side;
can be used to open the file Binary Files public:
buffer is a location to store the characters, void set_side (int a) { side=a; }
void open(const char * fname, ios::mode);
numbytes is the number of bytes to written or friend class CRectangle;
fname should be a string, specifying an absolute
read. friend void Change(CSquare s);
or relative path, including filename. ios:: mode
};
can be any number of the following: write(const char * buffer, numbytes);
in Open file for reading read(char * buffer, numbytes); void CRectangle::convert (CSquare a) {
out Open file for writing width = a.side; // the private member “side” of
ate Initial position: end of file Output Formatting height = a.side; // CSquare is accessed here
app Output is appended at the end trunk streamclass f; // declare file handle }
Existing file is erased f.flags(ios_base:: flag) // set output flags
void Change(CSquare s)
binary Binary mode possible flags: {
dec fixed hex oct scientific internal left right s.side += 5; // the private member “side” of
uppercase boolalpha showbase showpoint // CSquare is accessed here
in Reads (file must exist) showpos skipws unitbuf }
out Empties and writes (creates file if it adjustfield left | right | internal
doesn’t exist) basefield dec | oct | hex
out | trunc Empties and writes (creates file if it floatfield scientific | fixed Constructor calling order
doesn’t exist) 1. Calling virtual base class
f.fill() get fill character
out | app Appends (creates file if it doesn’t exist) constructor(s)
f.fill(ch) set fill character ch
in | out Reads and writes; initial position is the f.precision( numdigits) sets the precision for 2. Calling direct, non-virtual base class
beginning (file must exist) floating point numbers to numdigits constructor(s)
in | out | Empties, reads, and writes (creates file f.put( c) put a single char into output stream 3. Constructing own parts
trunc if it doesn’t exist) f.setf( flag) sets a flag a. Setting pointers to virtual
ifstream f; // open input file example f.setf( flag, mask) sets a flag w/value base class parts
f.open(“input.txt”, ios::in); f.width() returns the current number of b. Setting pointers of VFT
ofstream f; // open for writing in binary characters to be written c. Calling constructors of
f.open(“out.txt”, ios::out | ios::binary f.width(n) sets the number of chars to be written aggregated parts
| ios::app); 4. User-defined parts of the constructors
Closing a File Dynamic Memory in C++ Destructor calling order
A file can be closed by calling the handle’s close 1. User-defined parts of the destructor
Allocate Memory 2. Destructor(s) of aggregated
function f.close(); Syntax: pointer = new type [ size]; components
Writing To a File (Text Mode) int *ptr; // declare a pointer 3. Calling direct, non-virtual base class
The operator << can be used to write to a file. Like ptr = new int; // create a new instance destructor(s)
cout, a stream can be opened to a device. For file ptr = new int [5]; // new array of ints 4. Calling virtual base class destructor(s)

You might also like