Passing an object to itself.

Is there any pitfalls or negative consequences to doing something like this.

Any ways to safeguard against somebody accidentally calling an object recursively to itself?

Like if I changed line 10 to

cout << "cubea surface area: " << cubea.surfacearea(cubea) << endl; it would be a recursive loop.

It'd compile but then crash. An example like this is easy to see where it went wrong, but on something more abstracted it might be difficult to track down.

I was mostly wondering if there was a way to call objects to itself but to do it with some kind of recursive protection.

Here is the example to show what i mean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// passing an object to itself
#include <iostream>
using namespace std;

class Ccube {
    int x, y, z;
  public:
    void set_values (int,int,int);
    int surfacearea (Ccube& cubea) {
        cout << "cubea volume: " << cubea.volume() << endl;
        return 6*(x*y);}
    int volume () {return (x*y*z);}
};

void Ccube::set_values (int a, int b, int c) {
  x = a;
  y = b;
  z = c;
}


int main () {
  Ccube cubea;
  cubea.set_values (3,4,5);
  cout << "cubea surface area: " << cubea.surfacearea(cubea) << endl;
  return 0;
}
Last edited on
This example seems rather contrived; why not just call cubea.surfacearea() and have that method take no parameters, instead operating on this? As it is, it displayed the volume of the passed cube then returns the surface area of the calling cube, which makes very little sense to me.

In any case, I'm not sure what kind of solution you are looking for; recursion is a feature of the language, having at least as many valid uses as there are mistaken ones (such as the infinite example you gave), so my honest opinion would just be to not do it. If your code is convoluted to the point you can't follow an issue like that, perhaps it is too complex and should be simplified or broken down into pieces that you can confirm work?
This example was contrived as a simple way to convey the question.

I am new at this so I just try things out to see what works, and safeguarding stuff helps me figure out where I broke something or what I did wrong.

I just wondered if there was a way to safeguard / check against an object calling itself recursively before it gets passed.

Recursion is a nice feature, just sometimes it's nice to be able to turn off a feature also.

I'll try to keep my code simple or broken up enough to keep stuff like that from happening.

Thanks for the advice.
Topic archived. No new replies allowed.