"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid Shadowing Variables in C++ Class Methods?

How to Avoid Shadowing Variables in C++ Class Methods?

Published on 2024-12-22
Browse:819

How to Avoid Shadowing Variables in C   Class Methods?

Shadowing Variables in C

When defining variables within classes, C allows for variables with the same name to be used in different scopes. This phenomenon, known as "shadowing variables," can lead to confusion and unexpected behavior.

In the given class definition:

class Measure {
int N;
double measure_set[];
char nomefile[];
double T;
};

the member variable T will be shadowed by the variable T declared in the get method:

void Measure::get() {
int M=0;
int nmax=50;

// ...

cout > T;
cout 

As a result, any modifications made to T within the get method will actually affect the shadowed variable measure_set[0]. To rectify this issue, consider using distinct variable names or utilizing class member prefixes to avoid name collisions:

Distinct Variable Names:

class Measure {
int N;
double measure_set[];
char nomefile[];
double temperature; // Rename variable
};

void Measure::get() {
// ...

cout > temperature;
cout 

Class Member Prefixes:

class Measure {
int m_N;
double m_measureSet[];
std::string m_nomefile;
double m_T;
};

void Measure::get() {
// ...

cout > m_T;
cout 

By prefixing member variables with the class name or a specific identifier, you can avoid name collisions and ensure that shadowed variables do not interfere with class members.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3