How to deal with "super" calls and recursion - c++

My question is about merging 2 techniques:
Call recursively to super functions
Call recursively to the same function
Suppose a root class that has a recursive function (foo), and a extended class that override this function ( foo): the override function must call super::foo, but require to perform other operations before to call recursively.
I will try an example (it is only an example, and I know there is non-recursive way to solve this problem)
class Node
{
public:
// must be override
virtual int getNumValues()
{
if (parent) return parent->getNumValues() + 3;
else return 3;
}
protected:
Node *parent;
private:
int values[3];
};
class ExtNode: Node
{
public:
//#override
virtual int getNumValues()
{
int aux = Node::getNumValues(); //but need to avoid recursion here.
if (parent) return parent->getNumValues() + aux + 2;
else return aux + 2;
}
private:
int extValues[2];
};
So what I would is:
I may change both classes: Node and ExtNode.
I would not to copy the code from the first class method to the second to avoid Super call (the class chain may be long)
The recursive call should probably be done by the childest class
I am trying some ideas, but they seem poor programming practice or not possibles:
// In Node class
...
virtual int getNumValues()
{
if (parent && !isNodeObject(this)) return parent->getNumValues()+3;
else return 3;
}
bool isNodeObject( Node *ob)
{
//return if ob is instance of Node (and not an extended class). How?
}
I have also tried with optional parameters:
// In Node class
...
virtual int getNumValues( bool recursion = true)
{
if (parent && recursion) return parent->getNumValues()+3;
else return 3;
}
// In ExtNode class
...
virtual int getNumValues( bool recursion = true)
{
int aux = Node::getNumValues(false );
if (parent && recursion) return parent->getNumValues() + aux + 2;
else return aux + 2;
}
What is the best programming practice for that?
EDIT 1: Explanation of the real problem I am trying to resolve (asked from Joachim Pileborg)
I am creating a User interface library, that is, a set of classes and function to create easily widgets like frame, buttons, input texts, etc.
I have created a basic (root class) widget with most general features, a "Visible" widget to implement all generic functions for widgets that has a visible part, and soo on.
There are also some containers, like frames, layout and windows.
Now come the hard part: there is a function "updateStyle" that is supposed to update at once all the graphic part of the widget (and redraw it): this function call recursively to super class to perform more generic features, and also has to call recursively to containers to propagate changes (dimensions and positions of widgets may change)
Each widget is supposed to work "as this" and also to be extendable, that is why these requirements.
Code is extensive (about 8k lines) and has a lot of other features, so no point to copy here
the code.

It looks like you are searching for the template method pattern:
in the base class, implement a nonvirtual method that outlines the general behavior of the function.
define (abstract) virtual methods that define the special behavior parts inside that function
in derived classes, override the special behavior
class Node
{
public:
int getAllNumValues()
{
int allNumValues = getNumValues();
if (parent) allNumValues += parent->getAllNumValues();
return allNumValues;
}
protected:
virtual int getNumValues() {
return 3;
};
private:
Node *parent;
int values[3];
};
class ExtNode: Node
{
protected:
//#override
virtual int getNumValues()
{
return 2 + Node::getNumValues(); //but need to avoid recursion here.
}
private:
int extValues[2];
};
in case of your update functionality I'd suggest to have a template method update that does the recursive updating of your composite pattern, and another method updateThis that does updating of only the single object.

According to Herb Sutter's article: Virtuality, we should prefer to make virtual functions private. This implies that we should try to avoid calling "super" versions and instead make the base class do the work.
Here's an example:
class Node
{
public:
int getNumValues()
{
int result = 3 + DoGetNumValues();
if (parent)
result += parent->getNumValues();
return result;
}
private:
Node *parent;
int values[3];
virtual int DoGetNumValues() {return 0;}
};
class ExtNode : public Node
{
private:
int extValues[2];
int DoGetNumValues() override sealed {return 2 + GetMoreValues();}
virtual int GetMoreValues() {return 0;}
};
class Derived : public ExtNode
{
int GetMoreValues() override {return 1;}
};

