Reputation: 20264
Is it possible to add a copy constructor (or in other words to overload it) for class which I did not write?
For example, I am using some library that have a Point class. I want to add a copy constructor to it. I can not and do not want to edit it.
Imaginary syntax:
cv::Point cv::Point::Point(const AnotherPoint& p){
return cv::Point(p.x,p.y);
}
P.S I did not write AnotherPoint
also.
EDIT -Problem Background-:
All my problem that I want to copy std::vector<cv::Point>
to another std::vector<AnotherPoint>
using the standard function std::copy
. So I was seraching for a way to overload the copy constructor to make it.
Upvotes: 1
Views: 125
Reputation: 12757
That is not possible.
You can do the opposite, though, i.e. define an implicit conversion operator from your type (AnotherPoint
) to the the other one (cv::Point
).
This way, you will be able to use an object of type AnotherPoint
everywhere a cv::Point
is expected.
If you don't have control over AnotherPoint
too, I guess the only way to go is to define a standalone function that create a cv::Point
from a AnotherPoint
.
After OP EDIT:
Eventually, to transform a vector<cv::Point>
into a vector<AnotherPoint>
you can use the standalone function mentioned above as the unary_op
of std::transform
, as @TartanLlama suggested.
Upvotes: 1
Reputation: 65620
You can't add constructors to a type after its definition.
A simple way to copy a std::vector<cv::Point>
to a std::vector<AnotherPoint>
would be to use std::transform
:
std::vector<cv::Point> cvPoints;
//cvPoints filled
std::vector<AnotherPoint> otherPoints;
otherPoints.reserve(cvPoints.size()); //avoid unnecessary allocations
std::transform(std::begin(cvPoints), std::end(cvPoints),
std::back_inserter(otherPoints),
[](const cv::Point& p){ return AnotherPoint{p.x, p.y}; });
Upvotes: 5