There probably is a fairly simple and straight-forward answer for this, but for some reason I can’t see it.
I need to restrict calling methods from a class only to some methods implemented by derived classes of some interface.
Say I have
class A{
public:
static void foo();
};
class myInterface{
public:
virtual void onlyCallFooFromHere() = 0;
}
class myImplementation : public myInterface{
public:
virtual void onlyCallFooFromHere()
{
A::foo(); //this should work
}
void otherFoo()
{
A::foo(); //i want to get a compilation error here
}
}
So I should be able to call A::foo only from the method onlyCallFooFromHere()
Is there a way to achieve this? I’m open to any suggestions, including changing the class design.
EDIT:
So… I feel there’s a need to further explain the issue. I have a utility class which interacts with a database (mainly updates records) – class A.
In my interface (which represents a basic database objects) I have the virtual function updateRecord() from which I call methods from the db utility class. I want to enforce updating the database only in the updateRecord() function of all extending classes and nowhere else. I don’t believe this to be a bad design choice, even if not possible. However, if indeed not possible, I would appreciate a different solution.
[Disclaimer: this solution will stop Murphy, not Macchiavelli.]
How about:
So the basic idea is that your
DatabaseObjectbase class squirrels away a privateQueryobject and a privateUpdateobject and when it comes time to call the protected members of the subclass it hands off theUpdateinterface to theupdateRecord()method, and theQueryinterface to thequeryRecord()method.That way the natural thing for the subclasses is to use the object they are passed to talk to the database. Of course they can always resort to dirty tricks to store away a passed-in
Updateobject and try to use it later from a query method, but frankly if they go to such lengths, they’re on their own.