One small question about the c++ templates mechanism. Suppose we have a class called Point. Now suppose “Data” is a template class/container, containing only T (template) data member.
That is, “Data” looks more or less like this:
Template <class T>
class Data {
T dMember;
……..
};
Now suppose someone using this class in the main.cpp file and preforms the following declaration:
Data<Data<Point>> d;
I’m trying to understand completely how the object created looks like. I was trying to use the complier to get into the class call but to no avail. I know that Data need to initialize Data so it calls itself one time, but what it really does there? Is there a constructor being activated?
Thank you,
Guy
Data does not really call itsef one time. This is because the inner Data and the outer Data are two different classes. In general, if the compiler sees
Data<Data<Point>>, it first recognizes the inner part, i.e.Data<Point>. It then instantiates the template, meaning it creates a class having the properties described by the template. It’s important to realize that Data is not a class, but a template that can be used to create a whole bunch of classes. Each of those classes is different from the others, they are different types and have no real relation to each other. SoData<Point>is just one instanitation of the template, and its a class that has the same properties like, say,I’ll just call it Foo. The Compiler then sees
Data<Data<Point>>, which could as well beData<Foo>. It instantiates the template again, this time using Foo (i.e. the class it got from the first instantiation) as the parameter. It gets another class, in principle completely independent of the first one, except it has a member of the first instantiation’s type:Thats all. Data does not call itself, Data does not even exist as a type. The constructors being called in initalization are Bar’s constructors, which in turn will call Foo’s constructors. The constructor thingy you defined in Data is no real constructor, because anything that lies inside a class template is a template itself. So its a constructor template, and if you call Foo’s and/or Bar’s constructor the compiler uses that template to instantiate the actual constructors.
Data is just a blueprint for the compiler to build real classes (and member functions, if needed), it never gets out there to play or to call or initialize anything.