Gopi
Gopi

Reputation: 5877

Declaration of variables?

Case:1

    class A
    {
        private int i=0;

        public void display()
        {
            this.getValue();
        }

        private int getValue()
        {
            return i+2;
        }

    }

Case:2

    class B
    {
        public void display()
        {
            int i=0;
            this. getValue(i);
        }

        private int getValue(int i)
        {
            return i+2;
        }
    }

Does the declaration of "i" in both cases have any great difference (other than the global access) whenever I call display() ?

Upvotes: 0

Views: 209

Answers (3)

H2O
H2O

Reputation: 592

In first case i is a part of the object. When u create an object from class A, the object allocates memory for the variable "i". And it will remain until the object deleted.

But in the second way when you create the object from class B, there will be no memory allocation for the variable i. But only when you call the display function -in class B- memory variable "i" will be allocated temporarily. (When function's work is done all local variables will free)

Upvotes: 2

mouviciel
mouviciel

Reputation: 67831

In first case i exists outside of any method

In second case i exists only when display() method is called. If you want to give it persistence you can declare it as static.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170479

In this very case the effect is the same, but an instance of the class in the first snippet will occupy more memory.

Other than that in the first case it's a variable with the same address on each call and it retains the value, but in the second case it's not necessarily a variable with the same address - it is reallocated and reinitialized on each call.

Since you actually don't ever change i variable value you should declare it as const - this will give more clear code.

Upvotes: 2

Related Questions