Write a copy constructor for a class containing TList

Hi,
I am trying to use TList in my class and having problem to use it.

My code is as follows:

#include "TObject.h"
#include <iostream>

class A: public TObject {
friend class B;
private:
TList Blist;
public:
A();
A(const A&);
A& operator=(const A&);
virtual ~A();
void test(B*);
ClassDef(A,1);
};

class B: public TObject {
//friend class A;
private:
public:
void btest(A*);
ClassDef(B,1);
};

#if !defined(__CINT__)
ClassImp(A);
#endif

void A::test(B* b) { b->btest(this);}

A::A(){}
A::A(const A& a_){
Blist=a_.Blist;
}

A& A::operator=(A& a_){
 if (&a_== this) return *this;
  Blist=a_.Blist;
  return *this;
} 


#if !defined(__CINT__)
ClassImp(B);
#endif

void B::btest(A* a) { cout<< a << " is printed"<<endl;}

First of all, in class A, TList Blist is supposed to be a list to hold object B only. For STL, we can have list<B*> Blist, I am not sure how we can do the similar thing in ROOT.

The problems are in constructor and operator=.
If I run the code, I get the following outputs:

Thank for your helps.

cheers,

gma

I should have included “TList.h” in my code. But I still have error message.

Hi,

as the error message says: TCollection doesn’t allow you to use the copy constructor because its behavior is not well defined. You have to explicitly implement the copy constructor for your class A, and decide what to do with the TList elements. Common options are to copy the pointers or to copy the elements.

Cheers, Axel.

Hi, Axel,
Thanks. OK. I was not sure how to iterate the TList. Since it is related to the solution, I will give it a try. I change the copy to the following:

A::A(const A& a_){
//Blist=a_.Blist;
TListIter i = TListIter(&a_.Blist);

while (( B* obj = i->Next()))
	Blist.Add(obj);

}

A& A::operator=(A& a_){
 if (&a_== this) return *this;
  //Blist=a_.Blist;
  TListIter i = TListIter(&a_.Blist);

  while (( B* obj = i->Next()))
	Blist.Add(obj);



  return *this;
} 

I run my code again and get the error message:

Obviously, B is defined in the script. This is related to my previous question: How I can define a TList only held type B* object. Anyway, I don’t really understand this output.

cheers,

gma

OK, I fix this. Thanks.

gma