+ 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

12th May 2018, 5:53 PM
Daniel
5 Respuestas
+ 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.
12th May 2018, 11:00 PM
Zeke Williams
Zeke Williams - avatar
+ 1
You don't need to explicitely implement constructor and/or destructor if there is nothing specific to do in them.
13th May 2018, 3:22 AM
ifl
ifl - avatar
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.
12th May 2018, 6:22 PM
Blade Wolfmoon
Blade Wolfmoon - avatar
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.
12th May 2018, 6:39 PM
ifl
ifl - avatar
0
Constructors can be used to pass a specific Argument to the Class In case you want to be using that class effectively
13th May 2018, 11:41 PM
Mohammed Orif
Mohammed Orif - avatar