roshinichi
roshinichi

Reputation: 3

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

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!

Upvotes: 0

Views: 70

Answers (2)

user207421
user207421

Reputation: 310893

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.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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; }

Upvotes: 3

Related Questions