I'm sort of new to the technical reasons for constructors and destructors. I wrote a program with functions that display an objects starting state, end state, memory location, value, and when the constructors and destructors are called.
I'm having trouble understanding why they are called when they are and what they're actually doing. I'll post the results of a test run and the code I'm using - as well as what I know lol.
RESULTS:
Constructor called on 0x7fffc053f070
Initial state:
Location: 0x7fffc053f070
Value: 0
--- FOO ----
Location: 0x7fffc053f070
Value: 1
--- BAR ----
Location: 0x7fffc053f080
Value: 2
Destructor called on 0x7fffc053f080
--- BAZ ----
Location: 0x7fffc053f070
Value: 2
Final state:
Location: 0x7fffc053f070
Value: 2
Destructor called on 0x7fffc053f070
CODE:
#include <iostream>
#include <vector>
using namespace std;
//Short memory addresses are on the heap
//Long memory addresses are on the stack
class A {
public:
A(){
m_iValue = 0;
cout << "Constructor called on " << this << endl;
}
/* A(const A & a){
m_iValue = a.m_iValue;
cout << "Copy constructor called on " << this << endl;
}
*/
void increment(){
m_iValue++;
}
void display(){
cout << "Location: " << this << endl;
cout << " Value: " <<m_iValue << endl;
cout << endl;
}
virtual ~A(){
cout << "Destructor called on " << this << endl;
}
private:
int m_iValue;
};
void foo(A & a){
a.increment();
a.display();
}
void bar(A a){
a.increment();
a.display();
}
void baz(A * a){
a->increment();
a->display();
}
void blah(vector<A*> vA){
vA.back()->display();
delete vA.back();
vA.pop_back();
}
int main(int argc, char * argv[]){
A a;
cout << "Initial state: " << endl;
a.display();
cout << endl;
foo(a);
bar(a);
baz(&a);
cout << endl;
cout << "Final state: " << endl;
a.display();
return 0;
}
What I believe is happening:
So, the constructor is getting called once and the destructor is getting called twice. The constructor is called when the object is created in main. In foo(), m_iVariable is passed by reference, and the function increments m_iValue for the object at that location in memory. So the program displays the value as 1 (incremented from 0.)
This is where I get confused.. The third location is different from the first two locations. The object is getting passed in directly to bar(). I don't understand how the location can be different without calling the constructor or why the destructor is called after it increments, making the value 2.
But baz also increments the value. So that means bar didn't actually do anything? I still don't get how bar displays a new memory location and destructs, but never constructs.
Sorry for all the text, but anything will help. Thanks!
Oh and the commented out code, and the function blah were used for other things and aren't relative for this question.