next up previous contents index
Next: 2.4 Memory Management Up: 2.3 Class and object Previous: 2.3.1.1 Query interface example   Contents   Index

2.3.2 Object creation

Objects in C++ may be statically, dynamically, or automatically created. This holds true for ns-3 also, but some objects in the system- those using the replaceable component system- have some additional frameworks available. Specifically, reference counted objects are dynamically allocated using operator new, a templated MakeNewObject method, or an ns-3 component manager.

The ComponentManager class is inspired by COM and is a class used to create any Interface class by ClassId, where ClassId is a symbolic name associated to a particular class. Each class using the component manager declares a unique ns3::ClassId static variable that is bound to a constructor. The following code shows how the component manager can be used to create new objects of type A:

  Ptr<A> a = 0;
  a = ComponentManager::Create<A> (A::cid, A::iid);
The above code (from the unit tests for component-manager.cc) creates a class A (which is subclassed from Interface) and returning a pointer to A (as specified by A's interface ID)..

The above code sample can be changed in a few ways. First, if A statically aggregates interface B, a pointer to interface B can be returned even if the underlying object is of type A:

  Ptr<B> b = 0;
  b = ComponentManager::Create<A> (A::cid, B::iid);

Finally, the system accommodates non-default constructors. Assume that another constructor for A exists that takes a boolean argument, such as class A::A (bool bo). If the constructor for this class has registered a new class Id (such as cidOneBool), the following can be called:

  Ptr<B> b = 0;
  b = ComponentManager::Create<A,bool> (A::cidOneBool, B::iid, true);
where the last parameter is the passed-in boolean value to A's constructor, and again assigning returning the interface pointer B to the created object of type A. The classIds can be overridden at run time also by the default value system described below.

If a reference counted object is being new'ed and assigned to a reference counting smart pointer (class Ptr), then a templated helper function is available and recommended to be used:

  ns3::Ptr<B> b = ns3::Create<B> ();
This is simply a wrapper around operator new that correctly handles the reference counting system.


next up previous contents index
Next: 2.4 Memory Management Up: 2.3 Class and object Previous: 2.3.1.1 Query interface example   Contents   Index
Tom Henderson 2007-06-17