destructor called after calling constructor

By looking at the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
int wow=0;
class Foo{
   int cow = 0;
public:
  Foo(){
    std::cout << "Foo +\n";
    cow = 0;
    ++wow;
  }
  Foo(int n){
    std::cout << "Foo has " << n << "\n";
    cow = n;
    ++wow;
  }
  ~Foo(){
     std::cout << cow << " ~ Foo -\n";
   }
  void print(){
    std::cout << cow << " is the foo#\n";
  }
};

int main(){
  void * bar = ::operator new(sizeof(Foo));
  Foo * a = new(bar) Foo;
  *a = Foo(10);
  std::cout << wow << std::endl;
  a->~Foo();
  ::operator delete(bar);
  return 0;
}

and compiling and running it, the console shows:

Foo+
Foo has 10
10 ~ Foo -
2
10 ~ Foo -

My question is, why is the destructor called upon calling the constructor?

Should the first destructor call be 0 ~ Foo - ? Since that is the first Foo that is overwritten by Foo(10)?

Last edited on
*a = Foo(10);This creates a temporary, unnamed Foo object and then assigns it to *a using a compiler-generated assignment operator overload, which would look something like:
1
2
3
4
5
6
    
    Foo& operator=(const Foo& foo)
    {
        cow = foo.cow;
        return *this;
    }

The temporary object is then destroyed.
Last edited on
Can you give me another example of it please?
An example of what? What is the thing that you don't understand?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
int wow=0;
class Foo{
   int cow = 0;
public:
  Foo(){
    std::cout << "Foo +\n";
    cow = 0;
    ++wow;
  }
  Foo(int n){
    std::cout << "Foo has " << n << "\n";
    cow = n;
    ++wow;
  }
  ~Foo(){
     std::cout << cow << " ~ Foo -\n";
   }
  void print(){
    std::cout << cow << " is the foo#\n";
  }
};

int main(){
  void * bar = ::operator new(sizeof(Foo));
  Foo * a = ( Foo * )bar;
  *a = Foo(10);
  std::cout << wow << std::endl;
  a->~Foo();
  ::operator delete(bar);
  return 0;
}


Now I changed my code, this time it does not output Foo +, but it stills output 10 ~ Foo - twice? Why?
@MikeyBoy I still dont get as why a temporary constructor will be destroyed with a message of 10 ~ Foo -? A temporary constructor Foo has a member cow with a value of 0 right?
Please can you give me something like an indepth explanation or step by step on what is going on behind the scence of the line
*a = Foo(10);
Okay I already get it. Thanks for your help.
Topic archived. No new replies allowed.