Hi all,

I'm busy coding up some classes now and I was wondering if there is any danger in using a variable name twice, if the variable is limited to local scope.

For instance, let's say I have the following piece of code:

class Foo
{

void function1( double variable1 )
{
double variable2;
double variable3;
variable2 = function2( variable2 );
}

double function2( double variable2 )
{
double variable1;
double variable3;
return( variable1 * variable2 ) ;
}

};

In this code, variable2 appears locally in function1 and also as the definition of an input parameter for function2. Is this dangerous? Should the argument of function2 have another variable name? Or is this a stable way to program in C++? The same goes for variable1. Variable3 is in this case a dummy variable that is declared in local scope in both function1 and function2. Is this dangerous? Should variable3 be called differently in one of the functions? Or does the fact that the scope is local take care of any possible conflicts?

Thanks a lot,

Kartik

Recommended Answers

All 15 Replies

In the same scope, yes.
In different scopes, no.
But it could be very confusing to anyone reading the code. Generally not in functions as you have them, though.

Be careful if defining variables within code blocks ( if , for , while , ect)

In the same scope, yes.
In different scopes, no.
But it could be very confusing to anyone reading the code. Generally not in functions as you have them, though.

Be careful if defining variables within code blocks ( if , for , while , ect)

Thanks, right now I have a few functions that have variables in local scope that are defined with the same names.

I actually started off by just programming void functions and declaring variables that were shared by functions in the class directly, outside of any functions. Is this a safe way to program? I switched over to programming functions with return values and input argument, and locally declaring the variables because I wasn't sure if there might be a problem with functions interfering in their use of a single variable declared within the class.

To elucidate what I mean, for the code I posted in my initial post, it would amount to something like this:

class Foo
{
public:
protected:
private:
double variable1;
double variable2;
double variable3;
 
void function1()
{
variable2 = function2();
}
 
double function2( )
{
variable2 = variable1 * variable2;
}
 
};

Is this safe? Or is it better to program the way I've given in my initial post?

Thanks,

Kartik

PS: Just realised I missed out definition of public/protected/private in my initial post. Same questions go in any case.

The second version is better. You've reduced the ambiguity and you haven't hidden any variables. In addition, the functions are using the member variables to produce results.

However..., your function2 is specified to return a double and you have no return statement. This would be a better implementation:

double function2( )
{
  return (variable1 * variable2);
}

PS: Just realised I missed out definition of public/protected/private in my initial post. Same questions go in any case.

That is fine. It just means that the compiler assumes everything is defined as private. It makes your class pretty useless, because almost nothing can get at any members, but it is technically correct.

The second version is better. You've reduced the ambiguity and you haven't hidden any variables. In addition, the functions are using the member variables to produce results.

However..., your function2 is specified to return a double and you have no return statement. This would be a better implementation:

double function2( )
{
  return (variable1 * variable2);
}

That is fine. It just means that the compiler assumes everything is defined as private. It makes your class pretty useless, because almost nothing can get at any members, but it is technically correct.

Ah yea, I meant to make function2 void type when I rewrote the class, but forgot.

So there isn't any risk involved then in having the functions make use of variables that are not locally declared? Initially, I programmed it like that, but I then thought maybe also for readability of the code, that it would be better for the function to be explicit in what the inputs and outputs are, especially since I have header files and sources files with the class variables declared outside the functions, placed in the header files, whereas the functions declared in the source files (prototypes declared in the header).

I am just worried that it's possible that I accidently program functions that interfere with each other because they both call on the same class variables that are not restricted to local scope of the functions. I know if the code is functioning fine that this is not a problem, but I am trying to setup some good programming practices for myself to minimise errors from creeping in that could take ages to debug.

If the second way of programming is relatively fail-safe compared to the first method, then I will employ it. Just want to make sure.

Thanks,

Kartik

Ah yea, I meant to make function2 void type when I rewrote the class, but forgot.

If you had, function 1 would probably cause a compile error because you are attempting to assign the non-existent return value to a variable.

So there isn't any risk involved then in having the functions make use of variables that are not locally declared? Initially, I programmed it like that, but I then thought maybe also for readability of the code, that it would be better for the function to be explicit in what the inputs and outputs are, especially since I have header files and sources files with the class variables declared outside the functions, placed in the header files, whereas the functions declared in the source files (prototypes declared in the header).

