0

So for my code I want to build a quadtree. This means I have to subdivide a dataset. To solve this I want to have external nodes (class A) and internal nodes (class B) and a way to convert an external node into an internal node.

Is there a way to let a class A convert itself into class B in a way that it can be done from inside class A itself, while preserving the pointer that points to it?

I'm sorry, but I don't know how to explain this more clearly.

class A{
public:
    int a;
    int b;

    int c;

    void convert(){

        *convert class A into class B: conserving int a and int b, and discarding int c*

    }
};

class B{
public:
    int a;
    int b;

    void* One; // can be a pointer to an instance of class A or class B
    void* Two; // can be a pointer to an instance of class A or class B
};

Edit: thanks for the feedback, I will rethink my strategy.

Edit2: I found an answer for not storing useless pointers here: https://stackoverflow.com/a/48330314/6859125

zarro
  • 45
  • 4
  • Not cleanly, and the fact that you have such a need suggests that your design is off. – 500 - Internal Server Error Jun 23 '20 at 12:43
  • 1
    The linked question has an answer that [covers this explicitly](https://stackoverflow.com/a/16615725/332733) – Mgetz Jun 23 '20 at 12:43
  • You mean - you want to return a `B` which is equivalent to a given `A`? Yes, you can do that with a regular method or a [user-defined conversion](https://en.cppreference.com/w/cpp/language/cast_operator). – Useless Jun 23 '20 at 12:45
  • 1
    What do you want to achieve - what would be the result/benefit if you converted it (what ever you mean with converted)? – Ingo Mi Jun 23 '20 at 12:45
  • Or you want to replace an `A` object with a `B` object in situ? You can't reasonably do that. – Useless Jun 23 '20 at 12:45
  • Or you could just make `A` refer to an internal node `B` and also store the additional `c` - then no conversion is necessary. – Useless Jun 23 '20 at 12:46
  • Just to let you know, type punning `A` and `B` through a `void*` is prohibited. If you cast a `A*` to a `void*` then to a `B*` and only use the members `a` and `b`, it's still undefined behavior. – Guillaume Racicot Jun 23 '20 at 12:48
  • U could try to use a structured pattern Composite. Look at https://refactoring.guru/design-patterns/composite. It will help u to simplify the solution. – Max Jun 23 '20 at 12:49
  • @ Guillaume Racicot what would be a better way to do this? I don't like the idea of storing 8 pointers when only 4 are needed at one time. – zarro Jun 23 '20 at 13:16

1 Answers1

2

You probably want a single class:

class AB
{
    int a;
    int b;

    int c;
    bool amIABObject;
};

Then, just change the boolean to remember which "type" you are.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42