Polymorphism with TClass::New() after dynamic loading of derived class library during runtime


Please read tips for efficient and successful posting and posting code
So I want to tackle the following situation.
I have a class ‘Base’ derived from TObject with some virtual method ‘fun1’. Now a user can derive a class (let us say ‘Derived’) from ‘Base’, where the user overrides the method fun1. I need some way of executing following pseudo-code from the main() at runtime.

 Base *b = new Derived() ;
 b -> fun1() ;

Here the name of the class ‘Derived’ is not known to me at compile time. I tried the following code in main().

	TApplication *theApp = new TApplication("theApp",&argc,argv) ;
	gROOT -> ProcessLine(".L Derived.C+") ;
	TClass *cl = TClass::GetClass("Derived") ;
	TObject *b = (TObject*)cl -> DynamicCast(cl,cl -> New(),kTRUE) ;
	b -> Warning("Warning","") ;
	theApp -> Run() ;

Here I am aasuming that the user will write the class definition in the file named by class name. After successful compilation, I expect the code to call ‘Derived::Warning’ method during runtime. But this code doesn’t compile. It gives an error

[chinmay@chinmay test_codes]$ gcc `root-config --cflags --glibs` TestDynamicCast.C -o TestDynamicCast
/usr/bin/ld: /tmp/cce1fytK.o: undefined reference to symbol '_ZTVN10__cxxabiv117__class_type_infoE@@CXXABI_1.3'
/usr/lib64/libstdc++.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

during compile time.
The .C files used above are attached here.
TestDynamicCast.C (899 Bytes)
Derived.C (1.9 KB)

ROOT Version: 6.08/04
Platform: Fedora23
_Compiler:__gcc5.1.1


Okay.
It was stupid mistake on my part. compiling with g++ solved the compilation issue.
But the code is not doing what I need it to do.
When I do

[chinmay@chinmay test_codes]$ g++ TestDynamicCast.C `root-config --cflags --glibs` -o TestDynamicCast
[chinmay@chinmay test_codes]$ ./TestDynamicCast 

I get the output,

Warning in <Derived::Warning>:

which is confusing, as the output says that it has called the ‘Warning’ method of the ‘Derived’ class, yet it has not printed the message in “Derived::Warning” method. What’s happening ??

I think you meant:

TObject *b = (TObject*)cl -> DynamicCast(TObject::Class(),cl -> New(),kTRUE) ;

(The original call to DynamicCast is a no-op)

Instead of

virtual void Warning(const char *method, const char *msgfmt, ...)

I think you meant:

virtual void     Warning(const char *method, const char *msgfmt, ...) const

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.