I want to understand a simple object factory like this.
template <class Base>
class Factory
{
protected:
Factory (std::string name)
...
}
Factory<Base>::Factory (std::string name)
{
Factory_Map[name] = this;
}
//-------------------------------------
template <class Derived, class Base>
class Factory_Der: public Factory<Base>
{
public:
Factory_Der(std::string name) : Factory<Base>(name) { }
...
};
So the constructor of Factory_Der will call the constructor of Factory. But I don’t know this pointer in constructor of Factory will refer to Factory object or Factory_Der object. It seems that this will refer to Factory object but then the code shouldn’t work! (and it is working).
Thanks
First of all, you created one object, a
Factory_Derobject, right? So when you ask, what object does thethispointer point to, well, what object can it point to? You just have one object — aFactory_Derobject.Since
Factory_Derinherits fromFactory, part of the memory layout of aFactory_Derobject can be viewed as aFactoryobject. But it’s part of the same object. There is no “separate”Factoryobject anywhere that it could be pointing to.You seemed to get caught up in the fact that these are constructors. But constructors work very much like methods, except that they are special in that they are “automatically called” during object construction after the memory allocation. You could imagine that this object construction:
translates underneath into something like this (not real syntax; this is how Objective-C does it however):
This explains why
thisin the constructor points to the object.At the beginning of every constructor, one can specify an optional initializer list, which specifies how to initialize the base classes and the fields. (If you skip the initializer for something, a default is chosen.) So basically, a constructor automatically calls the constructor of the super class at the very beginning.
So again, we can imagine that your constructor:
gets translated underneath into something like this:
So you see, the derived class’s constructor essentially “passes” its
thisto the base class’s constructor. So the object that they see fromthisis the same object.Of course, at the time the base class’s constructor is running, the derived class’s state is not set up. So whether the object can be truly considered a derived class object is a matter of debate. But if your question is whether the object that
Factory‘s constructor sees fromthisis the object that will eventually become aFactory_Derobject, then the answer is unequivocally yes.