ACtE0305 Pure virtual function and file handling¶
Virtual function and dynamic binding¶
A virtual function enables runtime dispatch through a base-class interface.
Key fact:
- when a call is made through a base-class pointer or reference to a virtual function, the override chosen depends on the dynamic type of the object.
This is dynamic binding.
Without virtual, ordinary member calls are statically bound based on the static type used in the call expression.
Pure virtual function and abstract class¶
Pure virtual syntax:
Recognition facts:
- a class with at least one pure virtual function is abstract;
- abstract classes cannot be instantiated directly;
- derived classes must provide concrete overrides unless they remain abstract.
Stream class hierarchy¶
Core hierarchy cues:
| Class family | Role |
|---|---|
istream |
input stream |
ostream |
output stream |
iostream |
input and output |
ifstream |
file input |
ofstream |
file output |
fstream |
file input and output |
Console objects:
cinis standard input stream object;coutis standard output stream object;cerris unbuffered standard error output;clogis buffered error/log stream.
File opening, closing, and modes in C++¶
| Mode flag | Meaning |
|---|---|
ios::in |
open for input |
ios::out |
open for output |
ios::app |
append on each write |
ios::ate |
seek to end immediately after open |
ios::binary |
binary mode |
ios::trunc |
truncate existing file on open |
Opening styles:
Always close explicitly when needed or rely on RAII at scope exit.
Input/output operations and stream states¶
| Check | Meaning |
|---|---|
good() |
no error flags set |
eof() |
end-of-file flag set |
fail() |
logical/format or open failure |
bad() |
serious stream error |
File and console operations:
- formatted extraction/insertion:
>>,<<; - unformatted input:
get,getline,read; - unformatted output:
put,write.
Trap: formatted >> for strings stops at whitespace, whereas getline reads an entire line.
ios flags and manipulators¶
Formatting tools:
| Tool | Use |
|---|---|
setw(n) |
width |
setprecision(n) |
floating precision |
setfill(ch) |
fill character |
fixed |
fixed-point float format |
scientific |
scientific notation |
hex, oct, dec |
integer base |
left, right |
justification |
endl |
newline plus flush |
Manipulators change stream formatting state or perform immediate output effects.
File-handling traps¶
ios::appalways writes at end;ios::atemerely starts at end and can still seek elsewhere.eof()should not be used as a pre-read loop condition.- Dynamic binding requires a virtual function call through a base interface, not just inheritance alone.
Virtual-file-handling revision box¶
virtualenables runtime polymorphic dispatch.- Pure virtual function makes a class abstract.
istream,ostream,iostreamare the core stream families.ifstream,ofstream,fstreamare file-stream specializations.>>is formatted;getlineandreadare unformatted-style operations.ios::appandios::ateare not the same mode.