Get instance of class from another class

Hello. I have a question about getting the constructed object that is created in main() function from another class.

1
2
3
4
5
6
7
8
9
  class A {
      int a;
    public:
      A(int a) {this->a = a;}
  };

  int main() {
      A x = new A(5);
  }


Now, I want to take the instance x from another class, let's say, class B and I should use the methods of class A in class B.

How can I get the information of the instance from main() function?
line 4 is a bad habit.
just say
A(int a2b) {a = a2b;} //this is clutter/bloat just give the input parameter another name so it isnt needed.

you can inherit the classes so that B can access the methods of A, such that
B y;
y.A(42); //the B class object Y calls the A method because you inherited it, which then sets B's a variable, because it inherited that too.

Hi again. Thanks for correction.

Can I write a function in class B that does this call?
I believe you can using 'friend'
does anything here help: https://en.cppreference.com/w/cpp/language/friend

I am a little rusty on doing this -- it seems extra weird because A() sets a, so I don't really know off the top of my head what is needed to do that. If A() just did a print to the screen, though, borrowing it would be straightforward -- maybe try that as a starting point. There are any number of OOP features I do not use a lot; about all I do with friend is apply an overload so cout will work on an object, which is boilerplate code that you can get anywhere without having to dig into it /blush


Last edited on
Our instructer didn't allow us to use friend keyword in the project. I researched on the Internet and I found a getInstance() function which is used in Singleton Design Pattern. Hence, I will do some more research and try it in my code.

Thank you for your contributions. After my research, I will write here.
If each B instance always relates to the same A instance, then derive B from A, as jonnin advised.

If each B instance uses different A instances, then pass the A instance as a parameter:
1
2
3
4
class B {
public:
   void f(A &x) { cout << x.a << '\n'; }
};
Thank you dhayden. I tried the function and it works. There is no need to use Singleton design pattern in this part.

I will mark this question as solved.

See you in another C++ question!
Topic archived. No new replies allowed.