As others said in the comments, there is probably no default constructor and copy constructor for Myclass2 and Myclass. We don't see the actual code, but I think this example would help:
class Myclass2 {
public:
Myclass2() = default;
Myclass2(int const& x) : x(x) {}
Myclass2(Myclass2 const& myclass2) : Myclass2(myclass2.x) {}
int x;
};
class Myclass{
public:
Myclass() : instance() {}
Myclass(Myclass2 const& instance) : instance(instance) {}
Myclass(Myclass const& myclass) : Myclass(myclass.instance) {}
Myclass2 instance;
};
In some cases the explicitly generated default constructors are disabled (like when we declare our own constructors, more info http://en.cppreference.com/w/cpp/language/default_constructor), so we have to write them again. We need to create constructor Myclass2() : ...
so we can default initialize like for exampleMyclass2 myclass;
If all the members of class are default constructible, we can let it be automatically generated by declaring Myclass2() = default;
(C++11)
The line in your code this->instance = instance;
seem like something to be in member initialization list - it initializes members even "before" the constructor, so you can have const members that you would be otherwise unable to initialize. The syntax is:
Myclass(Myclass2 instance) : instance(instance) {
// the rest of constructor, where you can do what you want with already initialized instance
}
Don't worry about the instance(instance)
syntax, it recognizes what is what (although some people think the same names are a little confusing).
Also as others pointed out, if you are not taking Myclass2 instance as reference, you are creating temporary copy and there is no copy constructor for Myclass2.
Copy constructor (for Myclass
that would be the one with Myclass const& instance
argument only) is what we use when we want to initialize class like Myclass myclass(otherMyclass);
.
It's pretty common to delegate constructors by Myclass(something) : Myclass() {}
for example.
(Information about when you need to create which ones are available on http://en.cppreference.com/w/)
Sometimes we also may need to create copy assignment operator (http://en.cppreference.com/w/cpp/language/copy_assignment), so we can do things like:
Myclass m1;
Myclass m2;
m2 = m1;
but the explicit one is probably enough, if it's not you definitely wanna read What is The Rule of Three? and What is the Rule of Four (and a half)?.