Hi,
I have below piece of code in which i am dynamically casting a base type to derived type (which is allowed in case base class is polymorphic).
even then i m getting error while dynamic casting.
Please Help.
Thanks,
Harish
#include <iostream>
using namespace std;
//----------------------- class Idatatype ------------------------//
class IDatatype
{
public:
IDatatype(){ cout <<"constructor IDatatype"<<endl; i = 100 ; };
IDatatype( const IDatatype& right){ cout<<"copy constructor IDatatype"<<endl;i = right.i; };
virtual ~IDatatype(){};
virtual IDatatype& copyData(const IDatatype& right) = 0;
int getData() {return i ;}
void setData(int x){ i = x;};
void setData(IDatatype& right){ i = right.getData(); };
private:
int i ;
};
//----------------------- class FlatChargeInfo ------------------------//
class FlatChargeInfo : public IDatatype
{
public:
FlatChargeInfo() {cout<<"constructor FlatChargeInfo"<<endl;};
FlatChargeInfo(const FlatChargeInfo& other) {cout<<"copy constructor FlatChargeInfo"<<endl;
m_oCustomDatatype = other.m_oCustomDatatype; };
virtual ~FlatChargeInfo(){};
IDatatype* getData() {return m_oCustomDatatype; }
virtual IDatatype& copyData(const IDatatype& right){return *m_oCustomDatatype; };
private:
IDatatype* m_oCustomDatatype;
};
//----------------------- class FlatChargeInfoProxy ------------------------//
class FlatChargeInfoProxy : public IDatatype
{
public:
FlatChargeInfoProxy(){ cout<<"constructor FlatChargeInfoProxy"<<endl;
m_pFlatChargeInfo = new FlatChargeInfo();}
FlatChargeInfoProxy(const FlatChargeInfoProxy& other)
: IDatatype( other ) , m_pFlatChargeInfo( other.m_pFlatChargeInfo ){
m_oCustomDatatype = other.m_oCustomDatatype ;
cout<<"copy constructor FlatChargeInfoProxy"<<endl;
};
virtual ~FlatChargeInfoProxy(){};
//virtual void setCode( int newCode){ m_pFlatChargeInfo->setCode(newCode);};
IDatatype* getData(){return (m_oCustomDatatype);};
//void setData(IDatatype* iDataType){m_oCustomDatatype=iDataType;};
FlatChargeInfo* getChargeRecord(){return (m_pFlatChargeInfo);};
virtual IDatatype& copyData(const IDatatype& right);
private:
IDatatype* m_oCustomDatatype;
protected:
FlatChargeInfo * m_pFlatChargeInfo;
};
//## Assignment operator. Copyes data from argument to current datatype
IDatatype& FlatChargeInfoProxy::copyData(const IDatatype& right)
{
const FlatChargeInfoProxy* ptr = (dynamic_cast<const FlatChargeInfoProxy*>(&right));
if( ptr ) {
m_pFlatChargeInfo = ptr->m_pFlatChargeInfo;
// Copy data of customization object
// if (m_oCustomDatatype) {
//m_oCustomDatatype->copyData(*(ptr->m_oCustomDatatype));
// }
}
return *this;
};
//-------------------------------- MAIN -----------------------------------//
main(){
FlatChargeInfoProxy fp,fp2;
FlatChargeInfo f;
fp.copyData(f);
}