How to write copy constructor for a template class. So that if the template parameter is another user defined class it's copy constructor is also get called.
Following is my class
template <typename _TyV>
class Vertex {
public:
Vertex(_TyV in) : m_Label(in){ }
~Vertex() { }
bool operator < ( const Vertex & right) const {
return m_Label < right.m_Label;
}
bool operator == ( const Vertex & right ) const {
return m_Label == right.m_Label;
}
friend std::ostream& operator << (std::ostream& os, const Vertex& vertex) {
return os << vertex.m_Label;
}
_TyV getLabel() { return m_Label;}
private:
_TyV m_Label;
public:
VertexColor m_Color;
protected:
};
The copy constructor lets you create a new object from an existing one by initialization. A copy constructor of a class A is a non-template constructor in which the first parameter is of type A& , const A& , volatile A& , or const volatile A& , and the rest of its parameters (if there are any) have default values.
1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.
A copy constructor is a member function that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.
Either a) not at all, just rely on the compiler-provided default; or b) by just invoking the copy constructor of the member:
template <typename T> struct Foo
{
T var;
Foo(const Foo & rhs) : var(rhs.var) { }
};
The point is of course that the compiler-provided default copy constructor does precisely the same thing: it invokes the copy constructor of each member one by one. So for a class that's composed of clever member objects, the default copy constructor should be the best possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With