Question

Suppose I had the following:

class A; // forward declaration

class A {
public:
    A(A* parent) : parent(parent) {}
    A* parent;
    virtual void foo() = 0;
};

class B : public A {
public:
    B() : A(this) {}
    void foo() {}
};

When instantiating two separate instances of class B, the parent pointers are the same in each of the instances. Any idea why?

EDIT: I believe the above now more closely models what I have in my code.

Was it helpful?

Solution

You need to write a copy constructor. Your default constructor isn't invoked when an instance is copied, and the compiler-generated copy constructor will copy the parent pointer from the original instance.

A(A const &other) : parent(this) {}

You may want to write a copy-assignment operator too, to preserve the parent pointer when one instance is assigned to another.

Also, think about what should happen when copying or assigning from an instance whose parent has been changed from its default. In that case, should the copy/assignee get the same parent as the original? If so, your copy constructor and assignment operator will have to check whether parent == this and behave differently depending on the result. It may be simpler to just use nullptr as the default value — either way you need special-case handling for instances without parents, but a null pointer at least makes it obvious that no "real" parent has been assigned yet.

OTHER TIPS

Add a semicolon after the class definition. It's missing in the example you provided. Compilers sometimes give cryptic error messages for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top