0

May someone tell me please why we do write size_t after Graph in the following line?

Graph<std::size_t> g;

Graph is a class name and g is an object. What does size_t do there? Why should we write that?

I am so sorry if the question is too basic. But I could not find explanation on this and so far when I've wanted to create an object of class I have written:

class_name object;

like:

Graph g;
Evg
  • 25,259
  • 5
  • 41
  • 83

1 Answers1

2

Because Graph is a class template not an ordinary class.

Class templates define a class where the types of some of the variables, return types of methods, and/or parameters to the methods are specified as parameters.

Hence by using Graph<std::size_t > g; you are using one of the class template instantiation which has size_t as a type parameter.

You can use Graph<int > g too and so on.

An addition:

When the compiler encounters template method definitions, it performs syntax checking ony, but doesn’t actually compile the templates.

Let us write the template

template<typename T>
class MyClass
{
    T memberVar{};
};

Only when the compiler encounters an instantiation of the template, such as MyClass<int> myObj, it writes code for an int version of the MYClass template by replacing each T in the class template definition with int and so on.

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • 1
    nitpick: Your wording can suggest class templates would be special kinds of classes. "Class templates define a class where .." strictly speaking a class template does not define a class, they are just templates, not classes. You only get a class definition once you instantiate the template – 463035818_is_not_an_ai Jan 06 '20 at 12:28