C/C++
SeungAh Hong
C
Global Variables
- Characteristics
- Declared outside of functions
- Occupies a specific region of memory (heap) and is accessible from all functions
- Created and allocated when the program starts, and its memory space is released when the program terminates
- Advantages
- Convenient to use, accessible from every function, and returns values via call-by-reference
- Disadvantages
- Because its value can be changed by any function, it can be altered from anywhere. The memory space is not released
Local Variables
- Characteristics
- Declared inside a function or within a {...} scope
- Memory is created and allocated when the function is called, and released when the function ends
- Accessed within its scope; a call-by-reference pointer is required to access it
- Advantages
- No waste of memory occurs.
- Disadvantages
- It is cumbersome to access a specific function's variable from another function.
Static Variables (static variable)
- Characteristics
- When declared using the static keyword, it is automatically initialized to 0
- Since a static variable is allocated in the heap region, it retains its value even after termination.
C++
Virtual Functions
- Determining the call target not based on the pointer's data type, but by referring to the object that the pointer variable actually points to
Why Use Virtual Functions
- The C++ compiler decides whether a pointer operation is possible based on the pointer's data type, not the data type of the object it actually points to. Therefore, a virtual function is needed in order to call the object that is actually being pointed to.
Virtual Function Example
Third *tptr = new Third();
Second *sptr = tptr;
First * fptr = sptr;
tptr->FirstFunc() (o)
tptr->SecondFunc() (o)
tptr->ThirdFunc() (o)
sptr->FirstFunc() (o)
sptr->SecondFunc() (o)
sptr->ThirdFunc() (o)
fptr->FirstFunc() (o)
fptr->SecondFunc() (o)
fptr->ThirdFunc() (o)Pure Virtual Functions
- A function whose body is not defined
virtual int GetPay() const = 0;Abstract Classes
- A class from which objects cannot be created
- Contains one or more pure virtual functions
Virtual Destructors
- When all destructors must be called during the object destruction process regardless of the data type of the pointer variable used with the delete operator, you must declare it as virtual and implement a virtual destructor. If there is one or more virtual functions, a virtual destructor must always be called.
vitual ~First();