Polymorphic Pointer

I have this code:
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
28
29
30
31
32
33
34
35
#include <vector>
#include <algorithm>
class Object {
    std::vector<Object*> _children; // No QObject é usado um QList aqui
    Object* _parent = nullptr;
public:
    Object(Object* parent=nullptr) { setParent(parent); }
    Object(const Object&) = delete;

    void setParent(Object* parent) {
        if (_parent) {
            std::vector<Object*>& vec = _parent->_children;
            vec.erase(std::remove(vec.begin(), vec.end(), this), vec.end()); // remove this
        }
        _parent = parent;
        if (_parent) {
            _parent->_children.push_back(this);
        }
    }

    ~Object() {
        for (Object* child : _children)
            delete child; // deleta todos os filhos e, por recursão, seus filhos
    }
};
class DerivedObject : public Object
{
    public:
};
int main()
{
    Object Test;
    DerivedObject Test2;
    Test.setParent(Test2);
}

It is an "QObject" basic copy. I want to set an derived class as the Object* param. How can I do this?
The obvious fix would be to take the address of Test2.

Test.setParent(&Test2);

Of course, that will probably have an undesirable result since your Object class think it owns the pointers that are fed to it and also assumes they were allocated with new, which is a mistaken assumption in this case.

1
2
3
int main()
    Object Test;
    Test.setParent(new DerivedObject);


would be more correct.


Heh. Ignore the strike-through portion of this post. I should've looked more closely.
Last edited on
Construction inserts the object into the parent's tree, but destruction doesn't remove it.
Topic archived. No new replies allowed.