Visibility of function overloads split between base and derved classes - c++

I'm trying to refactor some visitor-pattern code to remove some code duplication. The crux of this task requires splitting function overloads from an existing API into two: some go into a base class whilst others go into a derived class which extends that base.
Upon trying to split the API between the base and derived classes I hit an unexpected compilation error. Attempting to put aside the visitor-related background to this, I've untangled/distilled my problem into the example (c++11) code that follows:
#include <iostream>
class X
{
public:
virtual const char * name() const =0;
};
class Y : public X
{
public:
virtual const char * name() const override { return "Y"; }
};
class Z : public X
{
public:
virtual const char * name() const override { return "Z"; }
};
class APIBase // The API is split between this base class...
{
public:
virtual void foo(Y & y) =0;
};
class APIDerived : public APIBase // ..and this derived class
{
public:
virtual void foo(Z & z) =0;
};
class APIImplementation : public APIDerived
{
public:
virtual void foo(Y & y) override {
std::cout << "foo(" << y.name() << ")" << std::endl;
}
virtual void foo(Z & z) override {
std::cout << "foo(" << z.name() << ")" << std::endl;
}
};
class A
{
public:
APIDerived & api() { return m_api; }
private:
APIImplementation m_api;
};
int main(int argc, char * argv[])
{
Y y;
Z z;
A a;
a.api().foo(y);
a.api().foo(z);
return 0;
}
The basic idea is that class A provides an implementation of the API defined in APIBase and APIDerived via the call api() which can then act on an object derived from class X and do something different depending on whether it's a Y or a Z.
I would expect this code to give me the following output when run:
foo(Y)
foo(Z)
However, upon compiling this code, gcc gives me the following error:
intf.cpp: In function ‘int main(int, char**)’:
intf.cpp:57:16: error: no matching function for call to ‘APIDerived::foo(Y&)’
a.api().foo(y);
^
intf.cpp:57:16: note: candidate is:
intf.cpp:30:16: note: virtual void APIDerived::foo(Z&)
virtual void foo(Z & z) =0;
^
intf.cpp:30:16: note: no known conversion for argument 1 from ‘Y’ to ‘Z&’
There are two ways I can make this example code compile and give the expected output, but I'm uncertain what differentiates them from the original in the compiler's (or C++ standard's) eyes.
1. Reunite the API by putting both foo() pure function declarations into either APIBase or APIDerived (but not split between them), e.g.:
class APIBase
{
public:
virtual void foo(Y & y) =0;
virtual void foo(Z & z) =0;
};
2. Change class A so that it derives from APIImplementation and ditch the api() redirection calls, e.g.:
class A : public APIImplementation {};
int main(int argc, char * argv[])
{
Y y;
Z z;
A a;
a.foo(y);
a.foo(z);
return 0;
}
I don't want to have to so either of these. Neither do I want to ditch inheritance in favour of templates.
I'm pretty new to C++: please can you help me understand why this example code fails to compile and, if possible, offer workarounds that won't require me to takes steps (1) or (2) above?
Technical details:
Platform: Centos 7, Linux 3.10.0-123.6.3.el7.x86_64
Compiler: gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16)

By default, an f in the base class and an f in a derived class are not treated as overloads and overload is not done between them.
The compiler basically walks backwards through scopes to find a scope where there's at least one item with the name it's looking for. Then it looks at everything with that name in that scope, and does overload resolution on them. If there's something at an outer scope from there (e.g., a parent class) with the same name, it will not be included in that overload resolution.
You can, however, bring the inherited name into scope:
struct base {
void foo(int);
};
class derived : public base {
using base::foo;
void foo();
};
Now, if you call foo in the derived class, the foos from the derived class and the base class are treated as an overload set, so the correct one to call will be based on the argument you pass (or lack thereof).

Related

is there a "semi-pure" virtual function in c++?