This is tricky. I think I'll say there is still some. How much is the direct result of how much you attention you give to the issue. It is not an issue when the variables and the functions are associated with each other inside a class. It is customary for the member variables to be declared outside of, and separate from, the member functions. What you need to be conscious of is that the member variables exist and what their names are when you are declaring your functions' local variables and parameters. You can use global variables, member variables, and local variables all together inside one function. As long as your local variable names are not identical to the global and/or member variable names, there should be no overlap issues.

I am just worried that it's possible that I accidently program functions that interfere with each other because they both call on the same class variables that are not restricted to local scope of the functions. I know if the code is functioning fine that this is not a problem, but I am trying to setup some good programming practices for myself to minimise errors from creeping in that could take ages to debug.

This is a valid concern, however, you need to understand that a major objective of OOP is encapsulation. This is achieved by creating private member variables that are referenced and manipulated by public member functions. Any of the functions can do anything to any of the variables. The effectiveness and safety of your functions is entirely the result of your algorithm and how much attention you pay while writing the code.

If the second way of programming is relatively fail-safe compared to the first method, then I will employ it. Just want to make sure.

When doing OOP, do so. It is substantially more effective and appropriate for OOP. But unfortunately, nothing is fail-safe. That's what debugging is for. Programming is not brainless work, you must pay attention to what you are doing. The "safety" of your code is directly related to how well you paid attention while writing it.

For procedural programming this entire conversation is null and void.

If you had, function 1 would probably cause a compile error because you are attempting to assign the non-existent return value to a variable.

Oops, my bad again. Was trying to illustrate a point by changing the original code, but guess I should have just coded the second example from scratch again properly (good rule for me to remember!).

This is tricky. I think I'll say there is still some. How much is the direct result of how much you attention you give to the issue. It is not an issue when the variables and the functions are associated with each other inside a class. It is customary for the member variables to be declared outside of, and separate from, the member functions. What you need to be conscious of is that the member variables exist and what their names are when you are declaring your functions' local variables and parameters. You can use global variables, member variables, and local variables all together inside one function. As long as your local variable names are not identical to the global and/or member variable names, there should be no overlap issues.


This is a valid concern, however, you need to understand that a major objective of OOP is encapsulation. This is achieved by creating private member variables that are referenced and manipulated by public member functions. Any of the functions can do anything to any of the variables. The effectiveness and safety of your functions is entirely the result of your algorithm and how much attention you pay while writing the code.


When doing OOP, do so. It is substantially more effective and appropriate for OOP. But unfortunately, nothing is fail-safe. That's what debugging is for. Programming is not brainless work, you must pay attention to what you are doing. The "safety" of your code is directly related to how well you paid attention while writing it.

For procedural programming this entire conversation is null and void.

Thanks! That clears it up for me indeed :) Guess I'll switch back to my original code where I had class variables that were shared by class functions. I guess that's exactly the ingredient that I'm missing at the moment; understanding the core principles of OOP. Think I'll have a browse on google and see if I can find more that describes the paradigm of encapsulation so I have a better grip on it.

Thanks again,

Kartik

Do not go back to your original style. The style in this post really is how it should be done.

Here's a good place to start reading up.

Your class should be laid out as follows:

//define your class
class myClass {
private:  //line not required, private is assumed if no other qualifier is used previously
  int iVar1, iVar2;  //integer member variables

protected:
  /*empty*/

public:
  myClass(); //default constructor
  ~myClass(); //default destructor
  void myFunction1( int newI1);  //another function
}; //end class definition

//implement member functions
myClass::myClass() {  //default constructor
  iVar1 = iVar2 = 0;
}

myClass::~myClass() { // default destructor
}

void myClass::myFunction1( int newI1) { //another function
  iVar1 = newI1;

  /* ... any other actions that use iVar1 and/or iVar2 ... */
}

If you had, function 1 would probably cause a compile error because you are attempting to assign the non-existent return value to a variable.


