M
Me
I need to be able to acces non-virtual members of sublcasses via a
base class pointer...and without the need for an explicit type cast.
I thought a pure virtual getPtr() that acts as a type cast would solve
the problem, but it appears not to.
I need this functionality to make object serialization a reality. Having
to explicitly cast each deserialized object to its original type defeats
the purpose of my serializing the blasted things in the first place. The
serialization functions all work at this point but the deserialized object,
accessible via a base class pointer, must allow for an "implicit" cast to
the correct subclass. See below...
#include <iostream>
#include <iomanip>
struct base {
virtual base* getPtr()=0;
};
struct subclass: public base {
subclass* getPtr() { return this; }
const char* isA() { return "subclass"; }
};
using namespace std;
int main(int argc, char** argv) {
base* p=new subclass();
// $ g++ test.cc # using gcc 4.1.2 and glibc 2.5.18
// test.cc: In function 'int main()':
// test.cc:19: error: 'struct base' has no member named 'classname'
cout << p->getPtr()->isA() << endl;
return 0;
};
I would EXPECT p->getPtr() to do a correct type cast of the pointer so
that ->isA() is called with a pointer of the correct type, but that's not
happening...WTF!?
base class pointer...and without the need for an explicit type cast.
I thought a pure virtual getPtr() that acts as a type cast would solve
the problem, but it appears not to.
I need this functionality to make object serialization a reality. Having
to explicitly cast each deserialized object to its original type defeats
the purpose of my serializing the blasted things in the first place. The
serialization functions all work at this point but the deserialized object,
accessible via a base class pointer, must allow for an "implicit" cast to
the correct subclass. See below...
#include <iostream>
#include <iomanip>
struct base {
virtual base* getPtr()=0;
};
struct subclass: public base {
subclass* getPtr() { return this; }
const char* isA() { return "subclass"; }
};
using namespace std;
int main(int argc, char** argv) {
base* p=new subclass();
// $ g++ test.cc # using gcc 4.1.2 and glibc 2.5.18
// test.cc: In function 'int main()':
// test.cc:19: error: 'struct base' has no member named 'classname'
cout << p->getPtr()->isA() << endl;
return 0;
};
I would EXPECT p->getPtr() to do a correct type cast of the pointer so
that ->isA() is called with a pointer of the correct type, but that's not
happening...WTF!?