Reputation: 23
I sincerely hope that people on here don't mind these sorts of questions. After having searched plenty of times, perhaps with the wrong search terms - nevertheless - I do not seem to be able to find ANYTHING on this. Yes, I have looked through cplusplus' documentation, yet I still could not find out the answer.
My question is simple, how do I make it so that a function can only be called via another function?
Here's an example
class someclas{
public:
void screen():
void setsomevariable (int somevariable){}
}clas;
And when I call the function, setsomevariable(), it should only be able to be used after having called the screen function. As such:
clas.screen().setsomevariable(..);
Again, how do I make this function a member of screen() alone?
Upvotes: 1
Views: 333
Reputation: 96266
This does match your requirements, but doesn't necessarily meet your needs. Would like to help more but you're stubbornly refusing to give details...
class Screen {
public:
void setsomevariable (int somevariable) {}
};
class someclas {
Screen s;
public:
Screen& screen() { return s; }
} clas;
Upvotes: 1
Reputation: 13661
A member function belongs to a class. You can't make a function a member of another.
You could keep a boolean in your class, and throw an exception if screen wasnt called before. But it's an ugly solution..
class someclas{
public:
someclas & screen() { // returns a reference to your class to enable the clas.screen().setsomevariable() syntax
screenCalled = true;
return *this;
}
void setsomevariable (int somevariable){
if (!screenCalled) {
throw std::exception();
}
// some code
screenCalled = false;
}
bool screenCalled;
}clas;
Upvotes: 0