Home > Back-end >  What arguments does new take?
What arguments does new take?

Time:01-05

Does new in C call a constructor behind the scenes? Or is it the other way around?

I have seen code like new MyClass(*this) which confuses me, since I didn't know that new could take arguments.

Maybe that's because new calls one of its constructors and, as a result, it can take the arguments declared by any of the constructors defined?


I assume this has been asked already, but I couldn't find the question answering it.

CodePudding user response:

MyClass(*this) creates an object of type MyClass by calling its constructor and passing *this as an argument. Putting new behind it means the object is allocated on the heap instead of the stack. It's not new which is taking the argument, it's MyClass.

CodePudding user response:

There is a difference between new and operator new. The new operator does both allocation of memory and the initialization whereas the operator new only does allocation. In your case you call new which allocate and initialize an object of MyClass class using a ctor.

#include <iostream>

class A {
    public:
        int m_value; 
        A(int value): m_value(value){};
};

int main (){
    int *a  = new int; 
    auto cb= new A(1);

    std::cout << *a << std::endl; 
    std::cout << b->m_value << std::endl; 
    printf("x ", *b);

}
Program returned: 
0
15
0f

As you can see the new for the a variable create only a pointer but nothing in it. That why when we dereference it we have 0 (all bit all 0, int is 4 bits most of the time so the pointer point to a memory content = to 0x0000) But for the b variable we initialize a value. And if we look at the memory content of the b object we can read 0f which mean it contain 15 (the member value)

CodePudding user response:

This is not new taking arguments, it's the constructor taking arguments.

  •  Tags:  
  • c
  • Related