0

the formulation of the question is probably tricky and not very clear, but this is what I mean:

I have a base class called Node. This class offers multiple methods that are relevant for any inherited class. My idea was to use a common structure and simply override the constructor and specific methods in the inherited classes.

class Node{
    uint node_id;
    Node(uint id); // Constructor
    callback(); // Callback method
    process(); // Process method
}
class Modified_Node: public Node{
    uint node_id;
    Modified_Node(uint id): Node(id); // New constructor reusing the base constructor
    process(); // New process function
}

The problem here is that the callback method has to call the process method. My idea was to inherit the class and simply override the process method, hoping it would make the callback method call the new process.

void callback(){
    do_something();
    process();
    return;
}

I've realized that callback is still calling the original process method in the template class. It makes sense as I'm not reinstantiating the callback method in any sense but I don't know what is the best way to do this, is it necessary to redefine the function callback completely or is there any way to do this elegantly? To clarify, the code in the callback method is exactly the same.

I've tried to modify the new class, changing the relevant methods, in this case process, in order to make the base method callback call the overridden method instead of the original without any luck.

Roc
  • 43
  • 1
  • 1
  • 8
  • 3
    Are you looking for virtual functions? https://www.learncpp.com/cpp-tutorial/virtual-functions/ – BoP Nov 15 '22 at 09:13
  • 2
    Perhaps you're looking for the chapter(s) covering polymorphism in [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Nov 15 '22 at 09:20
  • 3
    *"I have a template class"* -- this might be a poor choice of words, since it is similar to "[class template](https://en.cppreference.com/w/cpp/language/class_template)", which is often used for nodes, but is not what you have here. – JaMiT Nov 15 '22 at 09:21
  • I agree with @JaMiT. What you have there is a _base_ class. – Paul Sanders Nov 15 '22 at 09:35
  • @BoP, that's it, I guess declaring it as virtual solves my problem, I'll give it a try. thanks – Roc Nov 15 '22 at 09:43

0 Answers0