I have class Student (studentOwner) and class Section.
Here is my class Student:
class Student {
vector<Section*> enrolledSections;
public:
vector<Section*> getEnrolledSections() const { return enrolledSections; }
}
So, when I get vector<Section*> and assign to another vector, I will meet error. I’m using Microsoft Visual Studio.
// first example: no error, if take size of vector
int a = studentOwner->getEnrolledSections().size();
// second example: error, when only take its vector and assign again
// Error: no suitable user-define conversion from "std::vector<error-type" ....
vector<Section*> enrolled = studentOwner->getEnrolledSections();
// third example: error when take this vector and assign to reference of same type
// Error: initial value of reference to non-const value must be lvalue
vector<Section*>& enrolled = studentOwner->getEnrolledSections();
Full error at second example is:
Error: no suitable user-define conversion from "std::vector<error-type", std::alocator<<error-type> *>> "to " std::vector<Section*, std::allocator<Section*>>" exists
In many class of my project, I cannot do line two and line three and received same error. I cannot explain by myself. Please teach me at this point.
Thanks 🙂
Usually if you see
error-typein MSVC errors, it’s a result of a forward declared type that wasn’t included in time for that compilation unit. For example,In the comments you indicate a circular include dependency. As @Daniel Castro noted, you should forward declare in your header files to avoid the circular includes, then include the needed header files in your .cpp files (note the forward declaration
class Student;above if you’re not familiar).As an aside, I would also note some design issues with your example. Returning
std::vector<Section*>doesn’t tell much about who owns what. If I get astd::vectorby value from a function, the convention is that I now own the vector and its contents. If I own something, then I’m responsible for deleting it. Without seeing your actual implementation, most coders would be surprised to learn they shouldn’t delete the contents of the vector. I would suggest either returning the vector byconst&(eg,const vector<Section*>&) which prevents client code from manipulating the vector (so clients don’t own it), or using std::shared_ptr to manage a shared ownership scheme of yourSectionobjects:Now it’s clear who owns what. More than you were asking for, but hopefully it helps.