N
nw
Hi,
I have three classes, a template pure virtual base class, a template
derived class and a third which I would like to use to store copies of
the derived class. The code looks like this:
#include <iostream>
#include <vector>
using namespace std;
template <class _prec> class Base {
public:
_prec i;
Base() {
i = 12;
}
virtual void f() = 0;
};
template <class _prec> class Derived : public Base<_prec> {
public:
void f() {
std::cout << this->i << std::endl;
}
};
template <class _prec> class Collect {
public:
vector <Base<_prec> > vec;
Collect() {
}
void g(Base<_prec> &in) {
vec.push_back(in);
}
};
int main() {
Derived<int> d;
Collect<int> c;
c.g(d);
return 0;
}
This results in linking errors, which result from vector being unable
to create a copy of the pure virtual class. Can anyone suggest how I
should solve this?
My first attempted was to make the function in Base virtual, rather
than pure virtual (i.e. virtual void f() {}). This then compiles,
however when the object is extracted from the vector (i.e. I do
vec[0].f() in Collect), the base method is called not that of the
derived class. Any ideas?
I think this should all be standard C++ but I'm using gcc version 4.1.2
to compile this code.
Any help appreciated!
I have three classes, a template pure virtual base class, a template
derived class and a third which I would like to use to store copies of
the derived class. The code looks like this:
#include <iostream>
#include <vector>
using namespace std;
template <class _prec> class Base {
public:
_prec i;
Base() {
i = 12;
}
virtual void f() = 0;
};
template <class _prec> class Derived : public Base<_prec> {
public:
void f() {
std::cout << this->i << std::endl;
}
};
template <class _prec> class Collect {
public:
vector <Base<_prec> > vec;
Collect() {
}
void g(Base<_prec> &in) {
vec.push_back(in);
}
};
int main() {
Derived<int> d;
Collect<int> c;
c.g(d);
return 0;
}
This results in linking errors, which result from vector being unable
to create a copy of the pure virtual class. Can anyone suggest how I
should solve this?
My first attempted was to make the function in Base virtual, rather
than pure virtual (i.e. virtual void f() {}). This then compiles,
however when the object is extracted from the vector (i.e. I do
vec[0].f() in Collect), the base method is called not that of the
derived class. Any ideas?
I think this should all be standard C++ but I'm using gcc version 4.1.2
to compile this code.
Any help appreciated!