G52CPP
Lecture 1 & 2
Header
|
reference 省去 copy的过程
What is usually in a header file?
- Function declarations
- Macro definitions (#define)
- Constant definitions
- Possibly other things as well
- Ensure that the header file #includes everything that it needs itself
- Ensure that it doesn’t matter if the header file is #included multiple times
- Ensure that header files can be included in any order
#include
Replaces this statement by the text of the specified file- Java’s
import
Sizes of types
- A minimum size (bits): char 8(1 byte), short 16(2 byte), long 32(4 byte)
- Relativesizes: char <= short <= int <= long
bool and inttype
- bool : true / false (C++ only, not C)
- IMPORTANT:
bool
andint
can be converted implicitly / automatically to each other- true defined to be 1 when converted to int
- false defined to be 0 when converted to int
- 0 is defined to be false, non-zero as true
In both C and C++ any integer types can be used in conditions (i.e. char, short, long, int)
123456 int x = 6;while ( x ){printf( "X is %d\n", x );x -= 2;}
|
|
#ifdef WINDOWS
… windows code here …
#elif SYS5UNIX
… System 5 code here …
#endif
#ifndef UNIQUE_DEFINE_NAME_FOR_FILE
#define UNIQUE_DEFINE_NAME_FOR_FILE
… include the rest of the file here …
#endif
char c1 = ‘h’;
char pc2 = &c1;
int pi4 = (int*)pc2;
char c1 = ‘h’;
char pc2 = &c1;
printf(“%p “,(void)pc2);
printf(“%p\n”,(void*)&c1);
|
|
注意分号!
Use .
to access struct members
The heap and malloc()
malloc()
returns a void*
|
|
Positioning of struct elements
#pragma
struct
may get empty space in them- To align members for maximum speed
-#pragma
means a compiler/operating system specific pre-processor directive
- `#pragma pack(1)` it will save space but will speed down
union
- Elements of unions are in the SAME place
- Elements of unions may be different sizes
- A union is as big as the biggest thing in it
- Unions are a way of providing different ways of looking at the same memory
Lecture 7
classes vs structs in C++
- Everything you do with a
class
in C++ could also be done with astruct
The difference is (ONLY!!!) in encapsulation
struct defaults to public, class to private
struct: Data only and no member functions
- Data should (usually) be private
- Methods (functions) should be:
private
for internal use onlypublic
for the external class interface
- The values of the data members comprise the state of the object
- Interface methods can be:
- Mutators – change the ‘state’ of the object
- Accessors – only query values, no changes
- Use
this->
notthis.
Constructors and Destructors
Constructor (as in Java)
- Called when an object is created
- Has function name same as class name
- no return type (none/empty, NOT void!)
- Adding a constructor makes it impossible to provide a C-style initialiser. e.g.
= {0,1,2};
Destructor (similar to Java finalize)
- Called when an object is destroyed
- A function with name ~ then class name • E.g.:
~DemoClass()
- And no return type
Default parameters
- Default values appear only in the function declaration, not any separate definition
- Use `=
‘’ 12DemoClass( char* dummy, int iValue = -1){ /*Nothing*/ }
Default Constructor
The ‘Default Constructor’ is a constructor which can be called with no parameters
- e.g. one which has no parameters
- or has default values for all parameters
- A class can only have one default constructor
- More would introduce ambiguity
When you create arrays of objects, the default constructor is used (because no parameters are provided):DemoClass myDemoArray[4];
IMPORTANT: Do NOT add empty brackets ()
when constructing on the stack if there are no parameters!
- Compiler thinks you are declaring a function
- e.g.
DemoClass myDemoClass1();
// WRONG!!!
Initialisation vs Assignment
Compare the following:
1)
2)
Member data is NOT always initialised
- Basic types and pointers (e.g. int, short or char*) are NOT initialised
- Default constructor is called for members of type class/struct unless you say otherwise
- Using initialisation list
Inline functions
Use the keyword inline
, e.g.:
Similar to a ‘safe’ macro expansion
- Safely replaces the function call with the code
- Unlike a macro (
#define
) - Avoids the overhead of creating a stack frame
- Code gets included in EVERY file/function which calls it
- Unlike a macro (
- VERY useful for small, fast functions
Defining functions within the class declaration implicitly makes them inline
Function set default value for parameters in declaration.
Lecture8
Reference
A way to give a new name to an item
References always have to refer to something
- Must give them a thing to refer to on initialisation
- No such thing as a NULL reference
do NOT return a reference to a local variable
The need for references
- Useful if we need to keep the same syntax
- Useful as return values, to chain functions together
- References are necessary for operator overloading
Passing parameters
- When a function is called, the values of the parameters are copied into the stack frame for the new function
New and Delete
delete destroys an object
- It cares about the object type
- Calls the destructor of the class it thinks the thing is (using pointer type) and then frees the memory
- You MUST
delete
anything which you create
using new - You MUST
delete [] ...
any arrays which you create usingnew ... []
- You MUST
free
any memory which youmalloc
/alloc
/calloc
/realloc
- You MUST
If you want to create objects in dynamic memory then you must go through
new
You can usenew
on basic types (e.g.int)
Arraynew []
uses the default constructor for objects, and does not initialise basic types
Lecture 9
this and static
Static member functions do not have a this
pointer
const
Pointers to constant data
Constant pointers
|
|
String literal
String literals should not be changed
const references
const
references make the thing referred to constconst
references are useful for parameters- Passing by value (not reference) means the original variable (safer)
cannot be accidentally modified - Passing a reference means that no copy is made (maybe quicker)
- Passing by value (not reference) means the original variable (safer)
- Using a const reference means no copy needs to be made, but the original can still not be changed, like a copy but faster
mutable
提前 奶一口 const 就能改了
friend
friend 写在 被用的那个class里,就可以访问private的了
Lecture 10
Namespace
Namespaces are used to avoid name conflicts
- Only the name is affected
namespace <NamespaceName>{}
|
|
scoping
::
Left of scoping operator is
- blank (to access a global variable/function)
- class name (to access member of that class)
- namespace name (to use that namespace)
streams for input/output
File access using streams
ifstream
object - open the file for inputofstream
object - open the file for outputfstream
object – specify what to open file for
stringstream
Lecture 11
没有virtual的时候pSubAsBase->foo()
是调用父类的
如果父类方法 virtual之后,再这么访问,要看pSubAsBase
到底是什么class
vitual 之后想用父类的function 就要 用到 ::
1 2 3
4 5 6
Inheritance and constructors
create in stack
create in heap
- Do not call virtual functions from the constructor or destructor
想要也删掉sub的,把父类的destructor加virtual
Lecture 13
Function pointers
Function pointers
括号里是paraeter
- callback function
Virtual and non-virtual functions
Lecture 14
4 functions created by default if needed
- You can make them unavailable (e.g. private)
- A defaul tconstructor(no parameters needed)
- A copy constructor (copy one object to another)
- An assignment operator (=operator)
- A destructor
A default constructor
- Automatically created if and only if you do NOT create any other constructors
The Copy Constructor
The copy constructor is used to initialise one object from another of the same type
12MyClass( const MyClass& rhs )Takes a constant reference to the object to copy from
- Has to be a reference!
Assignment operator
- Used when value of one object is assigned to another
ob1=ob2=ob3=ob4;
Destructor
- Default destructor does nothing
Conversion constructor
- A conversion constructor is a constructor with one parameter.123MyClass( char c ){ ... do something with c ... }MyClass ob = ‘h’;
int 就可以这么用
conversion operator
explict
Providing a one-parameter constructor provides a conversion constructor
Lecture 15
Casting
- static cast
- dynamic cast
- const cast
- reinterpret cast
casting-ness是强转比如int& xr = (int&)(x);
,尽量避免
dynamic 失败的时候会抛出exception 所以,sub base class转的时候。用dynamic.
Pointer:
Reference:
Operator overloading
non-mumber function
别忘了friend
mumber function
Operator overloading restrictions
Lecture 16
= and !=
+ and +=
template
|
|
The compiler will actually generate the functions which are needed, according to the parameters
Lecture 17
Functor
Functors are classes which overload the () operator
Lecture 18
How do we report errors?
- Return an error value from function
- Set a global error code
- Throw an exception (to report error)
catch
catch
clauses are checked in the order in which they are encountered- Exceptions are thrown by value
- Catch by reference or by value would work - Catch by reference avoids the copy
catch ( ... )
will match ANY exceptioncatch ( BaseClass& b ) { }
will also catch sub-class objectscatch ( BaseClass* b ) { }
will also catch sub-class pointers
Lambda
Lambdas are anonymous functors that get created on the fly
Basic lambda function:
|
|