I want to have a reference to the source object in the receiving object
after a copy (Copy ctr or assignment). I dont want the receiving object
to be able to modify contents in the copied object.
How should i do this?
Here is my first stab at a solution, but its not working.
Its the dynamic downcast from Base* to SubA* that fails when i run. I
want to use a dynamic cast since i sometimes need to do a runtime check
to see if an object is if a certain type. I need to do a downcast to be
able to check the values of the original (source) object.
So how can i have access to the source object, use it as the downcasted
subtype ,and restrict that access to be read-only.
class Base
{
public:
Base() : sourceObj(NULL) {}
virtual ~Base() {}
Base(const Base& other)
{
*this = other
}
Base& operator=(const Base& other)
{
sourceObj = &other;
return *this;
}
protected:
const Base* sourceObj;
}
class SubA : Base
{
public:
SubA() : Base() {}
~SubA() {}
SubA(const SubA& other) : Base(other) {}
int anAttribute;
void checkAttributeOfSource()
{
// Line below casts an error when run in MS VC++ .NET
SubA* a = dynamic_cast<SubA*>(sourceObj);
if (a->anAttribute = 1)
{
// do something
}
}
}
// ---- Main snippet --------
Base* aBase = new SubA();
// Line below casts an error when run in MS VC++ .NET
SubA* aSub = dynamic_cast<SubA*>(aBase);
// --- Scenario B
SubA a1.readFromdatabase();
SubA a2(a1);
a2.ReadFromClient();
// Here i want to be able to query values in a1 without modifying
a1
a2.CompareMeTosourceObject();