Anda di halaman 1dari 15

C++ Quick Guide v 0.

91
Adam Grossman <adamtg@metashadow.com>

Class e!inition
class <class name> [: <access level1> <base class name>] { [<access level2>:] [explicit] <class name>([<arguments>]) [: <variable name>(<value>)>,]; //constructor [friend <class name>|static] <type> <variable name>; // variable [friend <class name>|static|virtual] <return type> <metho name>([arguments]) // method - inline ! // function body " [friend <class name>|static|virtual] <return type> <metho name>([<arguments>])[=0]; // method - prototype [friend <class name>;] [virtual] ~<class name>(); ## estructor <type> operator<operator>([argument]); }; // defining a method if only prototype is declared in class <class name>::<metho name>([<arguments>]) { // function body }

class declaration
"ield
<class name> <access level1>

#ur$ose name of class

%alue& escri$tion any legal variable name

controls access level of base public: access levels from base class remain the same class to anything the uses protected: public members become protected derived class private: public and protected members become private

class de!inition
access "ield
<access level2>

#ur$ose controls member access for anything using class

%alue& escri$tion There can be as many access level sections in the class as needed, even the multiple sections of the same access level. The deffault level is private.
public: unrestricted access protected: only accessible by derived class private: only accessible by the class itself

constructors NOTE: A base class's constructor is always called before the derived class's constructor. f the base class needs an

arguments to the constructor, include the parent class constructor in the initiali!ation list NOTE: f the constructor's single argument is of the same type as the class, and the constructor uses that ob"ect to ma#e a copy of it for the newly created ob"ect, it's called a copy constructor. f the single argument is of a type other then the class itself, and it is used to convert the argument type to a new ob"ect of the constructor's class type, it's called a conversion constructor. "ield
explicit

#ur$ose

%alue& escri$tion

forbids the constructor to be n order to use the constructor, it must be e$plicitly called. This used for an implicit avoids inadvertently copy constructors to be called. conversion Name of constructor arguments constructors always are the same name as the class follows standards % rules, e$cept for one e$ception. n the method declaration, a default value can be given. The default argument must always start at the first argument, and move right without any non&default arguments between defaulted arguments. nitiali!es member variables outside of the constructor body. These can only initiali!e ob"ect members, not class members 'members declared as static(

<class name> <arguments>

<variable name>(<value>)>

nitiali!ation list

mem'er varia'le declaration (see )!riend* section on the )!riend* o$tion+, "ield #ur$ose %alue& escri$tion
static

ma#es member variable a class member

%lass does not need to instantiated to be accessed. This would be e)uivalent to creating a global variable within a namespace named *class name+. The same variable is accessed, whether it is referenced from an ob"ect or not. follows standard % rules

<type> <variable name>

variable declaration

mem'er method declaration (see )!riend* section on the )!riend* o$tion+, "ield #ur$ose %alue& escri$tion
static

ma#es method a class method

%lass does not need to instantiated to be accessed, therefore there can not be a ,this- variable sent for methods. This would be e)uivalent to creating a global within a namespace named *class name+. The same function is accessed, whether it is referenced from an ob"ect or not. f a pointer of the type base class points to a derived class, the derived class method will be called. n other words, it's not the pointer type which determines the class, but the class the pointer is actually pointing to. f the base class is methods are declared virtual, the derived classes do not to declare it's methods as virtual. As long as the base is declared virtual, those members are considered virtual all the way down the hierarchy. follows standard % rules follows standards % rules, e$cept for one e$ception. n the method declaration, a default value can be given. The default argument must always start at the first argument, and move right without any non&default arguments between defaulted arguments. That means the method is "ust declared, but not defined. A class with even single pure virtual function can not be instantiated and must have a derived class which defines the every pure virtual

virtual

Allows polymorphism

<return type> <metho name> <arguments>

method fingerprint arguments

=0

this ma#es the function a pure virtual function 'must be used with virtual(

function

!riend "ield
friend <class name> [<member>]

#ur$ose

%alue& escri$tion

