I know that virtual functions should not be called either directly or indirectly in a constructor, but this code runs fine.
Is what I have here safe?
#include <iostream>
#include <string>
struct A {
A (const std::string& name) {std::cout << name << std::endl;}
virtual std::string tag() const = 0;
};
struct B: A {
B() : A (tag()) {}
virtual std::string tag() const override {return "B";}
};
int main() {
B b; // Output gives "B\n"
}
If not, would the following (based on a comment) be a correct workaround?
// Replacement for class B:
struct B: A {
B() : A (name()) {}
virtual std::string tag() const override {return name();}
private:
static std::string name() {return "B";} // use static function
};