FindObject

Hi,
Is it possible to find object of my own class?
I need to do something like

#include "myclass.h" //header of my class

//[...]
myclass* a=new myclass("name");

//here I forget about pointer *a

//get back object
myclass* b = (myclass*)gROOT->FindObject("name");

I do not insist on “gROOT->FindObject”. It can be anything what gives me access to created object.

Sugestions welcome

Hi,

I’d just take care of that in MyClass. Add:

class MyClass { ... public: MyClass(const char* name) {fgObjMap[name]=this;} ~MyClass() {fgObjMap[name]=0; } // or remove from map static FindObject(const char* name) {return fgObjMap[name];} private: static std::map<std::string,MyClass*> fgObjMap; };
(don’t forget to put fgObjMap into your source file, too - it’s a static var). Now you can call MyClass::FindObject(“name”).

Axel.

Hi,
Thanks for answer.
However I ended with

#include "TNamed.h"

class myclass : public TNamed
{
 public:
  myclass(const char* name);

  //  ClassDef(myclass,1);
};

//ClassImp(myclass);
myclass::myclass(const char* name)
{
  SetName(name);
}

void testclass()
{
  a1 = new myclass("nam");
  
  gDirectory->GetList()->Add(a1);
  
  myclass* b1 = (myclass*)gROOT->FindObject("nam");
  
  cout<<b1<<endl;
  cout<<b1->GetName()<<endl;
  cout<<b1->ClassName()<<endl;
}

It works well. The only little problem which I can see is that b1->ClassName() return “TNamed” instead of “myclass”. But I can live with it :slight_smile:

greetings,

[quote]It works well. The only little problem which I can see is that b1->ClassName() return “TNamed” instead of “myclass”. But I can live with it Smile
[/quote]This is the expected behavior if you class ‘myclass’ is interperted (we can not overload the virtual table of a compile object (TNamed) with the one from an interpreted class) or if you did not put ClassDef in a compiled class (because IsA is not properly overloaded).

Cheers,
Philippe.

yes, after compilation ClassName() works too.

thanks,