Hello, I am having a problem when trying to use a TCanvas as a private variable in a class, and using it in a method of that class! Here are the files in which there is a problem:
File Functor.h
class Functor
{
public:
// Constructor/Destructor
Functor(string s="Functor");
~Functor() = default;
// Methods
virtual double operator()(double x);
void Draw(double xi, double xf, int num, string xtitle, string ytitle);
protected:
TCanvas *c; // Here is the variable of the TCanvas
string name;
};
File Functor.cpp
Functor::Functor(string s) :name(s)
{
c = new TCanvas("c","c",900,800);
}
double Functor::operator()(double x)
{
return 0;
}
void Functor::Draw(double xi, double xf, int num, string xtitle, string ytitle)
{
double x[num], y[num], h = (xf-xi)/((double)num);
// Values for TGraph
for(int i=0; i<num ; i++)
{
x[i] = xi + i*h;
y[i] = this->operator()(x[i]);
}
TApplication app("app",nullptr,nullptr);
TGraph* graph = new TGraph(num, x, y);
// Aesthetics
graph -> SetTitle(name.c_str());
graph -> GetXaxis() -> SetTitle(xtitle.c_str());
graph -> GetYaxis() -> SetTitle(ytitle.c_str());
graph -> GetXaxis() -> CenterTitle(true);
graph -> GetYaxis() -> CenterTitle(true);
graph -> SetLineColor(kRed);
graph -> SetMarkerColor(kRed);
graph->Draw("APL");
// Legend
auto legend = new TLegend(0.1,0.7,0.48,0.9);
legend->SetHeader("Legends","C"); // option "C" allows to center the header
legend->AddEntry("graph","Funtion","l");
legend->Draw();
//Canvas Interface
c->Modified();
c->Update();
TRootCanvas *rc = (TRootCanvas *)c->GetCanvasImp();
rc->Connect("CloseWindow()","TApplication",gApplication,"Terminate()"); // The error occurs here
app.Run();
}
(The operator overloading is supposed to be overridden so don`t worry)
The error is this:
*** Break *** segmentation violation
===========================================================
There was a crash.
...
===========================================================
#6 0x00007efeeb1d33c8 in TQObject::Connect(char const*, char const*, void*, char const*) () from /usr/local/root_v6_24/lib/libCore.so.6.24
#7 0x000055a2a29203ba in Functor::Draw (this=0x7ffffb61bc20, xi=-5, xf=5, num=1000, xtitle="x", ytitle="y") at src/Functor.cpp:50
===========================================================
Thanks for your help!
_ROOT Version: 6.24/06
_Platform: Ubuntu 20.04
_Compiler: GCC