Bubesh p
Bubesh p

Reputation: 65

Lifetime of objects in c++

class Entity
{
  public:
    int a;
    Entity(int t)
      :a(t)
    {
        std::cout << "Constructor !" << std::endl;
    }
    ~Entity()
    {
        std::cout << "Destructor !" << std::endl;
    }

    Entity(Entity& o)
    {
        std::cout << "Copied !" << std::endl;
        this->a = o.a;
    }
};

Entity hi()
{
    Entity oi(3);
   return oi;
} 

int main()
{
  {
        Entity o(1);
        o = hi();
  }
     std::cin.get();
}

OUTPUT:

Constructor !

Constructor !

Copied !

Destructor !

Destructor !

Destructor !


I created two objects and I copied one, So three constructors and three destructors.

Upvotes: 0

Views: 895

Answers (2)

Roushan Singh
Roushan Singh

Reputation: 93

This is a trivial question

Can any one explain the reason for three destructor?

when you call

o=hi();

your function is called which makes an object of type Entity , which in return calls the constructor. This is where you get one extra constructor message

Replace your Entity(int t) contructor by this

 Entity(int t)
   :a(t)
  {
    std::cout << "Constructor created with integer "<< a << std::endl;
  }

You will see which constructors were called when you run the code.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490808

Your "Copied!" line in the output is coming from the copy constructor, so you're creating three objects, not just two (then you're destroying all three, as expected).

Note that a copy constructor should normally take its argument by const reference. At a guess, you may be using Microsoft's C++ compiler, which will bind a temporary to a non-const reference.

Also note that if you turn on optimization, you can probably expect to see just two constructors and two destructors, with no copy construction happening. With a new enough (C++17) compiler, that should happen even if you don't turn on optimization (copy elision has become mandatory).

Upvotes: 2

Related Questions