Object or Variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream.h>
#include<fstream.h>
#include<string.h>
using namespace std;
int main()
{
int count,len,i;
string name,rev;
cout<<"\n how many?";
cin>>count;
while(count--)
{
   cout<<"\n name:";
cin>>name;
rev.erase();
for(i=name.length();i>=0;i--)
rev+=name[i];
cout<<"\n reverse:"<<rev;
}
return 0;
}


Hi.This is a 100% working program i saw online which reverses a string.I dont understand some aspects of this program.I want to know whether name & rev are objects or variables.
If they are objects,how can you in line 14 & 17 assign value to them as variables without specifying any data member.
And how can i execute their member functions such as in line 15 & 16 if they are variables.
I want to know whether name & rev are objects or variables.

They're instances of the string class.
http://www.cplusplus.com/reference/string/string/

how can you in line 14 & 17 assign value to them as variables without specifying any data member.

You can assign data like that because the >> and << operators for the cin and cout objects respectively have been overloaded to accept strings.
http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/

And how can i execute their member functions such as in line 15 & 16 if they are variables.

As above, they're instances of a class, not single variables. Therefore, they have their own member functions.
Last edited on
A variable is just an object with a name so name and rev are both variables and objects.
A string is an object (or class). On lines 14 and 17, the two "overloaded" operators '>>' and '+=' are called for the class string.
A class allows you to overload operators so that you have a common interface between it and other classes.
1
2
3
4
5
6
7
8
9
10
11
12
class Int
{
int I;
public:
Int():I(0){}
Int operator+(Int Param) //Here we overload the + operator, which must 
{                                      //take a value (the value on the right of the +,
Int temp;                         //and return a temporary object holding the result
temp.I = I + Param.I       //of adding our two objects.
return temp;
}
}
@BlackSheep / OP

It's worth noting that those two operators are overloaded in different classes.

The += operator is overloaded in the string class.

The >> operator isn't overloaded in string. It's overloaded in istream, of which cin is an instance.
Last edited on
Thanks a lot for the help guys
Topic archived. No new replies allowed.