Re: converting derived class pointer to private base class pointer
* "Francesco S. Carta" <entul...@gmail.com> wrote:
subramanian10...@yahoo.com, India <subramanian10...@yahoo.com>, on
14/08/2010 08:40:06, wrote:
...
In any case, as a self-improvement, Derived::Clone should be returning a
Derived* and not a Base*, as I learned else-thread.
--
FSC
Thanks very much for providing this additional information. Is the
reason for Derived::Clone() to return only 'Derived*' instead of
'Base*', the following:
If the Derived::Clone() returned a 'Base*' and if Base had a mutator
which modifies the 'Base::data', it would amount to modifying the
private part of Derived object(returned by Derived::Clone()) through
the 'Base*' because the derivation is private ?
Here is the complete program which, of course, is a modification of
your program:
#include <cstdlib>
#include <iostream>
using namespace std;
class Base
{
public:
Base(int data = 0) : data(data) {};
Base(const Base& base) : data(base.data) {};
virtual Base* Clone() const {
cout << "cloning Base" << endl;
return new Base(*this);
}
int Data() const {
return data;
}
void Data(int i); // newly added mutator
virtual ~Base() { }
private:
int data;
};
inline void Base::Data(int i)
{
data = i;
return;
}
class Derived : private Base {
public:
Derived(int data = 0) : Base(data) {};
Derived(const Derived& derived) : Base(derived) {};
Base* Clone() const {
cout << "cloning Derived" << endl;
return new Derived(*this);
}
virtual ~Derived() { }
};
int main()
{
Derived d(42);
Base* pb = d.Clone();
cout << pb->Data() << endl;
pb->Data(100);
cout << pb->Data() << endl;
delete pb;
pb = 0;
return EXIT_SUCCESS;
}
This program compiles fine with g++3.4.3 and when run, produces the
output:
cloning Derived
42
100
Here, note that the '100' is the value stored in the Base::data of the
Base portion of the Derived object. But this should not happen because
Base is derived with 'private'. Hence if Derived::Clone() returned a
'Base*', then, even if we modified the Base::data of this newly
constructed Base object returned by Derived::Clone(), through
Base::Data(value), then it is not wrong because we would be modifying
an independent Base object. Is this understanding of mine is correct ?
Kindly clarify.
Thanks
V.Subramanian