Reputation: 117
class Stack{
public:
char data_[100];
int top_;
};
class Stack{
public:
char data[100];
int top;
};
What is the difference between the above two classes ? When I am using the class where the variable names are like int top_ ,the stack operations are running fine but when I am using the class with variables int top, errors like this are popping up : error: invalid use of member ( did you forget the '&' ?) error: conflicts with previous declaration. What is the role of the _(underscore) in this code ? Why is it making such a difference ?
#include<iostream>
#include<cstring>
using namespace std;
class Stack{
public:
char data[100];
int top;
bool empty()
{
return (top == -1);
}
char top()
{
return (data[top]);
}
void pop()
{
top--;
}
void push(char c)
{
data[++top] = c;
}
};
int main()
{
Stack s;
s.top = -1;
char str[10] = "ABCDEFGH";
for(int i=0;i<strlen(str);i++)
s.push(str[i]);
cout<<str<<endl;
cout<<"Reversed string is : ";
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
}
Upvotes: 0
Views: 1191
Reputation: 44268
What is the role of the _(underscore) in this code ?
It makes top
and top_
2 different identifiers. The same way you can make it top1
or topFOOBAR
.
Why is it making such a difference ?
When you use top
for member here you have a conflict with method named top
as well. Changing top
to top_
or top1
would make that conflict to disappear - you cannot have 2 different things in your class with the same name.
Some people have a habit to give member variables special names, like m_member
or member_
or even _member
(last one is not safe but still used sometimes). This decoration allows reader to see that code is dealing with member var on one side and avoiding name collisions like one you had on another.
Upvotes: 5