MoultoB MoultoB - 1 month ago 10
C++ Question

Templates in C++ public function

I'm going through some C++ learning and I am tackling this question on Hackerrank.

I think I understand how templates work and the example given, except for one line:

template <class T>
class MyTemplate {
T element;
public:
MyTemplate (T arg) {element=arg;} //what does this line do?
T divideBy2 () {return element/2;}
};

Answer

The line

MyTemplate(T arg){ element=arg; }

is the definition of MyTemplate's constructor, taking a T argument (where T is known at the moment of instantiation of the class - e.g. MyTemplate<int> -> T is int) and assigning the this->element field to arg in its body.

Comments