allows outside classes access gives the class name *class name+ access to the member, to class regardless of it's access level 'if the member is public, it has no effect(. f no member is given, the *class name+ has access to all of the class's private and protected members

o$erator overloading This allows operators to be overloaded to common operators '.,&,/0, etc( can be used in a class, hopefully to ma#e the class more intuitive for the user of the class. 1or binary operators, it's the left side operand which ma#es the call. 1or unary operators, the ob"ect that ma#es the call is based on the operator type.

"ield
<type>

#ur$ose the result of the operator

%alue& escri$tion 2ased on the operator. if the operator is '3', a bool type would be e$pected, if the type is '.', the type would be the operator's class to be returned Any legal c.. operator, including '.','&','/0', etc. NOTE: Operators li#e '.' and '.3' are considered different operators. 4ee below for prefi$5postfi$ operator notes.

<operator>

operator being overloaded

([argument])

1or binary operators, the Any class or built&in type. right side operand is the argument. 1or unary operators, it's determined by the operators purpose.

#re!i-&#ost!i- o$erator overloading n order to detemine whether the pre& or post& fi$ operator is used, the following convention is used
<type>$ operator++(); //prefix { // incre ent !hatever needs to incre ented return "this; } <type> operator++(int); //postfix { #t$pe% te p&ob' = "this; // incre ent !hatever needs to be incre ented in this class return te p&ob'; }

destructor NOTE: destructors are called from the derived class first, then the base class "ield #ur$ose
virtual

%alue& escri$tion behaves "ust li#e a virtual method, e$cept the base class destructor will be called. 2ut if the destructor is not

allows polymorphism

declared virtual, and the class is destroyed via a pointer to the base class, the derived class's destructor will not be called.
~<class name>()

cleans up class

destructors are always the same name as the class and never has any arguments

.ethod overloading&overriding 6ethods can either can either be overloaded 'used for methods with common name in the same class( or overridden 'used in inheritance(. Overloading5overriding is based the methods signature, which is the methods name and arguments. The return value is not part of the methods signature. /verloading /verridding 6ethods in the same class share the same name, but have different arguments. 6ethod has the same signature has a method in it's base class. The method in the derived class will be called. f the base call and derived class have the same name, but different arguments, it is functionally similar to having overloaded methods in the derived class

iostream
stdin. stdout0 stderr writing to stdout5stderr stream:
(include #iostrea % std::)cout*stderr+ ## <stu%% output>| std::endl [## <stu%% to ouput>| std::endl];

"ield
std::)cout*cerr+ ## stu%% output std::endl

#ur$ose stream ob"ect for stdout and stderr ,pushes- stream to the ob"ect 7ata to be outputted output manipulator

%alue& escri$tion ostream 'no nead to instatiate cout or cerr ob"ects( overloaded bit&wise operator This can be any type of value which supports output, such as built&in types, strings, etc. EO8 and flush

cin read in data from stdin


(include #iostrea % std::cin %% <variable>;

NOTE: std::cin's return value evaluates to false in two situations. t read an EO1 or the incoming stream contains date that is not a legal value for variable.

"ield
std::cin %% variable

#ur$ose stream ob"ect for stdin ,pushes- stream to the variable variable to hold incoming stream

%alue& escri$tion ostream 'no nead to instatiate cout or cerr ob"ects( overloaded bit&wise operator the data in the stream, as long as it is of a compatible type 'integer values being read in for an int variable, etc.(

"ile 1&/ There are three file stream ob"ects


fstrea ifstrea ofstrea

allows reading and writing to a file allows "ust reading from a file allows "ust writing to a file

All three basically behave the same, "ust and are more restrictive. This allows a stream ob"ect to be passed to a method while having compile time chec#ing to ma#e sure the right stream direction ob"ect is being passed. o$ening a !ile NOTE: The arguments in ,ile-open can also be used for the "fstrea NOTE: Only certain modes are valid for certain file stream ob"ects constructor.

(include #fstrea % )fstrea *ifstrea *ofstrea + ,ile;

,ile-open(char &%ilename' int mo e)

"ield
)strea *ifstrea * ofstrea + ,./0-open char &%ilename

#ur$ose stream ob"ect method for opening a file file to open modes to open file

%alue& escri$tion a file stream ob"ect

standard % string 7efaults modes:


fstrea : ios::in * ios::out ifstrea : ios::in ofstrea : ios::out

int mo e

4ee table below for modes

.ode
ios::in ios::out ios::app ios::ate ios::trunc ios::binar$

escri$tion Open file to read Open file to write All the data you write, is put at the end of the file. t calls ios::out All the date you write, is put at the end of the file. t does not call ios::out 7eletes all previous content in the file. 'empties the file( Opens the file in binary mode.

checking !or error a!ter o$ening !iles, Two ways: 9. *fstream ob"ect+.open(---) return values evaluates to false :. *fstream ob"ect+-fail() evaluates to false 'useful for when file is opened in constructor( close !ile, *fstream ob"ect+.-close(); 'do not thin# there is a need to elaborate( in$ut methods
,ile %% <value>; //reads one word at a time, does include EOL ,ile-1etch(<char>); //reads one char at time ,ile-1etline(char "strin1,int len1th); //reads

ax at least length chars

out$ut method
,ile ## <value>; //reads one word at a time, does include EOL

,ile-putch(<char>); //write one char at time ,ile-!rite(char "string'int length); //reads

ax at least length chars

Casting
All casts are in the form of:
"&cast#<target(type>%(<source expression>)

cast t2$e
static&cast

e-am$le
int i; %loat %; %)static(cast<%loat>(i);

escri$tion& escri$tion 8i#e a % type cast. 7oes bi&directional pointer casting between base classes and derived class, but does not do safety chec#s, "ust ma#es sure they are compatible 'which means incomplete types can be casted( Alters the const&ness of an e$pression

const&cast

const char &s1)*hello*; char &s2; s2)const(cast<char &>(s1); +ase &b; ## non,polymorphic -erive & ; ## erive %rom +ase ) ne. -erive (); b) ynamic(cast<+ase &>(b);

d$na ic&cast

Only used with pointers and references to ob"ects. 1or non&polymorphic classes, can only case from derived to base class. f the class is polymorphic, the casting can be done in either direction, and verifies that the resulting ob"ect will be a complete ob"ect. <eturn N=88 on failure. 2lindly casts pointers. There is no safety chec#ing, so unrelated classes can be casted that will cause runtime errors when the pointer is dereferenced.

reinterpret&cast /lass0 &a; /lass+ &b; ## a completely unrelate class b)reinterpret(cast</lass+ &>(a);

Const 3andling
2asically >const? applies to whatever is on its immediate left 'other than if there is nothing there in which case it applies to whatever is its immediate right(. E$ample
const int & /onstant2 int const & /onstant2 int & const /onstant1 int const & const /onstant2 class 0 ! int %unc() const; "

7escription 7eclare that 2onstant3 is variable pointer to a constant integer 7eclare that 2onstant4 is constant pointer to a variable integer 7eclare that 2onstant5 is constant pointer to a constant integer. Adding a const to the end of a method guarantees that no member variables will be altered in the function call.

4em$lates
6echanisms for generic types. The entire template 'declaration and implementation( must be inside a header file, because it re)uires a recompilation every time it is used, unli#e a standard library
te plate # )(class | typename) i enti%ier [) e%ault][' [(class|typename) i enti%ier [) e%ault]]&]& | [int variable[) e%ault][']]&% [%unction eclaration | class eclaration]

"ield
te plate (class | typename) i enti%ier = e%ault

#ur$ose identifies function or class will use a template

%alue& escri$tion

prepends the template identifier class or value can be used. they both behave e$actly the same way name which will reference the parameter type any valid variable name

if no type is given, this type will any valid type be used non&type parameter allows multiple parameter types in a single template declaration instead of a type being set at compile, and constant integer value can be set

[int variable[) e%ault]['] [' [(class|typename) i enti%ier[) e%ault type]]&]

"unction 4em$late 4tandard function overloading applies, including overloading between template and non&template functions.
"unction 4em$late 5-am$le

template <class 3> 3 %unction(3 x) ! x44; return x; " int i'5; char x'y; i)1; x)1; 5)%unction(i); ## type is in%erre by argument x)%unction<char>(c); ## type is explicitly set

Class 4em$late
Class 4em$late 5-am$le

template <class 31' class 32> class /lass0 ! 31 x; 32 y; 31 get6(); voi set7(32 in7); ";

template <class 31' class 32> 31 ! return x; " template <class 31' class 32> voi ! y)in7; " ## class must be eclare /lass0<int' %loat> c; int x; x)c8get6(); c8set7(1892);

class0<31'32>::get6()

class0<31'32>::set7(32 in7)

.ith types explicitly set

6$eciali7ation Allows the overriding of the default template implementation for a certain type. n a speciali!ed template, the same methods do not need to be implemented, each can have it's own set of methods, but speciali!ed class will not inherit any undefined methods from the generic template.

te plate #<stan ar being speciali:e >

template types i enti%ier> "% class <name o% class

te plate <> class <name o% class being speciali:e > #<type>% "ield
te plate #<stan ar template types i enti%ier>% <> <name o% class being speciali:e > #<type>%

#ur$ose identifies function or class will use a template same synta$ as a standard template identifier identifies as an e$plicit type speciali!ation identifies the class being speciali!ed the type that that this template will be speciali!ed

%alue& escri$tion

alias for type

any valid class name any valid type

6$eciali7ation 4em$late 5-am$le

## stan ar template <class 3> class /lass0 ! 3 x(; voi set(3 x); "; template <class 3> voi ! x()x; " class0<3>::set(3 x)

##template to han le pointer ## ;<3=: 3 is not a pointer type8

3his syntax 5ust

## allo.s template speciali:ation %or to han le pointers ## i% they nee to be han le i%%erently template <class 3 &> class /lass0 ! 3 x(; voi set(3 &x); "; template <class 3> voi ! x()&x; " class0<3>::set(3 &x)

##template to han le speci%ic type template <> class /lass0 <char &> ! char &x(; voi set(char &x); "; voi class0<char &>::set(char &x) ! ## assuming x( .as allocate strcpy(x('x); "

some.here else888

5-ce$tions
E$ceptions allow for runtime errors to be handled and control be based to an error handler without any e$plicit return value chec#s for every call. The basic setup for a e$ception handling is the thro!6tr$6catch bloc#
tr$ { [thro! #ob'ect% | %unction .ith thro! #ob'ect%] } (catch (<[---| type variable]>) { })4

f there is nothing catch a thrown e$ception, the program will abort. "ield
tr$

#ur$ose

%alue& escri$tion

mar#s the beginning of the bloc# which any legal code will ta#e a thrown e$ception and pass it to the catch bloc#s the ob"ect being thrown is what will be caught by the catch bloc#s. The thro! can be e$plicitly in the tr$ bloc#, or it can be in in any function called within the tr$ bloc# any legal ob"ect5type

thro! ob5ect

catch (<[---| type variable]>)

one or more bloc#s to catch the thrown the body of catch is any legal code e$ceptions. each catch has a type it can catch. The catches will try each catch in order, trying to match the thro!n type to the catch argument ,so ideally, the catches should be placed in order of most specific to least specific. ,@- means it will catch any type, but there will not be any argument associated with it. , type variable* is a any legal type and any legal variable name.

8ethrowing an e-ce$tion f a catch does not want to handle an e$ception or wants to have the ne$t level also handle the e$ception, it can be rethro!n , simply by calling thro! with no argument. The e$ception will be thrown down to the previous level. n this e$ample, the catch with the int argument in main will actually handle the e$ception.
8ethrowing e-am$le

int level(2() ! st ::cout << >?evel 2> << st ::en l; thro. 19; " int level(1() ! st ::cout << >?evel 1> << st ::en l; try !

level(2(); " catch (char c) ! st ::cout << >?1: =rror type char: > << c << st ::en l; " catch (888) ! thro.; " " int main() ! try ! level(1(); " catch (int i) ! st ::cout << >@ain: =rror type int: > << i << st ::en l; " catch (char c) ! st ::cout << >@ain: =rror type " " e%ault> << st ::en l;

5-ce$tion 6$eci!ier 1unction specifiers specify what type of e$ceptions 'if any( a function, or a function it calls can throw. A function without a function specifier can throw any #ind of e$ception. 9/45, the e$ception specifier is not part of the function signature %unction thro!([types']&) "ield
%unction thro! [types']&

#ur$ose function prototype or declaration signifies an e$ception specifier list of A or more types of e$ceptions that can be thrown. f A types are listed, then the function will not throw any e$ceptions.

%alue& escri$tion any valid function any valid type

6tandard 5-ce$tions There are some standard e$ception classes which are used by the %.. 4tandard 8ibrary. They are derived from the e-ce$tion base class. 5-ce$tion Class
ba (alloc ba (cast

escri$tion thrown by the ne! operator when storage space can not be allocated thrown by dynamicBcast when the casted ob"ect would be

incomplete
ba (exception ba (typei logic(error (an runtime(error (an ios(base::%ailure itAs itAs erive erive classes) classes)

thrown when a function throws an e$ception that violates the e$ception specifier thrown when t$peid is given a N=88 pointer value thrown when a logic error occurs which could be detected by reading the code. thrown when a error occurs that could not have been detected by reading the code,. base class for iostrea classes

:icense This wor# is licensed under a %reative %ommons Attribution&Noncommercial&No 7erivative Cor#s D.A =nited 4tates 8icense.

ocument Changes

7ate AF5:G5AH AF5DA5AH

Eersion A.A9 A.A:

Name Adam Irossman *adamtgJmetashadow.com+ Adam Irossman *adamtgJmetashadow.com+

%hange nitial <elease Added in: Eersion K in title 5O operator overloading const's casting T27 section Added n: 1illed in constructor information 1i$ed: errors in cast code samples Added in: templates %hanged formating of code frames 1inished: Templates Added in: E$ceptions This will be the first official ,beta- release

AF5DA5AH AG5AL5AH 9A59D5AH

A.AD A.AM A.AL

Adam Irossman *adamtgJmetashadow.com+ Adam Irossman *adamtgJmetashadow.com+ Adam Irossman *adamtgJmetashadow.com+

9A5:95AH

A.H

Adam Irossman *adamtgJmetashadow.com+

9A5:95AH

A.H9

Adam Irossman *adamtgJmetashadow.com+

Added license

Anda mungkin juga menyukai