MoultoB MoultoB - 1 year ago 97
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;}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download