+ 1
I don’t understand the point of an object with destructors and constructors
#include <iostream> using namespace std; class MyClass { public: MyClass(); ~MyClass(); }; MyClass::MyClass() { cout<<"Constructor"<<endl; } MyClass::~MyClass() { cout<<"Destructor"<<endl; } int main() { MyClass obj; } Why don’t you need to create an object at the end of the code for the program to work? I don’t understand how this works please help me
5 Antworten
+ 1
You don't need to create an object of your class for the code to work because the program enters in main(). It will still compile, but you don't need to call it. The same thing is true for functions as well. If you define a function outside of main and never call it, the program will still run, as long as there are no errors during compilation.
+ 1
You don't need to explicitely implement constructor and/or destructor if there is nothing specific to do in them.
0
The point of a constructor is to initialize an object in valid state. So it becomes usable. The point of a destructor is to perform what you consider needed before wiping the object off the memory.
0
For example, let's say you need to have a member of your object that is never null. You can initialize it in the constructor to make sure it has a value.
Also, let's say the object has a list as a member. You may want to delete all elements of that list in the destructor.
0
Constructors can be used to pass a specific Argument to the Class
In case you want to be using that class effectively