Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'cannot initialize return object of type Base* with an lvalue of type value_type (aka Derived*)?

I have a base class and a derived class. When i try to convert the derived class pointer to base class pointer, i get a compilation error.

class Base  {
  ..
}

class Derived: public Base {

}

class X {
    public:
        Base* getWriter(int shard) {
            return writers[0][shard];
        }
    private:
        mutable vector<vector<Derived*>> writers_;
}

And the error I get is

error: cannot initialize return object of type 'Base *'
with an lvalue of type 'value_type' (aka 'Derived *') on line "return writers[0][shard];"

like image 668
user1159517 Avatar asked Dec 07 '16 20:12

user1159517


2 Answers

The header that defines X is not including the header that defines class Derived, so the compiler does not know the relationship between Base and Derived.

like image 96
1201ProgramAlarm Avatar answered Nov 01 '22 13:11

1201ProgramAlarm


This error happens when the relation between the types Base and Derived are not known to the compiler.

This is the case if you only have forward declarations of Base and/or Derived, but no class definitions. Including the header that defines Derived before you attempt this conversion should resolve your issue.

like image 27
rubenvb Avatar answered Nov 01 '22 14:11

rubenvb