C++ Note
new/delete
vs malloc/free
new/delete
( keyword ) call the Constructor/Destructor.
malloc/free
( std. function ) simply allocate memory from the heap.
OOP features
Encapsulation:
Human
{
public:
void eat();
private:
void openMouth();
void putFoodIn();
void closeMouth();
}
void Human::eat()
{
openMouth();
putFoodIn();
closeMouth();
}
Abstraction: Essential characteristics of model.
Inheritance & Polymorphism: Women
and Man
, since they are part of Human
, so both can speak()
, but their voice
is different.
union
The union is only as big as necessary to hold its largest data member.
A union can have member functions (including constructors and destructors), but not virtual functions.
A union cannot have base classes and cannot be used as a base class.
A union cannot have data members of reference types.
stack vs heap
Stack:
Heap:
reference vs pointer
array vs pointer
char amessage[] = "now is the time";
char *pmessage = "now is the time";
amessage[0] = 'N' //OK
pmessage[0] = 'N' //Compile OK,But run NG
amessage
is an array who live in stack.
pmessage
is a pointer who live in stack, but its value is commonly stored in a string table.
sizeof(pmessage)
is size of pointer but not string length.
before main()
, global object while be constructed
virtual destructor
class A{
public:
~A(){
qDebug()<<"A Dead";
}
};
class B: public A{
public:
~B(){
qDebug()<<"B Dead";
}
};
A* ab = new B();
delete ab; // A Dead
//But
class A{
public:
virtual ~A(){
qDebug()<<"A Dead";
}
};
// A Dead
// B Dead
Stack Overflow
Eg: infinite recursion.
Heap Overflow
garbage collection.
Inline function
If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
So, it decreases the frequency of function call but it increases the size of function which contains the call of inline function .
To be continue…