gfdsal
gfdsal

Reputation: 721

The scope of arguments in Class in c++

I have this class in c++ that basically prints out "cat1". Following is the code:

class Cat {
public:
        Cat(const std::string h = "")
        : name(h)
        {
                std::cout << "Cat " << name << " created." << std::endl;
        }
        void eatFood(){
                std::cout << "Food eaten by cat named " << name << "." << std::endl;
        }

        std::string name="";
};

Cat makeCat2() {
        return Cat("Cat2");
}

int main(int argc, char *argv[])
{
    Cat kit = makeCat2();
    kit.eatFood();
}

THe result is

Cat Cat2 created
Food eaten by cat named Cat2

But when instead of changing the argument declaration of the class Cat from

Cat(const std::string h = "")
        : name(h)

to

Cat(const std::string name = "")

The result is

Cat Cat2 created
Food eaten by cat named 

So my question is why if we change from std::string h = "" to directly assiging the arguments to name via std::string name= "" then why is string variable "name" is not stored or updated i.e when member function eatfood() prints "name" nothing prints out which is initial value. In other words the only way to update the arugument cat2 in member function is to use initialization method using name(h)?

Upvotes: 1

Views: 190

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

There are two variables named name here.

The first is the parameter to the constructor, which is only in scope for that constructor (this is the same variable that you instead called h in the other example).

The second is the member variable.

If you don't set the second to the same value as the first, that value is never stored anywhere and will be "lost" when the constructor ends.

Upvotes: 1

Soeren
Soeren

Reputation: 1829

The parameter has no implicit connection to the member variable.

So you have two options:

first use the initializer list:

Cat(const std::string h = "")
    : name(h)

or initialize the variable yourself in the constructor:

 Cat(const std::string h = "") {
    this->name = h;
 }

Upvotes: 1

Related Questions