-3

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; }
};
skypjack
  • 49,335
  • 19
  • 95
  • 187
  • It is the constructor – SingerOfTheFall Oct 25 '16 at 10:40
  • 7
    Which book are you using to learn C++? This is elementary. – Lightness Races in Orbit Oct 25 '16 at 10:42
  • @LightnessRacesinOrbit I'm starting to wonder if there should be a "c++ books to avoid" page... – UKMonkey Oct 25 '16 at 10:51
  • 1
    @UKMonkey: Web browsers cannot yet handle the volume of characters required to display such a page. – Lightness Races in Orbit Oct 25 '16 at 10:53
  • @LightnessRacesinOrbit to be honest I've just been doing things online and looking up bits I don't understand. I know it's pretty lazy and not the most constructive way. Is there a particular resource you can recommend? –  Oct 25 '16 at 10:56
  • "Accelerated C++: Practical Programming by Example" is still a good (if old and therefore slightly out of date) book – doctorlove Oct 25 '16 at 11:02
  • 1
    @MoultoB: **[The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)** – Lightness Races in Orbit Oct 25 '16 at 11:19
  • 3
    @MoultoB: The problem with "looking up bits I don't understand" is that you are probably missing a load of important details that you don't _know_ you don't understand. So you don't look them up, and you go on not knowing. You should structure your learning. People spend a lot of time and effort putting together proper structured courses for people like you to study and learn from, and it's not for fun! – Lightness Races in Orbit Oct 25 '16 at 11:20

1 Answers1

0

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.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416