For the first example,
Node::getNumValues() computes some function of a tree.
ExtNode::getNumValues() computes another function of a tree. Either result of
ExtNode::getNumValues() is function of ( Node::getNumValues(), tree ) or it depends on tree only.
For UI problem,
Think about chain of responsibility design pattern. Forward update request up to the root node, which in its turn initiates tree traversal to update all nodes starting from root.

One way to deal with this is to make the function non virtual, then explicitly call in each override the super classe's function (similar to the constructor).
Having the method non-virtual means that each class that is inherited will have it's own implementation of the method, so you won't overwrite the classe's parent code by writing a implementation of the function.
The downside will be that you will have to call the function via a pointer that is explicitly of a certain type, thus forcing you to know the type.
To avoid this drawback, make a virtual function that calls the required recursive function, and use that function instead.
As a side note, non-virtual functions should be avoided.
Here's a sample code
class base
{
public:
int doStuff()
{
printf(" base called ");
return 0;
}
};
class ext : public base
{
public:
int doStuff()
{
base::doStuff();
printf(" ext called ");
return 0;
};
};
class ext2 : public ext
{
public:
int doStuff()
{
ext::doStuff();
printf(" ext 2 called");
return 0;
};
};
void runTest()
{
base* ptr = new ext2();
ptr->doStuff();
ext2* recast = (ext2*) ptr;
recast->doStuff();
}
For the code above, the output will be " base called base called ext called ext2 called".
If you declare the doStuff function virtual in the base class (thus making it virutal for every child class) the output will be " base called ext called ext2 called base called ext called ext2 called".

Related

How can I choose the algorithm of a code only once at the beginning in C++?

There are two different algorithms being used throughout the code. Which one is chosen is determined at runtime by a parameter (e.g. true or false). I do not want to use if-statements each time the algorithm comes up.
So instead of writing the following every time
if (parameter==true)
algorithmOne();
else
algorithmTwo();
I want to set the algorithm at the beginning, like
if (parameter==true)
algorithm()=algorithmOne();
else
algorithm()=algorithmTwo();
and only use 'algorithm()' from this point forward.
How can I choose the algorithm at the beginning depending on a parameter after the code is already compiled?
Edit:
How do you do that within the constructor of a class (since a pointer-to-member function is no regular pointer)? As both algorithms rely on member variables and functions of this class, it is inconvenient to derive a new class.
Solution:
This could be solved with a virtual function and derived classes.
class Base
{
public:
Base();
virtual void algorithm() = 0;
~Base();
protected:
double d;
int i;
...
}
class DerivedOne : public Base
{
public:
DerivedOne() : Noise() {};
void algorithm() override;
~DerivedOne();
};
Base *b;
if (parameter==true)
{
b = new DerivedOne();
}
else
{
b = new DerivedTwo();
}
Then the function can be called with:
b->algorithm();
And deleted with:
delete b;
This may not be the best way but it seems to work for me. See answers and comments.
You're almost there:
auto algorithm = parameter ? algorithmOne : algorithmTwo.
No (), you're not trying to call any function here.
The answer you are looking for is likely a function/method pointer.
The syntax for a function pointer is as follows:
typedef void (*MyFunctionPointer)();
MyFunctionPointer *algorithm;
void function(bool parameter)
{
if (parameter)
algorithm = &myFirstAlgo;
else
algorithm = &mySecondAlgo;
}
void anotherFunction()
{
algorithm();
}
Please note that this approach works for C, C++03 and C++11. If you want to use auto on the global scope, you need to give it a default value.
The object-oriented way of doing this would be to define a base class with the algorithm interface:
class AlgorithmBase
{
public:
virtual void algorithm() = 0;
virtual ~AlgorithmBase() {} // virtual destructor may be needed
};
Then implement classes for the different algorithm implementations:
class AlgorithmOne: public AlgorithmBase
{
public:
virtual void algorithm();
};
void AlgorithmOne::algorithm()
{
...
}
and similarly for AlgorithmTwo and other implementations.
Now, you can define a pointer to an algorithm object containing the selected implementation and use that whenever the algorithm shall be executed:
AlgorithmBase *algorithm = 0;
if(parameter)
{
algorithm = new AlgorithmOne();
}
else
{
algorithm = new AlgorithmTwo();
}
...
algorithm->algorithm(); // Call the selected algorithm
...
delete algorithm; // Destroy algorithm instance before exiting

