How to save TLegend to a graph saved in .root file?

Hello all,

I am trying to add a graph in .root file. The legend is appearing on the canvas but its not getting saved in .root file when I am trying to save a graph in .root file. In .root file only graph with a graph title and graph axis name is getting saved.

My code is as below:
ABC.c

#include <iostream>
#include <TGraph.h>
#include <TCanvas.h>
#include <TLegend.h>

using namespace std;

int ABC()
{
gROOT -> SetStyle("Plain");

TCanvas *c = new TCanvas();

string dirName = "C:/Test/";
string outFileName = dirName + "ABC.root";

TFile *fout = new TFile(outFileName.c_str(), "RECREATE"); 
fout -> cd();
 
TMultiGraph *mg = new TMultiGraph();
mg -> SetTitle("Z vs D; Ze;Dr ");

TGraph *graph1 = new TGraph("C:/Test/Test.txt", "%lg %lg", " ");
graph1 -> SetLineColor(1);

TGraph *graph2 = new TGraph("C:/Test/Test.txt", "%lg %*lg %lg", " ");
graph2->SetLineColor(5);

TGraph *graph3 = new TGraph("C:/Test/Test.txt", "%lg %*lg %*lg %lg", " ");
graph3->SetLineColor(3);

mg -> Add(graph1);
mg -> Add(graph2);
mg -> Add(graph3);

TLegend *leg = new TLegend(0.1, 0.7, 0.3, 0.9);
leg -> SetNColumns(2);
leg -> SetHeader("Test");
leg -> SetFillColor(0);
leg -> AddEntry(graph1, "Graph1", "l");
leg -> AddEntry(graph2, "Graph2", "l");
leg -> AddEntry(graph3, "Graph3", "l");
leg -> DrawClone("Same");

fout ->Close();

return c;
}

How would it be possible? Please guide me.

Thank you.

Instead of: fout ->Close(); put: mg->Write("My_mg"); leg->Write("My_leg"); delete fout; or: mg->SetName("My_mg"); mg->Write(); leg->SetName("My_leg"); leg->Write(); delete fout;