Wednesday 17 July 2013

Casting in c++

The below example demostrates the types of casting available with c++.

C++ is strongly types language. 

The example below demostrates the diffrent.

Please read the comments to know some theory about the diffrent types of castings.

class base
{
public:
int a;base()
{
cout<<
"Base class object"<<endl;}

void fun(){
cout<<
"Function from base class"<<endl;}
};
class der:public base{
public:der()
{
cout<<
"Der class object"<<endl;}

int b;
void fder(){
cout<<
"Function from derieved"<<endl;}
};
class unrelated{
public:unrelated()
{
cout<<
"Unrelated class object"<<endl;}

void funrelelated(){
cout<<
"Function is unrelated"<<endl;}
};
 
int _tmain(int argc, _TCHAR* argv[]){

// created pointer and objects of each of the class we defined base *bp;
base bo;
der *dp;
der doo;
unrelated *up;
unrelated uo;
// Lets talk about Dynamic cast before we start implementing// 1. Applies to pointer and objects of related classe// 2. Allows downcasting fails in downcasting// 3 Always check that the object are converted or notbp= dynamic_cast<base * >(&doo);//dp= dynamic_cast<der *>(&bo);// This statement will fail or not compile
// Static cast can perform conversion between pointers to related clasees.
// No overhead of type safety check
der *stcst=static_cast<der *>(bp);// Reineterpretcast covnverts any pointer type to any other pointer typer even of unrelated classesbase *bp= new base;unrelated *ur=
reinterpret_cast<unrelated *> (bp);// Constant removes the constantness of object


return
0;}

No comments:

Post a Comment

Apache Beam Learning In Java Tutorials

 Wow  https://youtu.be/9kGETU63rkc