Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing instance of own class to another

Assuming I have these classes (question marks mark the question what I need to pass here):

class A
{
  ...
  public:
  void pass()
  {
     B ins;
     ins.doSth(?????);
  }
};

class B
{
  ...
  public:
  void doSth(const A &sth)
  {
    ...
  }
}

int main()
{
  A te;
  te.pass();
}

Can you pass an instance of your own class or is this just an example of a failed class structure on my side?

like image 535
RandomUser42 Avatar asked Oct 21 '25 05:10

RandomUser42


1 Answers

The current object in a member function is *this. You can pass that to another function.

You will have to consider how the classes depend on each other, and that one class cannot use the other class until the declaration is complete.

This would work though:

class A
{
  //...
  public:
  void pass();
};

class B
{
  //...
  public:
  void doSth(const A &sth)
  {
    //...
  }
};


// Here both classes are completely declared

void A::pass()
{
   B ins;
   ins.doSth(*this);
}


int main()
{
  A te;
  te.pass();
}
like image 161
Bo Persson Avatar answered Oct 23 '25 20:10

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!