How can I access member functions of STL classes inside derived classes that aren't in the base class? (detailed explanation in body)

Right now I have a base class, class Base{}, with two classes deriving from it, BFS{} and DFS{}. BFS has queue, and DFS has stack, so they both have a member called "nodes", but the type is their respective std::queue and std::stack. My search function takes in a pointer to base class as its parameter so that it can accept both derived classes, and runs the search by pushing and popping from the member classes inside the derived classes (as per the usual DFS BFS algorithms). The issue is, since I passed in my base class as the parameter, whenever I try to call push or pop on the member stack/queue called "nodes" from the derived classes, it always says that the push/pop cannot be done because there is no member inside the base class called "nodes". How am I supposed to make this work?
Also, this setup is a requirement of the assignment I am doing and I just can't figure out how this is supposed to work, any help is appreciated.
Thanks!
class Base {
public:
virtual void push(uint64_t roomID, float intensity, int distance) = 0;
virtual Node pop(void) = 0;
virtual int size(void) = 0;
};
class Breadth : public Base {
public:
std::queue<std::pair<uint64_t, int>> U;
void push(uint64_t roomID, float intensity, int distance) { std::pair<uint64_t, int> p(roomID, distance); U.push(p); }
Node pop() { Node rr; rr.ID = U.front().first; rr.distance = U.front().second; U.pop(); return rr; }
int size() { return U.size(); }
};
class Depth : public Base {
public:
std::stack<std::pair<uint64_t, int>> U;
void push(uint64_t roomID, float intensity, int distance) { std::pair<uint64_t, int> p(roomID, distance); U.push(p); }
UnexploredRoom pop() { U.pop(); }
int size() { U.size(); }
};
void robotSearch::searchLoop(Base* search, Discovered* D, uint64_t roomID)
{
Node room;
room.ID = roomID;
room.distance = 0;
search->U.push(room); //problem here, compiler wont let me push U
...
}
To implement custom behaviour through a pointer to a base class, you need to use virtual functions. Another approach would be to use generic code with templates.
Example:
class Base {
public:
virtual ~Base() {}
virtual void push(int i) = 0;
virtual int pop() = 0;
};
class DFS : public Base{
public:
virtual void push(int i) override { /*...*/ }
virtual int pop() override { /*...*/ return {}; }
};
class BFS : public Base {
public:
virtual void push(int i) override { /*...*/ }
virtual int pop() override { /*...*/ return {}; }
};
Right now, you have some virtual methods push and pop, but for some reason, you don't use them and instead try to access a member of the derived classes instead. You seem to have copied code from the answer by Ayjay but not applied it correctly.
That member U should really not be exposed like this, that is, it should be private, and you should use your class methods to manipulate it.
Therefore, you wouldn't write
search->U.push(room);
even if it was legal here (which it isn't, as the base class does not have anything named like that).
Instead, you go with
search->push(room);
Note that I omitted the other arguments that this takes, of course you also have to provide values for your intensity and distance arguments.
Doing so will call the appropriate method, that is either Breadth::push or Depth::push, which then will access the corresponding member of the respective class.
By the way, for reasons of control, you should use the override keyword as Ayjay did, and also, you should give a member a more descriptive name that U.

Designing A class with multiple set of method implementation [c++]

I am working on an existing project which has one class for which I need an alternate member function definition. I don't want to modify existing member functions or their signatures, just an alternate definition which has to be selected run time based on some xml file (Compile time flag not preferred).
I am new to C++, so this may be a stupid question.
Please suggest design guidelines such that I don't have to change and test existing code base, and just plug my implementation.
Example
class ABC{
public:
int operate(int, int);
}
//Assume below method to be existing implementation
ABC::operate(int op1, int op2)
{
return op1+ op2; //add
}
//Alternate desired implementation
ABC::operate(int op1, int op2)
{
return op1 * op2; //multiply
}
Ideally I would want above to be run time selection but can fall to compile time if thats the only way.
note this thread Reason for C++ member function hiding regarding name-hiding in inheritence.
When a derived class implements a NON VIRTUAL method with the same name as in the base class, that method in the base becomes hidden, and only the derived method can be used - through objects of static type Derived.
My suggestion for you is to implement something like
class ABC{
public:
int operate(int, int);
};
//Assume below method to be existing implementation
ABC::operate(int op1, int op2)
{
return op1+ op2; //add
}
Now, for your extended functionality, derive from ABC (sidenote: inheritence or composition is another discussion, read about it on google).
class Derived : public ABC{
operate(int op1, int op2){
return op1 * op2; //multiply
}
}
Now, wherever you need your new functionality, change the static type of the calling object to Derived, and the derived operate will be called.
A more logical solution is possible if it is possible to change ABC's operate's signature to virtual int operate(int,int);, then polimorphism could take place, and accessing operate through reference types anywhere would invoke the operate that belongs to the dynamic type of the calling object.
Thus, you would only have to instantiate your object to be of type Derived rather than ABC.
Note that virtual method usage is not possible if operate is static, and it was unclear here if that is the case.
I was preparing an answer but Gulzar answered meanwhile ( end of his answer )
What you need is a base notion/mechanism in C++ called dynamic binding ( maybe you learned it also meanwhile as your post is 1 month old )
#include <iostream>
#include <cstddef>
using namespace std;
class ABC_Base
{
public:
//pure virtual member function
//compelling effective creation of the
//function in the daughter classes
virtual int operate(int,int) = 0;
//virtual xtor as base will be derived
virtual ~ABC_Base() {}
};
class ABC_M1 : public ABC_Base
{
int operate (int a, int b ) {return a+b; }
};
class ABC_M2 : public ABC_Base
{
int operate (int a, int b ) {return a*b; }
};
ABC_Base * createABC(string xml_filename)
{
int criterion = 0;
// nullptr need at least c++11 option
ABC_Base * ptr = nullptr;
//read xml file and update criterion
//see other post to do that
//criterion = ...
switch(criterion)
{
case 0:
ptr = new ABC_M1();
break;
case 1:
ptr = new ABC_M2();
break;
default:
break;
}
return ptr;
}
int main()
{
ABC_Base * ptr = createABC("My_Config.xml");
if (nullptr != ptr)
{
cout << ptr->operate(3,4) << endl;
}
// If you absolutely want / have to use plain old pointers
// do not forget to release things
// works even if ptr is null, so unconditional delete
delete(ptr);
return 0;
}

What design pattern should I use to avoid dummy code here?

I have a base class -
class content
{
private:
int m_data;
public:
int getdbhandle() { return m_sql_db; }
void setData(int data) { m_data = data; }
virtual int getterrestrialServices { qDebug()"This is a dummy interface"; }
};
class telecontent: public content
{
virtual int getterrestrialServices { qDebug()" Real implementation here"; }
};
Now, the class content is instantiated as telecontent, when the product type is tele.
However, when the product type is generic - the dummy interface prints keep coming.
How can I avoid so? Is there any design pattern that forces the base class not to implement the dummy function? I want an efficient way so that only derived class has method. I don't want the base class to have that method. But, I can't modify the caller - code- so that the method is not called. I want the best way to strategically design such that the dummy interface can be avoided.
is there any design pattern that forces the base class not to
implement the dummy function?
Pure virtual allows this:
class content
{
private:
int m_data;
public:
virtual ~content() { }
int getdbhandle() { return m_sql_db; }
void setData(int data) { m_data = data; }
virtual int getterrestrialServices() = 0; // pure virtual
};
This means no one can create instances of content (will cause a compiler error), and so when some one inherits from content they must provide an implementation of getterrestrialServices() (else again, they'll get a compiler error).
What you need is pure virtual like so:
virtual int getterrestrialServices() = 0;
It will force every class the inherits content to implement it and you wont be able to create a content class, only classes the inherit from it so you wont have the dummy prints.

Possibility to mix composite pattern and curiously recurring template pattern

I have a composite pattern implementation, used for GUI components:
class CObject {
private:
CObject * m_pParent;
CObjectContainer * m_pChildren;
void private_foo() {
this->foo();
//Calls private_foo for each child in container.
m_pChildren->foo();
}
public:
virtual void foo() {
//empty for base class
}
virtual CObject * duplicate() {
//Do duplication code
return new CObject(*this);
}
virtual CObject * detach() {
//Remove this object (along with it's children)
//from current tree.
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return this;
}
}
class CSpecificObject : public CObject {
public:
virtual void foo() {
//Specific code for this class
}
virtual CSpecificObject * duplicate() {
//Overload, but the code only calls diferent constructor
return new CSpecificObject(*this);
}
virtual CSpecificObject * detach() {
//Note the code is identical.
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return this;
}
}
Unfortunately the number of inherited classes increases rapidly and the duplicate code (in given example only the detach() method) is giving me a headache.
Is there a way to cleanly implement detach() methods, keeping the return type the same as the object, on which it is called?
I was thinking about CRTP, but I can not think of a way to keep the dynamic polymorphism along with compile time polymorphism:
template <Child>
class CObject {
private:
...
Child * detach() {
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return static_cast<Child*>(this);
}
...
}
//Array of CObject* pointers is no longer possible.
You can add one level of abstraction:
class CObjectBase
{
public:
// Other methods...
virtual CObjectBase* detach() = 0;
virtual CObjectBase* duplicate() const = 0;
};
template <typename Child>
class CObject : public CObjectBase
{
public:
// ...
Child* duplicate() const
{
return new Child(*static_cast<Child*>(this));
}
Child* detach()
{
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return static_cast<Child*>(this); // Cast needed here (inherent to CRTP)
}
std::vector<CObjectBase*> children; // Array possible now
// ...
};
class MyObject : public CObject<MyObject>
{
// ...
};
In natural language: an interface for all objects (CObjectBase) have a partial implementation for its descendants (CObject<Child>), which just have to inherit this partial implementation, decreasing the amount of replicated code.
I was thinking about CRTP, but I can not think of a way to keep the dynamic polymorphism along with compile time polymorphism
You can mix them by providing default virtual implementations for certain interfaces using CRTP style base classes.
Thus you have the possibility to aggregate CRTP base implementations (maybe configured with additional 'policy'-template parameters) and still being able to override particular behavior in inherited classes.
Microsoft's ATL library uses this a lot.
I also make use of this technique in my STTCL state machine library.
From the snippet alone it is unclear why you need detach() to return a pointer to a delivered type.
To take advantage of detach() returning a delivered type, it needs to be called using a reference to the delivered type anyway. Like this:
CSpecificObject* specific_object = new SpecificObject();
// ...
specific_object->detach()->method_declared_in_specific_object();
But this can be replaced with equivalent that works even if detach is void:
specific_object->detach();
specific_object->method_declared_in_specific_object();
If you have a reference to the base type, you can't take advantage of detach() return type:
CObject* specific_object = new SpecificObject();
//...
// !!! Won't compile:
specific_object->detach()->method_declared_in_specific_object();
For this reason it is unclear what are the advantages of the approach you are trying to implement.
A side not is that the duplicate() method is smelly. It breaks when delivered class does not overwrite it, but uses the default implementation from the parent class. It can be a sign that something is wrong with the high level design.