Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which constructor (or implicit conversion) is called when passing a pointer to the constructor?

class Test {
    public:
 
    Test() {
        std::cout << "constructing" << std::endl;
    }
     Test(Test &t) {
        std::cout << "calling copy constructor" << std::endl;
    }
    Test(Test &&t) {
        std::cout << "calling move constructor" << std::endl;
    }
    Test& operator=(const Test& a){
        std::cout << "calling = constructor" << std::endl;
        return *this;
    }
};

Test* t1 = new Test(); 
Test* t2 (t1); // what's being called here 

When passing a pointer to a constructor like t2, what constructor is called? (Or implicit conversion and then constructor?) This code just prints "constructing" as a result of t1 being constructed.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Test* t2 (t1);

is direct-initialization. Direct-initialization considers constructors for class types, but Test* is a pointer type, not a class type. Non-class types do not have constructors.

For a pointer type, direct-initialization with a single expression in the parenthesized initializer simply copies the value of the expression into the new pointer object (potentially after implicit conversions, which are not necessary here).

So t2 will simply have the same value as t1, pointing to the object created with new Test();.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading