0

How would I do so without making base method virtual?

class Base { public: bool foo() const; } class Derived : public Base{ public: bool foo() const; } 
4
  • 1
    Can you modify the base class at all? Then you might be interested in the curiously recurring template pattern. But if you can modify the base class, it's easier to just make the function virtual to begin with. Commented Oct 21, 2014 at 6:45
  • bool Base::isEmpty() const { Derived d; return d.isEmpty(); }. Commented Oct 21, 2014 at 6:53
  • 3
    @juanchopanza I see you're going by "ask a silly question, get a silly answer" :-) Commented Oct 21, 2014 at 6:53
  • 4
    bigteeth, can you elaborate on why you need this? Currently, the question smells of an X-Y problem. Commented Oct 21, 2014 at 6:54

3 Answers 3

2

There is no any sense to call isEmpty of a derived class from isEmpty of the base class because the base class knows nothing about its derived classes. Take into account that the base class is single while there can be numerous derived classes. So of what derived class are you going to call function isEmpty?

There is sense to call isEmpty of the base class in a derived class. it can be done the following way

bool Derived::isEmpty() const { return Base::isEmpty(); } 
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot. That's why there is a virtual keyword. If your class forbids use of this keyword, I'd rather not use it as a starting point to learn OOP.

Comments

0

If you really need this, you can store a null pointer to a function with the foo's signature in your base class instances, and use the base implementation until this pointer is null. Then you can change this pointer in your derived class and associate is with your derived implementation. Then your base class can call that function via the pointer.

Below is some schematic code for this:

class Base { public: bool foo() const { if (NULL == internalFoo) { // base implementation; } else { return internalFoo(); } } private: bool (*internalFoo)() = NULL; } class Derived : public Base{ public: bool foo() const; } 

4 Comments

Hmmm, this strategy deserves a name! How about..."virtual function"?
This is just implementing a virtual function by hand.
@TonyK, of course it is. But if the case is just not using the 'virtual' keyword, but getting the same effect, why not ;)
The Derived::foo would have to be static to be able to get a normal pointer to it (perhaps taking the first parameter of Base* type and casting it internally to simulate this). With this change, this would be a good answer, IMO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.