Hi, I remember from when I learned PHP, how easy and fun OOP was, and how to call member functions in conjuction (after eachother) on the same line, like this:
MyClass->Foo()->Bar()->Pancakes("flour etc");
To be able to do that, all you needed to do was make a return holding the class itself, like this:
class MyClass{
function Foo(){
echo "Inside Foo";
return $this;
}
function Bar(){
echo "Inside Bar";
return $this;
}
function Pancakes($ingredients){
echo "To make pancakes you need: "+$ingredients;
return $this;
}
}
My questions are:
- Is this achievable in C++?
- How would it look like; an example?
- Is there another way to do this?
- Are these approaches effective and useful?
- Recommendations, suggestions?
It's not required to answer all of them, just answer the ones you want. :)
Here's how I think it could look like:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyClass{
static MyClass myclass;
MyClass Foo();
MyClass Bar();
MyClass Pancakes(string ingredients);
};
MyClass MyClass::Foo(){
cout<<"Inside foo";
return this->myclass;
}
MyClass MyClass::Bar(){
cout<<"Inside bar";
return this->myclass;
}
MyClass MyClass::Pancakes(string ingredients){
cout<<"To make pancakes you need: "+ingredients;
return this->myclass;
}
int main(){
MyClass mc;
MyClass *ptr = &mc;
ptr->Foo()->Bar()->Pancakes("flour etc");
return 0;
}
Although I am quite sure this will give an error, I would at least approach it like so.
One other method doing this could be: creating an additional function with a string parameter that read and seperate each function for every -> or something.