Is there a way to write an abstract base class that looks like it's forcing an implementer to choose among a myriad of pure virtual functions?
The abstract base classes I'm writing define a mathematically tedious function, and request that the deriving code define only building block functions. The building block functions can be generalized to take on more arguments, though. For example, in the code below, it might "make sense" to allow another_derived::first() to take three arguments. The "mathematically tedious" part of this is the multiplication by 3. Unsurprisingly, it won't allow won't compile unless I comment out the creation of d2. I understand why.
One option is to create different base classes. One would request a single parameter function to be defined, and the other would request a two parameter function to be defined. However, there would be an enormous amount of code being copy and pasted between the two base class' definition of final_result(). This is why I'm asking, so I don't write WET code.
Another option would be to have one pure virtual function, but change the signature so that its implementation can do either of these things. I want to explore this, but I also don't want to start using fancier techniques so that it puts a barrier to entry on the type of people trying to inherit from these base classes. Ideally, if the writers of the base class could get away with barely knowing any c++, that would be great. Also, it would be ideal if the inheritors didn't even have to know about the existence of related classes they could be writing.
#include <iostream>
class base{
public:
virtual int first(int a) = 0;
int final_result(int a) {
return 3*first(a);
}
};
class derived : public base {
public:
int first(int a) {
return 2*a;
}
};
class another_derived : public base {
public:
int first(int a, int b) {
return a + b;
}
};
int main() {
derived d;
std::cout << d.final_result(1) << "\n";
//another_derived d2; // doesn't work
return 0;
}
Not sure it matches exactly what you want, but with CRTP, you might do something like:
template <typename Derived>
struct MulBy3
{
template <typename... Ts>
int final_result(Ts... args) { return 3 * static_cast<Derived&>(*this).first(args...); }
};
class derived : public MulBy3<derived> {
public:
int first(int a) { return 2*a; }
};
class another_derived : public MulBy3<another_derived > {
public:
int first(int a, int b) { return a + b; }
};
With usage similar to
int main() {
derived d;
std::cout << d.final_result(1) << "\n";
another_derived d2;
std::cout << d2.final_result(10, 4) << "\n";
}
Demo

C++ Errors declaring Interface with return template

