Q:

Write a program that describes the safe way to access one object to another in C++?

0

Write a program that describes the safe way to access one object to another in C++?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

#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;
}

Output:

class B constructor
class A function
class A constructor
-------------------------------------------------------------------------------------------------------

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;
}

Output:

class B constructor
class A constructor
class A function

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now