Beruflich Dokumente
Kultur Dokumente
Road Map
• Features of P/OOPS
• Classes, objects, methods, scopes, and inline nature
• Constructor and destructor
• Explicit constructor
• Copy constructor
• Default Object assignment and = operator
• Thumb Rules for class
• The constant functions and modification: mutable
• The static data and methods
• The early overloading: brief on ambiguity
• Pointers and references
Road Map …
• Overloading operators
• Communication
– Partial (Friend)
• Access and communication
– Complete (Inheritance)
• Reusability
• Virtual Inheritance and ambiguity with base class members
• Access control (Inheritance and protected members)
• Granting Access
• Virtual function, VTABLE, and pure virtual functions
– Inherited Virtual attribute, hierarchical
– The relation among classes and their behavior: A simple VTABLE
– Abstract classes (pure virtual function)
– Early binding vs. late binding
Road Map …
• Templates
– Generic function
– Generic Class templates
– Generic function and class restriction
– Explicit function and Explicit class specialization
– A brief on typename and export keywords
• Exception handling
– Fundamentals
– The try-catch, throw
– Multiple and Nested catches
– Catching class type exception
– Handling Derived class exceptions
– Catching all exceptions
– Terminate, unexpected, uncaught Exception function
Road Map …
#include<iostream>
using namespace std; // c++ styled comments
int main()
{
cout<<“Hello World in C++”<<endl;
return 0;
}
More codes …
int accept()
{ char name[11]; int age
cout<<“Enter your name and age”;
cin>>name>>age;
return age;
}
int (*fun_handler)(); // a std c call is made as (*fun_handler)();
int main()
{
accept(); //direct calls
fun_handler=accept;
fun_handler() ; // it works from ANSI C
onwards, std C++ return 0;
}
Data’s Scope
int ivar=9;
int main()
{
int ivar=7;
{
int ivar = 5;
cout<<“Global scope ”<< ::ivar<<endl;
cout<<“Inner block ”<<ivar<<endl;
}
cout<<“Global scope ”<< ::ivar<<endl;
cout<<“Inner block ”<<ivar<<endl;
return 0;
}
No default to int
Fun(int ) ;
/* Defaults to integer return. Not to be used in standard C++.
Though, compilers takes it up as standard C / old C++ style
*/
int Fun(int); // should use this way
double Fun();
char *Fun();
double Fun( uiarg, siarg) // K&R style not allowed as std c++
unsigned uiarg;
int siarg;
Must use as done previous
Default value to arguments
int Fun(int x=4,int y=6) ; //controversial feature (do not use it)
Fun(); // 4,6
Fun(10); //10,6
Fun(10,20); // 10 , 20
--------------------------------------Case 1------------------------------------------------
-------------------------.h file-------------------------
int Fun(int x=4,int y=6) ;
-------------------------file that includes .h----------------
int Fun(int x=4,int y=0) ; // illegal, cant redefine
--------------------------------------Case 2------------------------------------------------
-------------------------.h file-------------------------
int Fun(int x=4,int y) ;
-------------------------file that includes .h----------------
int Fun(int x=4,int y=0) ; // allowed
Inline functions & macros
•Inline is a new storage class used in functions as if it were a
macro.
•Unlike a macro, an inline function does not have side effects.
For Example:
#define toupper(c) (islower(c) ? (c) + (‘a’ – ‘A’) : (c))
•When invoked with toupper(*p++) expands to
#define toupper(*p++) (islower(*p++) ? (*p++) + (‘a’ – ‘A’)
: (*p++)) and increments p twice.
An inline function does not exhibit this behavior. Looks as:
inline toupper(int ivar)
{return islower(c) ? c + (‘a’ – ‘A’): c;
} // invokes pointer only once
Inline functions & macros …
namespace rtos
{
int dontknow;
class MsgQ
{
char *message;
public:
MsgQ(){}
MsgQ(char *msg, int size);
};
}
Using namespace …
•extern “C” {
#include “c_extern_decl.h”
#include “f77_extern_decl.h”
}
P/OOPS Programming Concept
Inheritance
Polymorphism
Objects
Objects
E n c a p s u l at i o n
Abstraction
Classes and objects
Classes and objects
Other objects adhere to these interfaces to use the object without having to be
concerned with how the object accomplishes it.
Encapsulation …
An object can be thought of as a self-contained atom. The object interface consists of
public methods and instantiate data.
Information hiding is when you remove data, methods or code from a class's public
interface in order to refine the scope of an object.
You'll remember that C++ classes have a public, protected and private interface.
Moving methods or data from public to protected or to private, you are hiding the
information from the public or protected interface.
Encapsulation …
If you have a class A with one public integer data member d, then the C++
definition would be...
class Home
{
public:
integer doors;
};
If you moved that data member from the public scope of the private scope, then
you would be hiding the member. Better said, you are hiding the member from
the public interface.
class Home
{
private:
integer doors;
};
Constructors and destructors, const members,
copy constructors and default assignment
Constructors and destructors
Constructor:
•Constructors build objects from dust.
•Constructors are like "init functions". They turn a pile of
arbitrary bits into a living object.
•Minimally they initialize internally used fields. They may also
allocate resources (memory, files, semaphores, sockets, etc).
•"ctor" is a typical abbreviation for constructor.
Constructors and destructors …
•Destructors
•A destructor gives an object its last rites.
•Destructors are used to release any resources allocated by the
object.
•E.g., class Lock might lock a semaphore, and the destructor will
release that semaphore. The most common example is when the
constructor uses new, and the destructor uses delete.
•Destructors are a "prepare to die" member function. They are
often abbreviated "dtor".
Constructors and destructors …
class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area (void) {return (*width * *height);}
};
CRectangle::CRectangle (int a, int b) {
width = new int; height = new int;
*width = a; *height = b; }
CRectangle::~CRectangle () { delete width; delete height;}
int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl; return 0;}
When are constructor and destructor executed?
•A copy constructor
•An overloaded = operator
•We will look this further with operator overloads
The constant functions and modification: mutable
class Demo
{ //mutable int intVar; Allows const members to modify
int intVar;
public:
int getVar() const { return intVar*intVar;}
int setVar(int intLocal) const {intVar = intLocal;} // error try modifying
};
int main()
{
Demo demoObj;
demoObj.setVar(10);
cout<<"The value set is ="<<demoObj.getVar()<<endl;
return 0;
}
Sharing Data: static data, and methods
The static data and methods: shared data
Class Shared
{ public:
static int shared;
};
int Shared :: shared; // defaults to 0
int main(){
Shared::shared = 100; // accessing
Shared shared_obj;
shared_obj.shared ; // All class objects can use it too!
}
An example: resource allocation detail
Class SharedResource{ static int Resource;
public:
int getResource();
void freeResource(){Resource=0;}};
int SharedResource :: Resource;
void SharedResource::getResource(){
if(Resource) return 0;
else{
Resource=1; return 1;
}
int main(){ SharedResource task1, task2;
if(task1.getResource()) cout<<“task1 has resource”<<endl;
if(!task2.getResource()) cout<<“Resource busy”<<endl;
task1.freeResource();
if(task2.getResource()) cout<<“task1 has resource”<<endl;
task2. freeResource();
} // try a code to maintain the number of tasks currently being used
An example: static methods
class Sinit{
static int ival;
public:
static int f(int &temp)
{
ival=temp;
cout<<i<<endl;}
};
int Sinit::ival;
int main(void)
{
int ilocal=10;
Sinit::f(ilocal);
return 0;
}
Static/Early Overloading and ambiguities
Aspects of Overloading
•We have also observe that the default parameters can be very confusing.
But applications sometime needs that or sometimes we can use it as a
short hand for overloading
•Overloading is an alternative and respected answer default parameters
that provides the flexibility and convenience
•It also is towards the definition aspect for language as explains much
about the static aspects of polymorphism
•The secret of overloading is that each redefinition of the methods must
use either different type of parameters or the no. of parameters
•Overloads also leads to ambiguity at times.
Ambiguities under Overloading
int main(){
abs(-100); // Ambiguous
abs(-100.05); // Unambiguous
}
Ambiguities under Overloading …
int main(){
f(97); // Ambiguous
f(‘A’); // Unambiguous
}
Ambiguities under Overloading …
int main()
{
f(9); // Ambiguous
f(2,4); // Unambiguous
}
Ambiguities under Overloading …
int main()
{
int ivarl=100;
f(ivarl); // Ambiguous
}
Pointer, References and Dynamic memory
allocation
Pointer and References
Strict definition
•Pointers are cells (often present as two or four bytes) capable of
referencing and dereference the memory allocations
•References are alias to the variable, offers high performance code
play and regarded as true concept of C++
•Pointers can be used as indirect references
•Example:
•data_type *pointer ; // declaring a pointer
•data_type &reference = any_variable; // note the = is a must
Pointer and References
int main() {
int *i_ptr;
float *f_ptr;
i_ptr = f_ptr ; // type mismatch
}
•C++ stronger type checking where pointers are involved, are different
from C, in which you may assign any value to any pointer.
• As we know what reference is, the need to know is the three ways a
reference can be used
1. As a function parameter
2. As a function returning references
3. Independent references
Reference Parameters
int main()
{
int ilvar=1;
neg(&ilvar); // manual call via pointers
neg((ilvar); // no & requires
}
Note: Remember when you assign a value to reference, you are actually
assigning value to that variable what reference pointer points to.
Passing Reference to objects
class loc {
int longitude, latitude ;
public :
loc () { } // needed to construct temporaries
loc (int lg, int lt) {
longitude = lg ;
latitude = lt ;
}
Overloading operation: An complete Example
void show () {
cout << longitude << “ “ ;
cout << latitude << “\n” ;
}
return temp ;
}
Overloading operator using friend(flexibility)
return temp;
}
Overloading operator using friend(flexibility)
int main ()
{
loc ob1 (10, 20), ob2 (5, 30), ob3 ( 7 , 14) ;
ob1.show () ;
b2.show () ;
ob3.show () ;
ob1 = ob2 + 10 ; // both of these
ob3 = 10 + ob2 ; // are valid
ob1. show () ;
ob3.show () ;
return 0 ;
}
Overloading new and delete
class loc {
int longitude, latitude ;
public :
…. Other as previous
void *operator new (size_t size ) ;
void operator delete (void *p) ;
};
Overloading new and delete
ob1.show ();
ob1 (7, 8) ; // can be executed by itself
ob1. show () ;
return 0 ;
}
Case of copy constructor/assignment
class eq
{
//int x;
public: int x;
eq(){}
eq(int temp)
{
x=temp;
cout<<"cons"<<x<<endl;
}
Case of copy constructor/assignment …
eq( const eq &e)
{
x =e.x;
cout<<"copycon"<<x<<endl;
}
eq &operator =(const eq &e)
{
x= e.x;
cout<<"= overload"<<x<<endl;
return *this;
}
~eq(){cout<<"des - called"<<endl;}
};
Case of copy constructor/assignment …
void f(eq &p)
{ cout<<"x= "<<p.x<<" @ "<<&(p.x)<<endl; }
int main()
{
eq o(10);
eq o1 = o; // invoke a copy constructor
eq o2 = o1; // invoke copy constructor
eq o3;
o3 = o2 = o1; // invoke = operator
f(o1); f(o2); f(o3);
return 0;
}
Complex declaration? [pointer to class members]
•Class Semaphore{ public: int lock;
Semaphore(int temp){ lock = temp;}
bool status_busy(){ lock>0?true:false;}
};
•Declaration of data member pointer
•int Semaphore::*lock_ptr;
•lock_ptr=&Semaphore:: lock; //get offset of data member
•Declaration of method member pointer
•bool (Semaphore::*status_ptr)();
•Status_ptr=&Semaphore::status_busy; //offset of method
•Calling is done as
•Semaphore Obj(1);
•If ((Obj.*status_ptr)()) cout<<“busy”<<endl; //method called
•Obj.*lock_ptr; // Is busy >0
[pointer to class members via pointer to object][ use ->*]
int main(){
derived dobj;
dobj.set(12,15) ;
dobj.show() ;
}
/* if 1. Is uncommented following will not compile
int main(){
derived dobj;
dobj.set(12,15) ; //error
dobj.show() ; //error
} */
Inheritance and protected member
Class base{
protected: int i,j; //private to base
public: void set(int a, int b) {i=a; j=b;}
void show(){ cout<<“i = ”<<i<<“
and j = ”<<j<<endl;} };
Class base{
protected: int i,j; //private to base
public: void set(int a, int b) {i=a; j=b;}
void show(){ cout<<“i = ”<<i<<“ and j = ”<<j<<endl;} };
Note: Even though base class is inherited as private by derived1, has the access to base’s public, and
protected member. But cannot pass this privilege to it’s derived
Protected base class inheritance
Class base{
protected: int i,j; //private to base
public: void set(int a, int b) {i=a; j=b;}
void show(){ cout<<“i = ”<<i<<“ and j = ”<<j<<endl;}
};
// all public n protected member of base becomes protected members of derived
Class derived1: protected base { int k;
public: void setk() { set(10,20); // may access i, j as eariler
k= i * j ; // derive can access i,j
}
void showk(){ cout<<“k in derived = ”<<k<<endl;
}
};
Class derived2: public derived1{};
main(){ derived1 d;
d.set(1,2); //illegal [is accessible if public]
return 0;
}
// if base class is inherited via protected, it means its members cannot be accessed
via out side function such as main() or any other independent function!
Granting Access
Class base{
protected: int i,j; //private to base
public: int public_var; // is public now
void set(int a, int b) {i=a; j=b;}
void show(){ cout<<“i = ”<<i<<“ and j = ”<<j<<endl;}
};
A
iData
iData iData
?
B C
Compiler
D
Virtual base classes: virtual inheritance
Polymorphism
A method that is not virtual is said to be statically bound, whereas virtual methods are
said to be dynamically bound. Non-virtual methods are statically bound, because the
binding of the method is performed at compile and link time and cannot be changed.
Virtual methods are dynamically bound, because the binding of the method is actually
performed at run-time.
When you call a virtual method, a small lookup is performed in the object virtual table
(a.k.a. vtable) to find the address of the method being called. By manipulating an objects
vtable at run-time, the target address can be altered.
Vtable
Call Entry-point
Declarations Call Callee
Adjustment Adjustment
A *pa_in_b = pb;
pa_in_b->f() B::f() none none
struct A { 0 A::vptr
virtual void f ();
virtual void g ();
virtual void h (); 16
int ia;
}; 8 ia
Note:
Each function descriptor in the vtable is 16 bytes but the offset and data pointers
are only 8, the earlier versions of this table didn't take that into account
struct B: public virtual A { 0 B::vptr
void f ();
void h ();
int ib;
};
8 ib
32
16 A::vptr
24 ia
32
16 A::vptr
24 ia
Case study : Implementing a v-table
A()
B()
C()
Base-class
region Virtual function
Used by derived
Derived-class
region
User control area Compiler control area
Case study : Implementing a v-table …
typedef (*fp)();
Class Base{
int basedata; void Base__Base(){;;;;;;;;;;;;;;;}
public: int Base__A()(){/*----------*/}
Base(); int Base__B()(){/*----------*/}
virtual int A(); int Base__C()(){/*----------*/}
virtual int B(); int Base__D()(){/*----------*/}
virtual int C();
int Z(); fp virtual_Base[3] = //vfTab
}; {
Base__A,
Base::Base() {;;;;;;;;;;;;;;} Base__B,
int Base::A() { /*------*/} Base__C,
int Base::B() { /*------*/} };
int Base::C() { /*------*/}
int Base::Z() { /*------*/} struct class_Base
{
fp *vtab;
int basedata;
}
Case study : Implementing a v-table
struct class_Base s;
//Allocate space
Base__Base(&bobj)
//call constructor &s is the implicit
int main() this pointer
{
Base bobj; bobj.vtab = virtual_Base
bobj.Z();
bobj.A(); // Initialize a Vtab
} //the obj’s vft is initilized when the
object created –at run time. The major
diff b/w malloc and new
Base__Z(&s);
(*bobj.vtab[1])(&s)
Case study : Implementing a v-table
typedef (*fp)();
Class D:public Base{
int ddata; void D__D() {;;;;;;;;;;;;;;;}
public: int D__DA() {/*----------*/}
D(); int D_B() {/*----------*/}
virtual int DA(); //local B()
virtual int B();
}; fp virtual_D[3] = //vfTab
{
D::D() {;;;;;;;;;;;;;;} Base__A,
int D::DA() { /*------*/} D__B,
int D::B() { /*------*/} Base__C,
D_DA
};
struct class_D
{
fp *vtab;
int basedata;
int ddata;
}
Case study : Implementing a v-table: predict
Base *p = malloc(sizeof(D));
Base__Base(p) ;
int main()
D__D(p);
{
Base d = new D; p.vtab = virtual_D
d->B() ; // D’s vtab
}
//d->B
(*s.vtab[1])();
// does as the earlier but with D’s call
Problems with a default virtual in derived class
void main(){
A *ap = new A; // works as expected
ap->f();
ap = new B;
ap->f(); // calls B::f()
ap = new C;
ap->f(); // calls C::F()
bp = new C;
bp->f(); // dosen’t work as expected: calls B::f() as p is a B ptr and c !virtual
}
Ending with Virtual destructors
class base{
public:
base(){}
~base(){}
}
class derived: public base{
public:
derived{}
~deriver(){}
}
int main()
{
base *b;
b = new derived;
delete b; // calls only base’s destructor as p is a base*[]
}
Abstraction
Another OOP concept related to encapsulation that is less widely used but
gaining ground is Abstraction.
Through the process of abstraction, a programmer hides all but the relevant data
about an object in order to reduce complexity and increase efficiency.
In the same way that abstraction sometimes works in art, the object that remains
is a representation of the original, with unwanted detail omitted. The resulting
object itself can be referred to as an abstraction, meaning a named entity made
up of selected attributes and behavior specific to a particular usage of the
originating entity.
The example presented is quite simple. Human's are a type of land animal and all
land animals have a number of legs.
There is also a less rigid definition of abstraction that would include classes that without
pure virtual functions, but that should not be directly instantiated.
A more rigid definition of abstraction is called purely abstract classes.
A C++ class is said to be purely abstract, if the class only contains pure virtual
functions.
The LandAnimal class was such a class. Purely abstract classes are often called
interfaces, protocol classes and abstract base classes.
Templates, generic function, class templates
and function templates
Templates
•Although not a part of original specification to C++, it was added several years
ago and is supported by all modern C++ compilers.
•In generic function or class the type of data upon which the function or class
operates is specified as a parameter
•Thus, we can use one function or class with several types of data without
recoding specific version of each of them
Generic function
•In essence, when you create a generic function you are creating a function that can
automatically overload itself. It’s general format is
int main ( )
{
int i = 10, j = 20;
double x = 10.1, y =23.3;
char a = ‘x’, b = ‘z’;
Function template
return 0;
}
Remember
temp = a; temp = a;
a = b; a = b;
b = temp; b = temp;
} }
A function with two generic type
# include <iostream>
using namespace std;
int main ( )
{
myfunc (10, “I like C++”);
myfunc (98.6, 19L);
return 0;
}
Explicitly overloading a generic function
temp = a;
a = b;
b = temp;
cout << “Inside template swapargs.\n”;
}
Explicitly overloading a generic function
temp = a;
a = b;
b = temp;
cout << “Inside swapargs int specialization.\n”;
}
Explicitly overloading a generic function
int main ( )
{
int i = 10, j = 20;
double x = 10-.1, y = 23.3;
char a = ‘x’, b = ‘z’;
cout << “Original i, j:” << i <<’ ‘ << j << ‘\n’;
cout << “Original x, y:” << x <<’ ‘ << y << ‘\n’;
cout << “Original a, b:” << a <<’ ‘ << b << ‘\n’;
swapargs (i, j); // calls explicitly overloaded swapargs ( )
swapargs (x, y); // calls generic swapargs ( )
swapargs (a, b); // calls generic swapargs ( )
cout << “Swapped i, j:” << i <<’ ‘ << j << ‘\n’;
cout << “Swapped x, y:” << x <<’ ‘ << y << ‘\n’;
cout << “Swapped a, b:” << a <<’ ‘ << b << ‘\n’;
return 0;
}
Using Standard Parameters with Template Functions
public :
stack ( ) { tos = 0; } // initialize stack
void push (StackType ob); // push object on stack
StackType pop ( ); // pop object from stack
};
Class templates …
// Push object.
template <class StackType> void stack <StackType>:: push
(StackType ob)
{
if (tos = =SIZE) {
cout << “Stack is full./n”;
return;
}
stck [tos] = ob;
tos++;
}
Class templates …
// pop an object.
template <class StackType>StackType stack<StackType> : : pop (
)
{
if (tos = = 0) {
cout << “Stack is empty./n”;
return 0; // return null on empty stack
}
tos--;
return stck [tos];
}
Class templates …
int main ( )
{
// Demonstrate character stacks.
stack<char> s1, s2; // create two character stacks
int i;
for (i=0; i<3; i++) cout << “Pop s1: “ <<s1.pop( ) << “\n”;
for (i=0; i<3; i++) cout << “Pop s2 “ <<s2.pop( ) << “\n”;
for (i=0; i<3; i++) cout << “Pop ds1: “ << ds1.po. ( ) << “ /n”;
for (i=0; i<3; i++) cout << “Pop ds2: “ << ds2.po. ( ) << “ /n”;
return 0;
}
The typename keyword
temp = a;
a = b;
b = temp;
}
Exception Handling
Exception Handling: Fundamentals
try{
// possibly expecting an error
if the expected
throw list-type;
}
// int x; will not work
catch(type list)
{
}
•Can have nested catches
Try
{ ……….}
catch(type1 list)
{ }
Catch(type2 list)
{ }
A simple example
# include <iostream>
using namespace std;
int main ( )
{
cout << “Start\n”;
int main ( )
{
cout << “Start\n”;
Xhandler (1); Xhandler (2); Xhandler (0); Xhandler (3);
cout << ‘End”;
return 0;
}
Exception Handling…
}
Catch(…){
// any exception un-handled type will come here
}
•You can re-throw an exception to outer block seeking if that can handle
•It’s general form is
Try
{
try{
if problem then
throw
}
catch(type list) {
// I will not /cannot handle hence
throw list
}}
Catch(…) {}
Example: Catch Any type …
Int main()
{
try {
}
catch(…)
{
cout<<“Any thin will come here”;
}
}
Throwing an exception from a function outside the try block.
int main ( )
{
cout << “Start\n|;
try { // start a try block
cout << “Inside try block\n”;
Xtest (0);
Xtest (1);
Xtest (2);
}
catch (int i) { // catch an error
cout << “Caught an exception – value is: “;
cout << i << “\n”;
}
Restricting Exception Handling…
•You can restrict an exception that a function can throw outside itself
}
•Note:
•if you throw any other type of exception then abnormal program
termination would occur that internally calls a function unexpected()
which by default calls terminate()
•You can similarly handle your own class type for all the above explained
concept
Restricting function throw types.
int main ( )
{
cout << “Start\n”;
Restricting function throw types.
try{
Xhandler (o); // also, try passing 1 and 2 to Xhandler ( )
}
catch (int i) {
cout << “Caught an integer\n”;
}
catch (char c) {
cout << “Caught char/n”;
}
catch (double d) {
cout << “Caught double /n”;
}
Setting the terminate
void my_Thandler()
{
cout<<"in my terminate"<<endl;
}
int main()
{
set_terminate(my_Thandler);
try{
if something wrong
throw ;
}
catch(type list)
{// catch a type
}
File Handling in C++
Hierarchy
IOS
istream ostream
iostream fstreambase
ifstream ofstream
FSTREAM
Operation under a file
•The data storage differs in media and the standard file and I/O
libraries takes care of bringing in to main memory[RAM] area.
•These system calls are the wrappers build around those system calls
that allow primarily the file operation you need to perform.
•C++ behaves a bit differently as it deals with object behavior and tries
to provide a easy way of handling file too!
#include <fstream>
using namespace std;
int main()
{
ofstream SaveFile("cpp-file.txt");
//an object with constructor
SaveFile.close();
// calling close method to free the file descriptor
return 0;
}
Reading A File
#include <fstream.h>
char ch;
while(!OpenFile.eof())
{
OpenFile.get(ch);
cout << ch;
}
OpenFile.close();
}
//The function eof() returns a nonzero value if the end of the file has
been reached. So, we make a while loop, that will loop until we
reach the end of the file
A useful reading
#include <fstream.h>
while(!T.eof())
{
T.get(ch);
cout << ch;
}
void main()
{
ifstream T("file1.txt");
read(T);
T.close();
T.open("file2.txt");
read(T);
T.close();
}
Modes of operation
ios::in Open file to read
#include <fstream.h>
void main()
{
ofstream SaveFile("file1.txt", ios::ate);
SaveFile.close();
}
Note: If you want to set more than one open mode, just use the OR
operator- |.
void main()
{
fstream File("test.txt",ios::in | ios::out);
char str[30];
while(!OpenFile.eof())
{
OpenFile >> str;
cout << str;
}
Reading line by line
if(!File)
{
cout << “Error opening the file! Aborting…\n”;
exit(1);
}
Check if the file opening was successful or not
if(File.fail())
{
cout << “Error opening the file! Aborting…\n”;
exit(1);
}
#include <fstream.h>
void main()
{
fstream File("test_file.txt",ios::out | ios::in | ios::binary);
char ch;
ch='o';
File.close();
}
Handling Binary data [block-wise data]
Example 2: Using read() and write()
#include <fstream.h>
#include <string.h>
void main()
{
fstream File("test_file.txt",ios::out | ios::in | ios::binary);
char arr[13];
strcpy(arr,"Hello World!"); //put Hello World! into the array
File.write(arr,5);
//put the first 5 symbols into the file- "Hello"
tellg() - Retunrs an int type, that shows the current position of the
inside-pointer. This one works only when you read a file.
Class phonebook{
public:
char name[80];
int areacode;
int prefix;
int num;
phonebook( char*n, int ac, int p, int nu)
{
strcpy(name,n);
areacode = ac;
prefix = p;
num = nm;
}
friend ostream &operator <<(stream &stream,phonebook o);
friend ostream &operator >>(stream &stream,phonebook &o)
};
Example …
int main()
{
phonebook a;
cin>>a;
cout<<a;
return 0;
}
Run time type identification
type_id, cast operators
RTTI
•RTTI were not the specification of STD C++ but both were added
to C++
•The 1st two are for comparison operator for object similarity check
•The before returns true if the invoking object is before the object
used as a parameter in calling order.
int main()
{
int i,j;
float f;
char *p;
Base bob;
Derived dob;
printf("typeid of i is %s\n",typeid(i).name());
printf("typeid of i is %s\n",typeid(f).name());
printf("typeid of i is %s\n",typeid(p).name());
printf("typeid of i is %s\n",typeid(bob).name());
printf("typeid of i is %s\n",typeid(dob).name());
class Base{
public:
virtual void A(){};
};
int main()
{
Base *bp,b;
Derived d;
Derived d1;
bp=&b;
printf("bp is now with %s\n",typeid(*bp). name());
bp=&d;
printf("bp is now with %s\n",typeid(*bp). name());
bp=&d1;
printf("bp is now with %s\n",typeid(*bp). name());
}
Cast operators
There are four casting operators in C++ with their main usage:
static_cast
To convert non polymorphic types.
const_cast
To add or remove the const-ness or volatile-ness type.
dynamic_cast
To convert polymorphic types.
reinterpret_cast
For type conversion of unrelated types.
Using Cast operators
•The syntax is same for the four type cast except the cast name:
name_cast<new_type> (expression)
where:
int main()
{
int main()
{
int p1 = 3;
cout<<"integer type, p1 = "<<p1<<endl;
cout<<"color c1 = static_cast<color> (p1)"<<endl;
color c1 = static_cast<color> (p1);
cout<<"enum type, c1 = "<<c1<<endl;
return 0;
}
Constant cast: Example
int main()
{
const int p = 20;
int main()
{
One b;
funct2(b);
return 0;
}
Dynamic cast: Example
//derived class...
class Derived1:public Base1 {};
if(!Test2)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
•The STL includes the classes vector, list, deque, set, multiset,
map, multimap, hash_set, hash_multiset, hash_map, and
hash_multimap.
•You can, for example, use a vector<int> in much the same way as you
would use an ordinary C array, except that vector eliminates the job of
managing dynamic memory allocation by hand.