1

I was writing an Integer struct

struct Integer
{
    int value;
    Integer(int value_) : value(_value){ }
};

This works fine but instead I wanted to use value name for the parameter too and this causes a name clash. That's why I tried to use this keyword like below

struct Integer
{
    int value;
    Integer(int value) : this->value(value){ }
};

But I got an error and I don't seem to understand the problem here. I would be very happy to learn. Thanks for your answers.

Piamoon
  • 95
  • 1
  • 7
  • 6
    It *shouldn't* clash. The names in the initializer list are always members or constructors, while the name inside the parentheses will always be the argument. – Some programmer dude Oct 22 '20 at 10:06
  • 4
    "The names in the initializer list are always members or " **classes**. Constructors don't have names, classes do. Just noting so you can find the correct name lookup rules. E.g https://stackoverflow.com/questions/25549652/why-is-there-an-injected-class-name – MSalters Oct 22 '20 at 10:19

3 Answers3

6

This works fine but instead I wanted to use value name for the parameter too and this causes a name clash.

No it doesn't.

Integer(int value) : value(value){ }

This is just fine (if a little confusing to some).

It is simply not permitted in the language grammar to write this-> there, probably because it would make no sense to specify any other object: the this-> is implicitly done for you.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
5

The standard way is to write

struct Integer
{
    int value;
    Integer(int value) : value(value){ }
};

In the initializer list : value(value), the first value refers to the member (because that's what a member initializer initializes), while the second value refers to the constructor argument (because that's an expression, and the name in an expression is looked up by the ordinary rules).

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

As other answers already mentioned, it is not defined in the C++grammer / syntax. See it here.

And there is no need to specify this. To disambiguate class vs. member you don't use this, you use the scope resoultion operator.

See this (strange) example:


#include <iostream>


class A{
public:
    A(int a){
        std::cout << "A("<< a << ")\n";
    }
    A(){
        std::cout << "A()\n";
    }
};

class B : public A
{
public:
    int A;
     B(int a) : A::A(42), A(a)
    {}
};

int main()
{  
    B b = 12;
    std::cout << b.A;
    return 0;
}

And of course this already exists:

#include <iostream>

class B;

class A{
public:
    A(int a){
        std::cout << "A("<< a << ")\n";
    }
    A(){
        std::cout << "A()\n";
    }
    A(B& b);
};

class B : public A
{
public:
    int A;
     B(int a) : A::A(*this), A(a)
    {}
};

inline A::A(B& b){
    std::cout << "A(B&)\n";
}

int main()
{  
    B b = 12;
    std::cout << b.A;
    return 0;
}
Bernd
  • 2,113
  • 8
  • 22