Your updated question is illegal because Bar::Options()
returns a reference to a Bar
and you don't provide a way to convert a Bar
to a Foo
object.
C++ Method chaining with classes
-
28-06-2022 - |
Pergunta
I'm attempting to do method chaining, however, instead of using the Methods in "Foo" I want to a constructor of a class (which is inherited from the base class):
class Bar {
public:
Bar() {
std::cout << "This is bar";
}
};
class Foo : public Bar {
public:
Foo() {
cout << "This is foo";
}
};
So my main would look like the following:
Foo f = Foo().Bar();
Why is this not possible in C++/C++11? Also, is there a way in which I can integrate this standard, or would I have to create an method in "Foo" which calls the constructor to "Bar"?
Edit:
class Bar {
public:
Bar() {
}
Bar& Options() {
cout << "sf";
return *this;
}
};
class Foo : public Bar {
public:
Foo() {
}
};
And then in main:
Foo F = Foo().Options();
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow