In Class declaration, why can't the parameters in the constructor have the same name as the variables defined in the private part?

StackOverflow https://stackoverflow.com/questions/22443989

Вопрос

I hope my question is clear.. If we have

    Class A
    {
    public: 
        A(); //default constructor
        A(int new_a, string new_b);
    private:
        int a;string b;
    };

(Sorry that I'm new to stack overflow and my formatting may be horrible.)

Aren't "new_a" and "new_b" mean the something as the a and b in private part? why do we put different names to them instead..?

thanks for answer!

Это было полезно?

Решение

You may declare the constructor the following way

Class A
{
public: 
    A(); //default constructor
    A( int a, string b);
private:
    int a;string b;
};

According to the C++ Standard

In a function declaration, or in any function declarator except the declarator of a function definition (8.4), names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator

So member function parameters may have the same names as private data members of the class. Also you could define the constructor the following way

A::A( int a, string b) : a( a ), b( b ) {}

or

A::A( int a, string b){ A::a = a; A::b = b; }

or

A::A( int a, string b){ this->a = a; this->b = b; }

Другие советы

They can have the same names. But when you do that you have to disambiguate the member from the parameter with the same name inside the body of the constructor.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top