C++ Function with Sring Return

I'd like to write a class member function which takes no parameters but returns a string. It would be used to return formatted text containing values of member variables in a class. The call might be used something like:

cout << "member variable listing: " << MyClassInstance.write();

Because I don't want any parameters, I don't think I can return either a pointer or a reference (only local automatic variables in the function), but I can't see how else I can return a string of characters, as opposed to a single character. Is this possible, and if so what should the return type for the function be?

Thanks (and apologies if I accidentally posted a partially completed version of this question).
Make the function return type std::string and merely return a string. It can be a variable or a hard coded string.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

std::string hello()
{
  std::string word = "hello world";
  return word;
}

int main()
{
	std::cout << hello() << std::endl;

	std::cin.get();

	return 0;
}
Last edited on
Thanks eker646; that is the solution I've been struggling to find.
One other suggestion, if i may.

Instead of using std:: in your line code. Try putting this below your #include <string>

using namespace std;

This will eliminate you having to use std::xxxxxxx throughout your coding for the rest of your program.

Using one of your code lines std::cout<<hello() << std::endl;

could simply be written as cout<<"hello<<endl;




Just a tip.



I know that.
Sometimes you have to assume that everyone is stupid. I don't know if AndeM knows that string uses the std namespace so I added it.
Last edited on
Topic archived. No new replies allowed.