S
Stefan Nikolaus
Hello,
I've run into problems with defining a template, which inherits from a
base template and the usage of virtual methods in those. I want to
initialize a member variable depending on which template is created and
I tried to define a virtual method, that's called from the base
template ctor. Here's my example code:
#include <iostream>
using namespace std;
template<typename T>
class A
{
public:
A() { cout << "A()" << endl; c = create(); }
virtual ~A() {}
class C
{
public:
virtual ~C() {}
virtual void foo() { cout << "A::C:foo()" << endl; }
};
virtual C* create() { cout << "A::create()" << endl; return new C;
}
C* c;
};
template<typename T>
class B : public A<T>
{
public:
B() : A<T>() { cout << "B()" << endl; }
virtual ~B() {}
class C : virtual public A<T>::C
{
public:
virtual ~C() {}
virtual void foo() { cout << "B::C:foo()" << endl; }
};
virtual typename A<T>::C* create() { cout << "B::create()" << endl;
return new C; }
};
int main( int /*argc*/, char** /*argv*/ )
{
A<int> a;
a.c->foo();
B<int> b;
b.c->foo();
}
Compiling this with gcc 4.1.0 and running it gives me:
A()
A::create()
A::C:foo()
A()
A::create()
B()
A::C:foo()
I've expected, that B::create() will be called on instantiating B<int>.
Why is this not the case?
How do I achieve what I want, preferably by using virtual methods?
Regards,
Stefan
I've run into problems with defining a template, which inherits from a
base template and the usage of virtual methods in those. I want to
initialize a member variable depending on which template is created and
I tried to define a virtual method, that's called from the base
template ctor. Here's my example code:
#include <iostream>
using namespace std;
template<typename T>
class A
{
public:
A() { cout << "A()" << endl; c = create(); }
virtual ~A() {}
class C
{
public:
virtual ~C() {}
virtual void foo() { cout << "A::C:foo()" << endl; }
};
virtual C* create() { cout << "A::create()" << endl; return new C;
}
C* c;
};
template<typename T>
class B : public A<T>
{
public:
B() : A<T>() { cout << "B()" << endl; }
virtual ~B() {}
class C : virtual public A<T>::C
{
public:
virtual ~C() {}
virtual void foo() { cout << "B::C:foo()" << endl; }
};
virtual typename A<T>::C* create() { cout << "B::create()" << endl;
return new C; }
};
int main( int /*argc*/, char** /*argv*/ )
{
A<int> a;
a.c->foo();
B<int> b;
b.c->foo();
}
Compiling this with gcc 4.1.0 and running it gives me:
A()
A::create()
A::C:foo()
A()
A::create()
B()
A::C:foo()
I've expected, that B::create() will be called on instantiating B<int>.
Why is this not the case?
How do I achieve what I want, preferably by using virtual methods?
Regards,
Stefan