Deeack
October 26th, 2009, 06:37 PM
Hi, I'm looking for help in trying to get my head around how class destructors in C++ deal with elements of their class, and I have a few questions I was hoping you could help me out with.
Consider the following example:
using namespace std;
class MyClass {
private:
int myInt;
vector<int> myVector;
public:
MyClass() {
// Do stuff
}
~MyClass() {
// Safe to leave empty in this situation?
}
};
int main() {
MyClass *example = new MyClass();
delete MyClass;
}
In the above example, when the delete is called, would the destructor for the vector be called as well, or do i need to somehow call the destructors of all the elements in the class in the classes destructor?
I'm of the belief that's what would happen but I'm fairly new to coding in C++, so I want to get into the habit of dealing with memory right early rather than have to try and get out of bad habits later!
Also am i right in saying that the abovie situation differs from the following:
using namespace std;
class MyClass {
private:
int myInt;
vector<int> *myVector = new vector<int>;
public:
MyClass() {
// Do stuff
}
~MyClass() {
// Ensure myVector is deleted
delete MyVector;
}
};
int main() {
MyClass *example = new MyClass();
delete MyClass;
}
Where if you declare a pointer to an new object you have to call delete on it manually? Does calling a delete on an object call it's destructor, and as such "myVector" should free any memory it's allocated for itself, or am I required to free the vectors allocated memory myself somehow?
Any help in clarifying this would be greatly appreciated!
Consider the following example:
using namespace std;
class MyClass {
private:
int myInt;
vector<int> myVector;
public:
MyClass() {
// Do stuff
}
~MyClass() {
// Safe to leave empty in this situation?
}
};
int main() {
MyClass *example = new MyClass();
delete MyClass;
}
In the above example, when the delete is called, would the destructor for the vector be called as well, or do i need to somehow call the destructors of all the elements in the class in the classes destructor?
I'm of the belief that's what would happen but I'm fairly new to coding in C++, so I want to get into the habit of dealing with memory right early rather than have to try and get out of bad habits later!
Also am i right in saying that the abovie situation differs from the following:
using namespace std;
class MyClass {
private:
int myInt;
vector<int> *myVector = new vector<int>;
public:
MyClass() {
// Do stuff
}
~MyClass() {
// Ensure myVector is deleted
delete MyVector;
}
};
int main() {
MyClass *example = new MyClass();
delete MyClass;
}
Where if you declare a pointer to an new object you have to call delete on it manually? Does calling a delete on an object call it's destructor, and as such "myVector" should free any memory it's allocated for itself, or am I required to free the vectors allocated memory myself somehow?
Any help in clarifying this would be greatly appreciated!