Muthu
Muthu

Reputation: 209

Global variable inside the class and local function variable

I tried out a c++ program, where i declared a variable of type int named "a" inside a class. And created a function named "b" inside which again i declared a variable named "a" and assigned the value to it. The variable "a" inside the function is considered as local variable. And if i want to assign the value to the variable a which is present in the class definition(not inside the function), how can i do it?

#include <iostream>

using namespace std;

class a{
    public:int a;//need to assign value for this "a" inside the function how can i do it
    int b(){
        int a=5;
        a=7;
        cout<<a;
    }
};
int main() {
    a A;
    A.b();
}

Upvotes: 2

Views: 5107

Answers (4)

knoxgon
knoxgon

Reputation: 1243

The problem is lying under the lack of this pointer to the class variable.

If you have a local variable inside your class function that is identical to the class variable, then you must use this keyword for the compiler to distinguish.

An easy mistake people tend to do is when having exactly the same names for the mutator's parameter variable as the class' variable.

#include <iostream>

using namespace std;

class Foo {
    int numberA;
public:
    void setNumberA(int numberA) {
        numberA = numberA; /*Incorrect way, the compiler thinks 
                             you are trying to modify the parameter*/

        this->numberA = numberA; //Correct way
    }
};

In your case, you must use this->a inside the function b().

Upvotes: 0

Shiv Kumar
Shiv Kumar

Reputation: 1114

To access the class variable you can use this keyword . For more explanation and getting knowledge of 'this` keyword you can go here

#include <iostream>

using namespace std;

class a{
    public:int a;//need to assign value for this "a" inside the function how can i do it
    int b(){
        int a=5;
        a=7;
        this->a = 8; // set outer a =8
        cout<< "local variable a: " << a << endl;
        cout<< "class a object variable a: " << this->a << endl;
        return 0;
    }
};
int main() {
    a A;
    A.b();
    cout << "A's variable a: " << A.a << endl; //should print 8
    return 0;
}

Upvotes: 8

oarcas
oarcas

Reputation: 149

Use this->a.

this allows you to access the members and methods of an instance from within.

EDIT: this is an academical exercise, but a bad programming practice. Just use different names for classes, members and variables.

Upvotes: 5

jfMR
jfMR

Reputation: 24738

Specifying the class-qualified name of a, i.e.: a::a, will do:

a::a=7;

Upvotes: 2

Related Questions