Let see an example, where class A object is calling from class B. In the first example, I am calling class a function in the constructor of class B.
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "class A constructor" <<endl;
}
void f()
{
cout << "class A function" <<endl;
}
};
class B
{
public:
B(class A *a)
{
cout << "class B constructor" <<endl;
a->f();
}
};
extern class A a;
class B b(&a);
class A a;
int main()
{
return 0;
}
You can see when we are running the code class A function is calling before the calling of the constructor of class A. It is unsafe and might show undefined behavior.
So below we are modifying the code for safety. In the below code function only call after the construction of class A.
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "class A constructor" <<endl;
}
void f()
{
cout << "class A function" <<endl;
}
};
class B
{
public:
B(class A *a)
: pFun(a)
{
cout << "class B constructor" <<endl;
}
void init()
{
pFun->f();
}
class A *pFun;
};
extern class A a;
class B b(&a);
class A a;
int main()
{
//Now Safe to access one object from another
b.init();
return 0;
}
Answer:
Let see an example, where class A object is calling from class B. In the first example, I am calling class a function in the constructor of class B.
Output:
You can see when we are running the code class A function is calling before the calling of the constructor of class A. It is unsafe and might show undefined behavior.
So below we are modifying the code for safety. In the below code function only call after the construction of class A.
Output: