N
Naren
Hello Grp,
I find this a curious thing.
Below is a code
#include <iostream>
using namespace std;
class B
{
public:
B(){cout << "constructed B\n";}
void f(){cout << "B Hello\n";}
~B(){cout << "Destroyed B\n";}
};
class A
{
B &obj;
public:
A(B &b)bj(b){cout << "constructed A\n";}
void f(){ cout << "A Hello\n"; obj.f();}
~A(){cout << "Destroyed A\n";}
};
class C
{
A& obj;
public:
C(A &a)bj(a){cout << "constructed C\n";};
~C(){cout << "Destroyed C\n";}
void f(){ cout << "C Hello\n";obj.f();}
};
int main()
{
B b;
C *c = new C(A(b));
c->f();
delete c;
return 0;
}
The output of the above is
constructed B
constructed A
constructed C
Destroyed A
C Hello
A Hello
B Hello
Destroyed C
Destroyed B
The local object A gets constructed and destroyed But the object C which has
a reference to this object still exists .This should have been a violation I
believe.
Could anyone explain this
Thaanx in advance
Rgds,
Naren.
I find this a curious thing.
Below is a code
#include <iostream>
using namespace std;
class B
{
public:
B(){cout << "constructed B\n";}
void f(){cout << "B Hello\n";}
~B(){cout << "Destroyed B\n";}
};
class A
{
B &obj;
public:
A(B &b)bj(b){cout << "constructed A\n";}
void f(){ cout << "A Hello\n"; obj.f();}
~A(){cout << "Destroyed A\n";}
};
class C
{
A& obj;
public:
C(A &a)bj(a){cout << "constructed C\n";};
~C(){cout << "Destroyed C\n";}
void f(){ cout << "C Hello\n";obj.f();}
};
int main()
{
B b;
C *c = new C(A(b));
c->f();
delete c;
return 0;
}
The output of the above is
constructed B
constructed A
constructed C
Destroyed A
C Hello
A Hello
B Hello
Destroyed C
Destroyed B
The local object A gets constructed and destroyed But the object C which has
a reference to this object still exists .This should have been a violation I
believe.
Could anyone explain this
Thaanx in advance
Rgds,
Naren.