This is tricky. I think I'll say there is still some. How much is the direct result of how much you attention you give to the issue. It is not an issue when the variables and the functions are associated with each other inside a class. It is customary for the member variables to be declared outside of, and separate from, the member functions. What you need to be conscious of is that the member variables exist and what their names are when you are declaring your functions' local variables and parameters. You can use global variables, member variables, and local variables all together inside one function. As long as your local variable names are not identical to the global and/or member variable names, there should be no overlap issues.


This is a valid concern, however, you need to understand that a major objective of OOP is encapsulation. This is achieved by creating private member variables that are referenced and manipulated by public member functions. Any of the functions can do anything to any of the variables. The effectiveness and safety of your functions is entirely the result of your algorithm and how much attention you pay while writing the code.


When doing OOP, do so. It is substantially more effective and appropriate for OOP. But unfortunately, nothing is fail-safe. That's what debugging is for. Programming is not brainless work, you must pay attention to what you are doing. The "safety" of your code is directly related to how well you paid attention while writing it.

For procedural programming this entire conversation is null and void.

Do not go back to your original style. The style in this post really is how it should be done.

Here's a good place to start reading up.

Your class should be laid out as follows:

//define your class
class myClass {
private:  //line not required, private is assumed if no other qualifier is used previously
  int iVar1, iVar2;  //integer member variables

protected:
  /*empty*/

public:
  myClass(); //default constructor
  ~myClass(); //default destructor
  void myFunction1( int newI1);  //another function
}; //end class definition

//implement member functions
myClass::myClass() {  //default constructor
  iVar1 = iVar2 = 0;
}

myClass::~myClass() { // default destructor
}

void myClass::myFunction1( int newI1) { //another function
  iVar1 = newI1;

  /* ... any other actions that use iVar1 and/or iVar2 ... */
}

Ok yep, thanks for the example. I read through the whole cplusplus tutorial, just guess it didn't come through clearly what the advantages are disadvantages are of programming class variables as being local to functions or shared between functions. I guess the one ingredient that I was missing is that function arguments should be called differently and then internally assigned to shared class variables, such as in myFunction1 in your example.

Thanks,

Kartik

Glad you figured it out :).

Glad you figured it out :).

Yep thanks a lot :) I do have a related query, which maybe you don't mind taking a look at.

I see a lot of different implementations of classes online, and one of the things I'm not sure is, when you declare class variables, is it better to declare them directly public (if they store data for instance that you need access to) or is it better to declare them private and then employ a get-function to access the data when you instantiate an object of the class?

Thanks a lot for your feedback once again,

Kartik

In general designate them private.

That is a subject of much debate and I am not going to try to steer you one way or the other.

What the argument really comes down to is whether or not the variable is only used by "getters" and "setters" that have absolute minimum functionality (a solitary assignment or return statement). Many people say to just make it public if that is the case. Others say everything should be private with the getters and setters (I tend to lean this way as well).

A major idea behind the OOP concept of encapsulation is protecting data integrity by separating the user from the data. The user must follow a defined protocol to access and manipulate the data. That protocol is defined and enforced in the object's public interface. If you don't follow the rules defined by the interface, you don't get access. When a member variable is public, this "security" is completely circumvented.

Glad you figured it out :).

That is a subject of much debate and I am not going to try to steer you one way or the other.

What the argument really comes down to is whether or not the variable is only used by "getters" and "setters" that have absolute minimum functionality (a solitary assignment or return statement). Many people say to just make it public if that is the case. Others say everything should be private with the getters and setters (I tend to lean this way as well).

A major idea behind the OOP concept of encapsulation is protecting data integrity by separating the user from the data. The user must follow a defined protocol to access and manipulate the data. That protocol is defined and enforced in the object's public interface. If you don't follow the rules defined by the interface, you don't get access. When a member variable is public, this "security" is completely circumvented.

I can see the perspective of protecting data integrity and I guess I subscribe to that rationale too, so I think I'll go ahead and employ getters and setters in my code.

Thanks a lot!

Kartik

There is absolutely nothing wrong with the code. Since your variables are used in their own scope, they don't affect each other.

Did you read the whole thread or just reply after skimming the first post? The OP is starting to learn OOP and was having trouble understanding the relationship between member variables and local variables within a class. (Hence, the slightly confusing thread title.)

As standalone functions, yes the code in the OP is technically correct. But they're member functions, not standalone functions.

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.