I have a base interface, declaration like this - IBaseTest.h:
#pragma once
template <class T1>
class IBaseTest
{
public:
virtual ~IBaseTest();
virtual T1 DoSomething() = 0;
};
And two children who overrides DoSomething() CBaseTest1 claass in - BaseTest1.h:
#pragma once
#include "IBaseTest.h"
class CBaseTest1: public IBaseTest<int>
{
public:
virtual int DoSomething();
};
BaseTest1.cpp:
#include "BaseTest1.h"
int CBaseTest1::DoSomething()
{
return -1;
}
And CBaseTest2 in - BaseTest2.h
#pragma once
#include "IBaseTest.h"
class CBaseTest2: public IBaseTest<long long>
{
public:
virtual long long DoSomething();
};
BaseTest2.cpp:
#include "BaseTest2.h"
long long CBaseTest2::DoSomething()
{
return -2;
}
So CBaseTest1::DoSomething() overrides return type to int, and CBaseTest2::DoSomething() to long long. Now, i want to use a pointer to the base interface, to work with those classes, and there i have the problem:
#include "IBaseTest.h"
#include "BaseTest1.h"
#include "BaseTest2.h"
int _tmain(int argc, _TCHAR* argv[])
{
IBaseTest<T1> * pBase = NULL;
pBase = new CBaseTest1();
cout << pBase->DoSomething() << endl;
pBase = new CBaseTest2();
cout << pBase->DoSomething() << endl;
getchar();
return 0;
}
The problem is i cannot declare IBaseTest<T1> * pBase = NULL; T1 is undefined. If declare the template before _tmain like this:
template <class T1>
int _tmain(int argc, _TCHAR* argv[])
{
...
}
I get: error C2988: unrecognizable template declaration/definition
So what do i put here instead of T1?
IBaseTest<??> * pBase = NULL;
The problem is that T1 parameter needs to be known when you instantiate an object of the template class IBaseTest. Technically, IBaseTest<int> and IBaseTest<long long> are two different types without a common base and C++ does not allow you to declare a variable IBaseTest<T1> pBase = NULL; where T1 is determined at runtime. What you are trying to achieve is something that would be possible in a dynamically typed language, but not in C++ because it is statically typed.
However, if you know the expected return type of DoSomething whenever you call that method, you can sort of make your example to work. First, you need to introduce a common base class that is not a template:
#include <typeinfo>
#include <typeindex>
#include <assert.h>
class IDynamicBase {
public:
virtual std::type_index type() const = 0;
virtual void doSomethingVoid(void* output) = 0;
template <typename T>
T doSomething() {
assert(type() == typeid(T));
T result;
doSomethingVoid(&result);
return result;
}
virtual ~IDynamicBase() {}
};
Note that it has a template method called doSomething that takes a type parameter for the return value. This is the method that we will call later.
Now, modify your previous IBaseTest to extend IDynamicBase:
template <class T1>
class IBaseTest : public IDynamicBase
{
public:
std::type_index type() const {return typeid(T1);}
void doSomethingVoid(void* output) {
*(reinterpret_cast<T1*>(output)) = DoSomething();
}
virtual T1 DoSomething() = 0;
virtual ~IBaseTest() {}
};
You don't need to change CBaseTest1 or CBaseTest2.
Finally, you can now write the code in your main function like this:
IDynamicBase* pBase = nullptr;
pBase = new CBaseTest1();
std::cout << pBase->doSomething<int>() << std::endl;
pBase = new CBaseTest2();
std::cout << pBase->doSomething<long long>() << std::endl;
Note that instead of calling pBase->DoSomething(), we now call pBase->doSomething<T>() where T is a type that must be known statically where we call the method and we provide that type at the call site, e.g. pBase->doSomething<int>().
The language does not allows to do directly what you are trying to do. At that point, you should ask yourself if that is the right solution for the problem.
The first approach that might work well assuming that you don't have too much different operations to do for each type would be to simply do the action in the function itself instead of returning type that are not related through inheritance.
class IBaseTest
{
public:
virtual void OutputTo(std::ostream &os) = 0;
};
class CBaseTest1
{
public:
virtual void OutputTo(std::ostream &os) override;
private:
int DoSomething();
};
void CBaseTest1OutputTo(std::ostream &os)
{
os << DoSomething() << std::endl;
}
If you have only a few types but a lot of operation, you might use the visitor pattern instead.
If you mainly have operation that depends on type, you could use:
class IVisitor
{
public:
virtual void Visit(int value) = 0;
virtual void Visit(long value) = 0;
};
Otherwise, use that which is more general
class IVisitor
{
public:
virtual void Visit (CBaseTest1 &test1) = 0;
virtual void Visit (CBaseTest2 &test2) = 0;
};
Then in your classes add an apply function
class IBaseTest
{
public:
virtual void Apply(IVisitor &visitor) = 0;
};
In each derived class, you implement the Apply function:
void CBaseTest1 : public IBaseTest
{
virtual void Apply(IVisitor &visitor) override
{
visitor.Visit(this->DoSomething()); // If you use first IVisitor definition
visitor.Visit(*this); // If you use second definition
};
And for creation purpose, you could have a factory that return the appropriate class from a type tag if you need to create those class from say a file…
One example assuming you want a new object each time:
enum class TypeTag { Integer = 1, LongInteger = 2 };
std::unique_ptr<IBaseTest> MakeObjectForTypeTag(TypeTag typeTag)
{
switch (typeTag)
{
case TypeTag::Integer : return new CBaseTest1();
case TypeTag::LongInteger : return new CBaseTest2();
}
}
So the only time you would do a switch statement is when you are creating an object… You could also use a map or even an array for that...
The right approach depends on your actual problem.
How many CBaseClass* do you have?
Do you expect to add other classes? Often?
How many operations similar to DoSomething() do you have?
How many actions that works on the result of DoSomething do you have?
Do you expect to add other actions? Often?
By responding to those questions, it will be much easier to take the right decision. If the action are stables (and you only have a few one), then specific virtual functions like OutputToabove is more appropriate. But if you have dozen of operation but don't expect much changes to ITestBase class hierarchy, then visitor solution is more appropriate.
And the reason why a given solution is more appropriate in a given context is mainly the maintenance effort when adding classes or actions in the future. You typically want that the most frequent change (adding a class or an action) require les changes everywhere in the code.

How to pass an implemented virtual member function as a parameter

#include <iostream>
class virtualClass{
public:
virtual int a() = 0;
};
class UnknownImplementation : public virtualClass{
public:
int a() override { return 1;}
};
class myFramework {
public:
int c(int (virtualClass::*implementedFunc)(void)){
implementedFunc();
return 2;
}
};
int main(){
//some user implements the virtual class and calls myFramework function
myFramework* mfp = new myFramework();
std::cout << mfp->c(&(UnknownImplementation::a)) << std::endl;
}
Hi, I am working on a framework that is supposed call an implemented virtual function and use it. It is similar to the code above.
The compiling errors I get are:
testVirtual.cpp: In member function ‘int myFramework::c(int (virtualClass::)())’: testVirtual.cpp:16:19: error: must use ‘.’ or
‘->’ to call pointer-to-member function in ‘implementedFunc (...)’,
e.g. ‘(... -> implementedFunc) (...)’ implementedFunc();
^ testVirtual.cpp: In function ‘int main()’: testVirtual.cpp:24:47: error: invalid use of non-static member
function ‘virtual int UnknownImplementation::a()’ std::cout <<
mfp->c(&(UnknownImplementation::a)) << std::endl;
How do I fix these problems?
Thanks in advance!
passing an instance of the implemented class and calling the function worked.
To build on sameerkn's comment, this code should be:
#include <iostream>
class virtualClass{
public:
virtual int a() = 0;
};
class mySubclass : public virtualClass{
public:
int a() override { return 1;}
};
int main(){
mySubclass * x= new mySubclass ();
// ...
std::cout << x->a () << std::endl;
}
The point here is that you can pass objects (or pointers) of type virtualClass around - even though they might actually be mySubclass objects in real life - and still wind up in the right implementation of a(). myFramework is entirely unnecessary.
That's what virtual methods are for - consumers of virtualClass don't need to know anything about classes that might - now or in the future - be derived from it, and if I have read your question correctly, this is what you want.

polymorphism and encapsulation of classes

I'm trying to take advantage of the polymorphism in c++, but I'm from a c world, and I think what I've done could be done more cleverly in a OOP way.
I have 2 classes that has exactly the same public attributes, and I want to "hide" that there exists 2 different implementations. Such that I can have a single class where I can use the member functions as If i were accessing the specific class.
An very simple implementation of what I'm trying to accomplish is below:
#include <iostream>
class subber{
private:
int id;
public:
int doStuff(int a,int b) {return a-b;};
};
class adder{
private:
int id;
public:
int doStuff(int a, int b) {return a+b;};
};
class wrapper{
private:
int type_m;
adder cls1;
subber cls2;
public:
wrapper(int type) {type_m=type;};//constructor
int doStuff(int a, int b) {if(type_m==0) return cls1.doStuff(a,b); else return cls2.doStuff(a,b);};
};
int main(){
wrapper class1(0);
std::cout <<class1.doStuff(1,3) <<std::endl;
wrapper class2(1);
std::cout <<class2.doStuff(1,3) <<std::endl;
return 0;
}
I have 2 classes called "subber" and "adder" which both have a member function called doStuff, which will either subtract of add 2 numbers.
This I wrap up in a class "wrapper", which has both "adder" and "subber" as private variables, and a doStuff public member function. And given which value I instantiate my "wrapper" class with, my "wrapper" class will simply relay the "doStuff" to the correct class.
This code does of cause work, but I would like to avoid instatiating both "subber" and "adder" in my wrapper class, since I will only need of them in each of my "wrapper" classes.
Thanks
There are many ways to do it. Through a Factory for example.
But to keep it simple - make a base abstract class that defines the interface, and derive your classes from it to implement the functionality. Then you only need to make the distinction once, when you create the class, after that you don't care, you just call the interface functions.
your code would look something like that.
class DoStuffer
{
public:
virtual int doStuff(int, int)=0;
virtual ~DoStuffer(){}; // Because Tony insists:-) See the comments
}
class subber: public DoStuffer{
public:
virtual int doStuff(int a,int b) {return a-b;};
};
class adder: public DoStuffer{
public:
virtual int doStuff(int a, int b) {return a+b;};
};
int main(){
DoStuffer *class1 = new adder();
DoStuffer *class2 = new subber();
std::cout <<class1->doStuff(1,3) <<std::endl;
std::cout <<class2->doStuff(1,3) <<std::endl;
delete class1; // don't forget these:-)
delete class2;
return 0;
}
This is one of the more idiomatic ways to use the C++ class system to accomplish what you want. Both adder and subber publicly inherit from wrapper, which is now an abstract base class. The doStuff method is now a (pure) virtual function. And instead of being a simple instance of wrapper, the "encapsulated" object is now a reference to a wrapper.
#include <iostream>
class wrapper {
public:
virtual int doStuff(int a, int b) = 0;
};
class subber : public wrapper {
public:
virtual int doStuff(int a,int b) {return a - b;}
};
class adder : public wrapper {
public:
virtual int doStuff(int a, int b) {return a + b;}
};
int main(){
// actual objects
adder impl1;
subber impl2;
// in real code, the wrapper references would probably be function arguments
wrapper& class1 = impl1;
std::cout << class1.doStuff(1,3) << std::endl;
wrapper& class2 = impl2;
std::cout << class2.doStuff(1,3) << std::endl;
return 0;
}
(Not using any factory pattern in this example, since it's not obvious that it's needed or what the question is about.)
Exactly what was last said.
Make a base class, and have a virtual function |doStuff| in it.
Then you can derive any number of classes out from it, all have to implement the above virtual function, in whatever way they want to.
Then you can just do the following
BaseClass *object1 = new DerivedClass1();
BaseClass *object2 = new DerivedClass2();
..
You can even do
object1 = object2;
And then they point to the same object (i.e. an object of type |DerivedClass2|)
But remember, when you do objectn->doStuff(), the function that will be executed will be what the pointer points to at run-time, and not at compile time.
i.e. if I do object1->doStuff() DerivedClass2's doStuff will be called because we already did `object1 = object2;
You may want to Google and read about
Polymorphism/ Run-time Polymorphism
Virtual Functions in C++
You can read Factory Method, which is something that is known as a Design Pattern, but later in life.
Thanks
The classic run-time polymorphic approach is:
struct Operation
{
virtual ~Operation() { } // guideline: if there are any virtual functions,
// provide virtual destructor
virtual int doStuff(int, int) const;
};
struct Subber : Operation
{
int doStuff(int a, int b) const { return a - b; }
};
struct Adder : Operation
{
int doStuff(int a, int b) const { return a + b; }
};
enum Operations { Add, Subtract };
struct Operation* op_factory(Operations op)
{
if (op == Add) return new Adder;
if (op == Subtract) return new Subber;
throw std::runtime_error("unsupported op");
}
int main()
{
Operation* p1 = op_factory(Add);
std::cout << p1->doStuff(1,3) <<std::endl;
Operation* p2 = op_factory(Subtract);
std::cout << p2->doStuff(1,3) <<std::endl;
delete p1;
delete p2;
}
From the Standard 5.3.5/5 "In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined.", which is why you must use the virtual keyword on the base class destructor.
It's noteworthy that in your example the type of operation to perform was communicated to the wrapper class using a function argument of 0 or 1... this is what suggests you want run-time polymorphism. For example, if the 0 or 1 value was based on a command line argument, file content, keyboard input etc., then the factory method above can pass a corresponding Add or Subtract value and receive an appropriately-behaving object derived from Operation. This concept of creating an instance of a run-time polymorphic type based on run-time values is known as a factory.
If you really only need compile-time polymorphism, you can do some interesting things with templates such as:
template <class Operation>
void output(int a, int b)
{
std::cout << Operation::doStuff(a, b) << std::endl;
std::cout << Operation::doStuff(a * 10, b * 10) << std::endl;
std::cout << Operation::doStuff(a * 100, b * 100) << std::endl;
}
int main()
{
output<adder>(1, 3);
output<subber>(1, 3);
}
FWIW, your approach is probably slightly faster than the virtual function approach (as it can potentially do more inlining), but not as clean, extensible, maintainable or scalable.
I think what you're looking for is virtual functions. If you declare a function virtual in your base class, you can do things like make a vector containing multiple objects derived from your base class, but when you call on a particular object it will execute it's own method.

Why do I get linker errors trying to build C++ code using pure virtual functions within a template?

In an application I'm currently writing, I created a template class with a pure virtual function, then an another class inheriting an instance of the former and implementing the virtual function. The virtual function is called from the parent's constructor, which is used by the child also. I can't build this code due to linker errors and I can't figure out why. Here's a simplified version of the code to reproduce the issue I'm having.
template <typename T> class Foo
{
public:
Foo(T a)
{
x = a;
echo();
}
protected:
T x;
virtual void echo() = 0;
};
class Bar : public Foo<int>
{
public:
Bar(int a) : Foo<int>(a)
{
}
void echo();
};
void Bar::echo()
{
cout << "value: " << x << endl;
}
int main(int argc, char* argv[])
{
Bar bar(100);
return 0;
}
The linker error appears as follows in MSVC:
purevirttest.obj : error LNK2019: unresolved external symbol "protected: virtual void __thiscall Foo::echo(void)" (?echo#?$Foo#H##MAEXXZ) referenced in function "public: __thiscall Foo::Foo(int)" (??0?$Foo#H##QAE#H#Z)
If I move the call to echo() from Foo's constructor, the code builds and executes nicely, I can call bar.echo() without any problems. Problem is I'd really like that function in the constructor. Any explanation of this mystery higly appreciated.
James McNellis' answer that "You can't call echo() from the constructor of Foo<T>" is almost correct.
You can't call it virtually from a Foo<T> constructor, because while the body of the Foo<T> constructor executes the object is of type Foo<T>. There's no derived class part yet. And a virtual call of echo(), as in your code, then goes to pure virtual function: bang, dead.
However, you can provide an implementation of a pure virtual function like echo(), and then call it non-virtually, like Foo::echo(), from the Foo constructor. :-) Except that that calls the Foo implementation. While it seems you'd like to call the derived class' implementation.
Now regarding your problem:
"I'd really like that function in the
constructor."
Well, as I'm writing this your (invalid) code looks like this:
template <typename T> class Foo
{
public:
Foo(T a)
{
x = a;
echo();
}
protected:
T x;
virtual void echo() = 0;
};
class Bar : public Foo<int>
{
public:
Bar(int a) : Foo<int>(a)
{
}
void echo();
};
void Bar::echo()
{
cout << "value: " << x << endl;
}
int main(int argc, char* argv[])
{
Bar bar(100);
return 0;
}
And as far as I understand your problem description, you want the Foo constructor to call the echo implementation of whatever class it is that inherits from Foo.
There are a number of ways to do that; they're all about bringing knowledge of the derived class' implementation to the base class.
One is known as CRTP, the Curiously Recurring Template Pattern, and adapted to your particular problem it can go like this:
#include <iostream>
template< class XType, class Derived >
class Foo
{
public:
Foo( XType const& a )
: state_( a )
{
Derived::echo( state_ );
}
protected:
struct State
{
XType x_;
State( XType const& x ): x_( x ) {}
};
private:
State state_;
};
class Bar
: public Foo< int, Bar >
{
private:
typedef Foo< int, Bar > Base;
public:
Bar( int a ): Base( a ) {}
static void echo( Base::State const& );
};
void Bar::echo( Base::State const& fooState )
{
using namespace std;
cout << "value: " << fooState.x_ << endl;
}
int main()
{
Bar bar(100);
}
The above is a solution that isn't bad, but isn't good either. If your actual problem is to call a derived class non-static member function from the base class constructor then the only "good" answer is Java or C#, which let you do such thing. It's intentionally not supported in C++, because it's very easy to then inadvertently try to access as-yet uninitialized stuff in the derived class object.
Anyways, as nearly always, where there is a compile time solution of something, there's also a run time solution.
You can simply pass the function to be executed as a constructor argument, like so:
#include <iostream>
template< class XType >
class Foo
{
protected:
struct State
{
XType x_;
State( XType const& x ): x_( x ) {}
};
public:
Foo( XType const& a, void (*echo)( State const& ) )
: state_( a )
{
echo( state_ );
}
private:
State state_;
};
class Bar
: public Foo< int >
{
private:
typedef Foo< int > Base;
public:
Bar( int a ): Base( a, echo ) {}
static void echo( Base::State const& );
};
void Bar::echo( Base::State const& fooState )
{
using namespace std;
cout << "value: " << fooState.x_ << endl;
}
int main()
{
Bar bar(100);
}
If you study those two programs you'll probably note a subtle difference (in addition to compile time versus run time knowledge transfer).
Finally, there are solutions involving dirty casts and there is also a loophole in the C++ type system that lets you access that protected base class state without casting, by using member pointers. The former is dangerous and latter is obscure and possibly inefficient. So, don't.
But hopefully one of the solutions above will suit you, or some suitable adaption.
Oh, by the way, the more general set of problems that yours seems to be an instance of, is known as DBDI, Dynamic Binding During Initialization. You can find a more general treatment of it in the C++ FAQ item 23.6 Okay, but is there a way to simulate that behavior as if dynamic binding worked on the this object within my base class's constructor?. Also, for the special case where the DBDI is that you want a part of the base class construction to be controlled/supplied by the derived class, see my blog entry "How to avoid post-construction by using Parts Factories".
Cheers & hth.,
You can't call echo() from the constructor of Foo<T>.
Inside of the constructor of Foo<T>, the dynamic type of the object is Foo<T>. It's not until after the Foo<T> constructor finishes that the dynamic type becomes Bar.
Since echo() is pure virtual in Foo<T> and since Foo<T> is the dynamic type of the object, you cannot call echo() in the constructor of Foo<T>.
Unless you are very familiar with how the dynamic type of an object changes during construction and destruction, it would be a good idea not to try calling virtual functions from constructors and destructors.