0

I have class A, is it possible to make sth like this? A(A(A()))? I mean creating some object in constructor and so on?

class A {
private:
    A *a;
public:
    A(){
        printf("A()\n");
    }


    A( A * var){
        printf("A(A)\n");
        a = var;
    }
};




  int main() {
        A x = A(A(A()));

        return 0;
  };

and this give me output A(), i mean why not A() A(A) A(A)? My A class represent a memory cell so A(1) is pointing to array[1] but A(A(1)) is sth like array[array[1]]. But i don't have idea how to implement this, only one object is created. (this A class is just an example of what I want to achieve)

Eldragon01
  • 11
  • 2
  • 1
    You're using the move constructor, not the conversion constructor `A(A* var)` - and the move is elided so you wouldn't notice that one either. – Ted Lyngmo Jan 17 '21 at 21:11
  • so its not possible? i've implemented move constructor but doesnt help – Eldragon01 Jan 17 '21 at 21:15
  • Sure, you can do something like [this](https://godbolt.org/z/eqxTTh) – Ted Lyngmo Jan 17 '21 at 21:17
  • 2
    An `A` isn't a `A*`, so it isn't clear to me why you expect the `A(A* var)` constructor to be used. – Kevin Jan 17 '21 at 21:18
  • 2
    `A()` gives you a temporary instance, not a pointer. That said, I think you're describing a so-called "XY problem" (research that term online). As a new user here, please take the [tour] and read [ask]. – Ulrich Eckhardt Jan 17 '21 at 21:18
  • But without using new? – Eldragon01 Jan 17 '21 at 21:26
  • You could hide the `new`/`delete` using a `unqiue_ptr` and `make_unique`: [example](https://godbolt.org/z/ah8Y48) – Ted Lyngmo Jan 17 '21 at 21:51
  • but i want as i write above, A(A(A(A))) – Eldragon01 Jan 17 '21 at 21:55
  • Have you tried using templates? – P47 R1ck Jan 17 '21 at 22:13
  • 1
    I don't know of a way to get `A(A(A(A))))` to create more than one instance in C++17 or later. You could create a helper function if you want to avoid typing `make_unique`: [example](https://godbolt.org/z/he4bed) – Ted Lyngmo Jan 17 '21 at 22:17
  • Or you could create a constructor that creates all the instances you want recursively: [example](https://godbolt.org/z/8vj5fc) – Ted Lyngmo Jan 17 '21 at 22:24
  • It sounds like you want `A(A())` to create an `A` object that references another. The problem with that is that there is no way to distinguish this between a call to the copy/move constructor. Passing an object to the constructor of its own class is exactly how you ask for that object to be copied (or moved) into a new instance. You could perhaps distinguish this case in your code with a static factory function, like `static A nested(A);` and then you could do `A::nested(A::nested(A()))` for example. – cdhowie Jan 17 '21 at 23:26

0 Answers0