Hey I was wondering how the string class is able to output its self the way it does.
For example:

#include <iostream>
#include <string>

using namespace std;

int main()
{
	string testString;
	
	testString = "Hello";
	
	cout << testString << endl;	
	
	system("PAUSE");
	return 0;
}

If I were to try to make a mimic class such as

#include <iostream>
#include <string>

using namespace std;

class myClass
{
	string content;
	
	
	public:
		
	void operator=(string newContent)
	{
		content = newContent;
	}
	
	string getContent()
	{
		return content;
	}
};


int main()
{
	myClass testString;
	
	testString = "Hello";
	
	cout << testString.getContent() << endl;	
	
	system("PAUSE");
	return 0;
}

I have to call my getContent() function to return the content of the class.

How does the string class output its contents without needing to call a function?

Thank you to those who take the time to read this.

Recommended Answers

All 3 Replies

you have to overload the << operator

class MyClass
{
public:
   friend ofstream& operator<<(const ofstream& out, const MyClass& str);
..
...
};

Thanks so much I knew it had something to do with operators but I didn't know what one.

There is also conversion Function :

#include<iostream>
#include<cstring>

using namespace std;
 
class Letters
{
private:
	char str[50];
public:
	Letters()  { str[0] = '\0';}
	Letters(const char * p)  { strcpy(str,p);  }

	operator const char *() { return str; } //conversion function
};
int main()
{ 		
		Letters str("hello world");

		cout<<str;
}

Of course there are some subtle issues with that class, but we
shall not discuss it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.