passing arguments to methods

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  class Menu {

  public:
  void welcome() {
       std::cout << "HELLO " << name << std::endl; //name of hero printed
     }
  }
  class Hero {
  private:
   std::string name;
   Menu menu;

  public:
  void getName() {
   return name; 
  }
  void welcomeFromHero() {
       menu.welcome() // i know i can pass here name to function but there are multiple values, can i pass the whole hero object?
     }
  }
Yes. Using the this pointer. this is the pointer to the object it’self.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
   class Menu {

  public:
  void welcome() {
       std::cout << "HELLO " << name << std::endl; //name of hero printed
     }
  }
  class Hero {
  private:
   std::string name;
   Menu menu;

  public:
  void getName() {
   return name; 
  }
  void welcomeFromHero() {
       menu.welcome(*this) // i know i can pass here name to function but there are multiple values, can i pass the whole hero object?
     }
  }
pass the least thing you need.
pass the string.

void welcome(string &s);
...
menu.welcome(name);
menu does not need the whole class in this scenario. If it needs all of it for something else, disregard.
Why would the Hero call menu.welcome to welcome himself ?
Narcissism 101...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <string>

 class Menu {

  public:
  void welcome(std::string* name) {
       std::cout << "HELLO " << *name << std::endl; //name of hero printed
     }
  };
  
  class Hero {
  private:
   std::string name;
   Menu menu;

  public:
  Hero(std::string n) {
   name = n;   
  }
  
  std::string getName() {
   return name; 
  }
  void welcomeFromHero() {
       menu.welcome(&name); 
     }
  };

int main()
{
    
 Hero myHero("JOHN");
 myHero.welcomeFromHero();
 
 return 0;
}
Last edited on
Topic archived. No new replies allowed.