Reputation: 1606
I would like to define a copy-constructor which just assigns the object to another one:
Header:
#ifndef TESTCLASS_HPP
#define TESTCLASS_HPP
#include <boost/math/distributions/geometric.hpp>
class Testclass {
public:
Testclass();
virtual ~Testclass();
private:
Testclass(const Testclass& orig);
int alpha;
boost::math::geometric_distribution <> geometricboost;
};
#endif /* TESTCLASS_HPP */
Implementation:
#include "Testclass.hpp"
Testclass::Testclass() : geometricboost(0) {
}
Testclass::Testclass(const Testclass& obj_ref) {
*this = obj_ref;
}
Testclass::~Testclass() {
}
The class itself doesn't contain any pointers, but eventually an object. IS this actually possible to do?
If not, what would be the easiest way just to just assign?
This gives the error:
Testclass.cpp: In copy constructor ‘Testclass::Testclass(const Testclass&)’: Testclass.cpp:13:46: error: no matching function for call to ‘boost::math::geometric_distribution::geometric_distribution()’ Testclass::Testclass(const Testclass& obj_ref) {
Upvotes: 1
Views: 240
Reputation: 18964
When your copy constructor runs it first tries to default initialise geometricboost
(because you don't specify any initialisation for it) and only then calls the assignment operator. This doesn't work because the geometric distribution does not have a default constructor.
You would be better off implementing assignment from copy (using the copy then swap idiom) rather than vice versa, as suggested at Calling assignment operator in copy constructor.
Alternatively you could just delete your copy constructor completely - the compiler generated one will work just fine.
Upvotes: 1
Reputation: 4247
If you implement your own copy constructor then you should initialize all members in the constructor's initializer list. Otherwise the default constructor is called for every member of a not built-in type before the assignment operator is executed.
boost::math::geometric_distribution
seems to have no default constructor. That's why you get the compiler error. You would fix it by using the copy constructor of geometric_distribution
:
Testclass::Testclass(const Testclass& obj_ref)
: alpha(obj_ref.alpha),
geometricboost(obj_ref.geometricboost)
{
}
According to the rule of three you should consider to also implement the copy-assignment operator (, move constructor, move assignment operator).
Upvotes: 1