Accessing to data members of a class issues!

In cin statements, I am not putting in like objectpass.name, objectpass.n, objectpass.ch
So there is noting displaying.
If I put in properly in cin like objectpass.name, objectpass.n, objectpass.ch then it display correctly.

Now if I don't put in like objectpass.name, objectpass.n, objectpass.ch in cin rather just name, n, ch and same don't put in objectpass.name, objectpass.n, objectpass.ch in cout too. Then, display is correct.

My question is if I don't put in like objectpass.name, objectpass.n, objectpass.ch in cin, rather only put in name, n, ch, will the data store some other place?
In short, cin >>objectpass.name and cin>>name are two different variables?
How?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
using namespace std;
class ObPass {
private:
   char name[40];  
   int n;
   char ch;
public:
   void disp(ObPass objectpass){
      cout << "Enter Name: " << endl;  
      cin >> name;
      cout << "Enter Integer: " << endl;  
      cin >> n; 
      cout<<"Enter Character: "<<endl;
      cin >> ch;  
      cout << objectpass.name << objectpass.n  << objectpass.ch << endl;
   }
};
int main() {
   ObPass object;
   object.disp(object); 
   return 0;
}
Your disp function is a member function (AKA "method" in OOP-speak) of your ObPass class.

When you refer to name within a member function, it is referring to this->name, which is the class's member variable.

When you do objectpass.name, you are referring to the ObPass object you passed by value, which you never assigned values to before printing them.

In other words, it is quite redundant to pass in objectpass into your member function, because your member function already has the information it needs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
class ObPass {
private:
   char name[40];  
   int n;
   char ch;
public:
   void disp(){
      cout << "Enter Name: " << endl;  
      cin >> name;
      cout << "Enter Integer: " << endl;  
      cin >> n; 
      cout<<"Enter Character: "<<endl;
      cin >> ch;  
      cout << name << n  << ch << endl;
   }
};
int main() {
   ObPass object;
   object.disp();
   return 0;
}


PS: "disp" (display) is a bad name for a function where the user is inputting values.
Last edited on
In your disp() method, you're passing the ObPass arguement in by value. This means that objectpass is a new object is not the same object as object in main(), but a copy of it.

Inside the disp() method, if you chang the values of the members of objectpass, you are changing the values of this new copy. However, if instead you change the value of n, then you're changing the members of this.

See https://www.learncpp.com/cpp-tutorial/72-passing-arguments-by-value/ for an explanation of passing by value, if you're not familiar with it.
Topic archived. No new replies allowed.