MoultoB MoultoB - 2 months ago 21
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;
MyTemplate (T arg) {element=arg;} //what does this line do?
T divideBy2 () {return element/2;}


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.