Intro to Object Oriented Programming
Where as defining new C data types used struct, we use classes to define new data types in C++.
Overview of classes
Features of classes:
- Include functions that directly operate on the fields.
- Special functions called constructors are used to initialize class objects (also called instances - variables declared to be of a class type).
- Special functions called destructors are used to perform clean-up operations just before the lifetime of a class instance ends.
- Add protection levels for the fields and functions (e.g. private) to provide data hiding and encapsulation.
- Use inheritance to define a class by extending an existing class.
stream class Hierarchy
Inheritance: class A inherits from class B if every class A object is-a class B object also.
istreamandostreamare both derived fromios.iostreaminherits from bothistreamandostream.- Note that multiple inheritance is allowed. A class can derive from multiple classes
- steam extraction (
>>) operator defined for allistreamsand insertion (<<) operator defined for allostreams, and becausefstreamandstringstreamare both derived fromiostream, they can use both<<and>>.
file input (std::ifstream)
ifstreamhas a constructor taking a string specifying the filename.- Calling the constructor with a filename is the same as calling
fopenwith the filename using arflag. - The file must already exist.
- Calling the constructor with a filename is the same as calling
- since
ifstreaminherits fromistream, we get the insertion (<<) operator. ifstreamhas a destructor that closes the file. When theifstreamobject's lifetime ends, it automatically closes itself.