Is it the matter of private and public ?

Hi, everyone, the following code runs fine,but if

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
38
39
40
41
42
43
44
45
46
47
48
  #include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class WhatThe
{
public:

		void settankName(string name)
	{
		 tankName = name;
	}

string gettankName()
{
	return tankName;
}

void displayMessage()
{
	cout<< "welcome to the Tank Museum\n"<<gettankName()<<endl;
}

private:
	string tankName;
};

int main()
{
	string nameofTank;
	WhatThe myTank;

	cout<<"Initial tank name is: "<<myTank.gettankName()<<endl;

	cout<<"\nPlease enter the tanks name: "<<endl;
	getline( cin, nameofTank);
	myTank.settankName (nameofTank);
	cout<<endl;

	myTank.displayMessage();

	

  return 0;
}


But if l change the last statement before "return 0;", to "myTank.gettankName()"
rather than "myTank.displayMessage();" , it comes out that the name l entered
could not appear in the console just like the "initial tank name is"...

However, l wonder why the displayMessage() function will output the name l entered on the screen just by the "<<gettankName()<<" but the former cannot?
Printing and returning are two different things.

Printing means that you make something visible on the screen. This is what std::cout is used for.

Returning is something you do to pass information from a function back to where the function was called from. The returned value can be used for anything you want, but you need to write the code for it to happen.

Some examples:
1
2
3
4
5
6
7
8
9
10
11
// print the name
std::cout << myTank.gettankName();

// store the name in a variable
std::string name = myTank.gettankName();

// pass the name as argument to another function 
if (!validName(myTank.gettankName()))
{
	std::cout << "Invalid tank name!\n"; 
}
Last edited on
Topic archived. No new replies allowed.