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

Why my custom constructor is not called when an object is passed as a parameter?

I have the following code:


struct Entity {
    Entity() {
        std::cout << "[Entity] constructed\n";
    }

    ~Entity() {
        std::cout << "[Entity] destructed\n";
    }

    void Operation(void) {
        std::cout << "[Entity] operation\n";
    }
};

void funcCpy(Entity ent) {
    ent.Operation();
}

int main() {
    Entity e1;

    funcCpy(e1);
}

This is the output:

[Entity] constructed
[Entity] operation
[Entity] destructed
[Entity] destructed

I expected my function to use the custom constructor, so the output would look like this:

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

[Entity] constructed
[Entity] operation
[Entity] constructed
[Entity] destructed
[Entity] destructed

Why does this happens? How could I use my custom constructor instead?

Thanks 🙂

>Solution :

https://en.cppreference.com/w/cpp/language/copy_constructor

object as params will call copy constructor of class

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