Jump to content
  • Advertisement
Sign in to follow this  
amateur programmer

using the same variable name twice in C++

This topic is 4492 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

in java code u can have two variables with the same name eg class b { String name =""; public void method(String name) { this.name = name; } } is there a way u can do this in c++. That exact code in C++ generates an error request for member y in this

Share this post


Link to post
Share on other sites
Advertisement
You can, but it isn't a good idea. This is referred to as shadowing a variable, and is very prone to causing confusing bugs.

Share this post


Link to post
Share on other sites
You don't actually have two variables of the same name in that snippet. You have a variable B::name and a local variable (arg to function) called name. The exact same construct is possible in C++. The reason you got an error is because you tried to compile Java code with a C++ compiler.

You could do this:

class B
{
public:
char *name;

void SetName(char *name) { this->name = name; }
};






Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!