C++
sizeof operator in C++
Returns the size in bytes of an expression's return type or a type name. Return type is constant size_t. Usage syntax
sizeof (type)
sizeof (expression)
First one returns size of type, second one returns size of type obtained after processing expression.
, comma operator in C++
Left hand expression is evaluated, result is discarded. Returned result is evaluated expression on right hand side.
int a = 15;
int b = 84;
int c = (a, b++);
printf("%d",c);
84
Named Cast in C++
staic_cast
Converts between types using implicit and user-defined conversions(const should not be involved).
static_cast<type_to_converted_to>(expression)
const_cast
Converts constness of a object. Changes a const object to nonconst
reinterpret_cast
Converts to new type between reinterpreting the underlying bit pattern. Treats the expression as if it had the new type all along.
Error Handling in C++
throw expression
throw raises exceptions(runtime_error for example). We use it after error has been detected and after it the function terminates. For example
throw std::runtime_error("Error!!!");
will result in error.
Full list of errors is here.
try and catch blocks
try{
//program
} catch (exception-declaration){
//hanlder-statement
} catch (exception-declaration){
//hanlder-statement
}
for example
try {
throw std::runtime_error("Some error!!!");
} catch(std::runtime_error err) {
std::cout<<err.what()<<" spotted";
}
Some error!!! spotted
There can be multiple catch statements, each handling different kind of exceptions. try blocks can be nested and if inner block fails to handle the exception(by not having appropriate catch block) then inner block is terminated and error is transferred to the outer try block.
The exceptions types defines only a data function named what which returns a C-type string in which we usually store our error information.
Functions in C++
IO library in C++
C++ deals with input and output using certain types. In addition to these we have other types too.
iostreamdefines types to read from and write to streamsistreamostreamiostreamwhich is capable of both reading and writing
fstreamdefines types to read from and write to filesifsteamofstreamfstream
sstreamdefine type to read and write in-memorystribgistringstreamostringstreamstringstream
There are also there siblings to handle wchar_t data, which have additional w in front of above name.
Quirks of IO library in C++
We cannot copy paste or assign IO Objects
We can instead access and manipulate condition state of a stream object using functions and flags.
Specify which mode to open file in using traits, these are of type
std::ios_base::openbase. Format isstd::_S_{mode}orstd::ios::{mode}. These modes given at cpprefrence.com.
Flags
std::ios_base::iostatestd::ios_base::badbitstd::ios_base::failbitstd::ios_base::goodbit
Methods
stream.eof()stream.fail()stream.bad()stream.bad()stream.good()stream.clear()stream.clear(flags)stream.setstate(flags)stream.rdstate()
Buffers in C++
Buffer store data(for performance reasons) before writing to a stream. Flush is writing of data to the stream(device or file). A flush can happen because
Program completes normally.
If buffer becomes full.
Explicitly using manipulators(such as
endl).Using
unitbuffmanipulationIf one output stream is connected to another(
cinandcerrboth tied tocout) then whenever tied stream is modified, then the buffer of tied stream is flushed.
Manipulators
endlends the line and flushes the bufferendsinserts a null character and flushes the bufferflushflushes the buffer but does not add anything to the endunitbuffflushes after every output from that point onwardnounitbuffreturns to normal buffering
Tying Input and Output Stream
When an input stream is tied with output stream, any attempt to use input stream causes flush to happen. For example cin and cout are tied. We can even tie two output streams, cerr and cout are example of such.
There are two overloaded tie methods. One takes no argument returns pointer to ostream if it exists, otherwise a null pointer. Second one take a pointer to an ostream and ties itself to that stream.
std::cout<<"Hello!!!"<<std::endl;
std::ostream *cout_new = std::cin.tie();
*cout_new<<"Should work as cout";
Hello!!! Should work as cout
Stream input output in C++
istreamtype provides input operationscinis anistreamobject>>operator reads input fromistrean objectgetlinereads input from aistreamand stores it in a givenstring
ostreamprovides output operationscoutis anostreamobjectcerris anostreamobject associated withstderrerror stream<<operator writes output to aostreamobject
File Input/Output
fstream header provides 3 types ifstream, ofstream and fstream. In addition to normal functionality of iostream, objects of these type have additional members.
There are a few ways to initialize object of these type.
fstream fstrm("file");
fstream fstrm("file","mode");
fstream fstrm; //defination first
fstrm.open("file");//returns void
fstrm.open("file","mode");
When open fails, failbit is set. Opened file is associated with an object, trying to open it with other causes failbit to set.
Closing a file is simple.
fstrm.close();
To check whether a file object is open or not we use is_open() method.
We can pass ifstream objects in place of iostrea&.