So this is not about a problem I faced but about a question in an exam I am not able to answer properly.
I have the following class:
template<class T>
class Server {
protected:
std::vector<T> requests;
public:
Server() = default;
Server(const Server& other) = default;
~Server() = default;
Server(const std::vector<T>& vec);
Server& operator=(const Server<T>& other) = default;
Server& operator+=(const T& request);
Server& operator-=(const T& request);
void operator()();
std::size_t numRequests() const;
friend Server<T> operator+(const Server<T>& a, const Server<T>& b );
friend std::ostream& operator<<(std::ostream&, const Server<T>&);
};
template<class T>
Server<T> operator+(const Server<T>& a, const Server<T>& b );
template<class T>
std::ostream& operator<<(std::ostream&, const Server<T>&);
Now, I create a class named LimitedNamedServer
, the difference between the classes are that LimitedNamedServer
objects has a maximum capacity of requests and a name.
This is what it looks like:
template<class T>
LimitedNamedServer : public Server<T> {
std::string name;
std::size_t maxLimit;
public:
LimitedNamedServer(const char* name, std::size_t limit) : Server<T>(), name(name), maxLimit(limit) {}
LimitedNamedServer(const LimitedNamedServer& other) = default;
~LimitedNamedServer() = default;
LimitedNamedServer(const char* name, std::size_t limit, const std::vector<T>& vec) : Server<T>(vec), name(name), maxLimit(limit) {
if(requests.size() > maxLimit) {
throw OverLimit();
}
}
LimitedNamedServer& operator=(const LimitedNamedServer<T>& other) = default;
LimitedNamedServer& operator+=(const T& request) {
if(numRequests()>=maxLimit) {
throw OverLimit();
}
else {
requests.push_back(request);
}
return *this;
}
};
Now, the problem is as follows:
Let
s1
,s2
ands3
be three objects from the classLimitedNamedServer
. Why will the following code not compile, how can this problem be fixed:
s1=s2+s3
I have no idea why this is not supposed to compile. From what I know the +
operator I defined for the class Server
can also be used on objects from the class LimitedNamedServer
. My best guess is that it happens due to that inside the implementation of +
, I create a new Server but not a LimitedNamedServer
, and that the error occurs because s1
expects to recieve a LimitedNamedServer
object while this is not the object returned.
This is just a guess however, can someone please explain the reason for that?