Wednesday, 18 September 2013

c++ - converting a base class pointer to a derived class pointer

c++ - converting a base class pointer to a derived class pointer

#include <iostream>
using namespace std;
class Base {
public:
Base() {};
~Base() {};
};
template<class T>
class Derived: public Base {
T _val;
public:
Derived() {}
Derived(T val): _val(val) {}
T raw() {return _val;}
};
int main()
{
Base * b = new Derived<int>(1);
Derived<int> * d = b;
cout << d->raw() << endl;
return 0;
}
I have some polymorphism problem right now and the code above summarizes
everything. I created a Base class pointer and I put the pointer of a new
derived template class in it. Then I created a new pointer for the derived
template class and I want it to have the reference the base class pointer
points to. Even though Base pointer (b) points to a Derived, the reference
cannot be passed to Derived class pointer (d) because there's no known
conversion from Base * to Derived<int> * (as what the compiler says).
So is there a trick or an alternative way to be able to do it? Thanks in
advance.

No comments:

Post a Comment