Search code examples
c++parametersconstructorcompositelvalue

c++ base constructor lvalue to parameter


I played a bit around with composite-patterns and inheritance in c++. It shouldn't be something special so i coded that a component has a parent as composite, the composite should derrived from component and use the constructor from it's base class (Component). But then i got following error:

"Cannot convert lvalue of type 'Composite*' to parameter type 'Composite*'"

Researched a bit and found out what lvalues/rvalues etc. are but didn't find anything about a "parameter" type. Is a parameter type a rvalue? Is it possible to convert a lvalue to a parameter type?

Here is my code as a smaller version:

class Component {
private:
  Composite* parent;
public:
  Component(Composite* parent) {
    this->parent = parent;
  }
};
class Composite : public Component {
public:
  Composite(Composite* parent) : Component(parent) /* <-- Error */ { }
};

Solution

  • Comments in corrected code.

    class Composite;  // <- _declare_ the idea of a Composite class here
    
    class Component {
    private:
        Composite* parent;
    public:
        Component(Composite* parent) {
            this->parent = parent;
        }
    };
    
    class Composite               // <- _define_ it here
            : public Component {
    public:
        Composite(Composite* parent) : Component(parent) /* <-- no error */ { }
    };