Supposing that I have the following two classes:
#ifndef CLASS1_H
#define CLASS1_H
#include <QDebug>
class Class1
{
public:
Class1(){}
void printName()
{
qDebug() << "Class1";
}
};
#endif // CLASS1_H
and
#ifndef CLASS2_H
#define CLASS2_H
#include "class1.h"
class Class2
{
public:
Class2(Class1 *pointerToClass1)
{
this->pointerToClass1 = pointerToClass1;
}
void doSomething()
{
this->pointerToClass1->printName();
}
private:
Class1 *pointerToClass1;
};
#endif // CLASS2_H
And the main function looks like this:
#include <QCoreApplication>
#include "class1.h"
#include "class2.h"
void func1()
{
Class1 class1;
Class2 *class2_1 = new Class2(&class1);
Class2 class2_2(&class1);
class2_1->doSomething();
class2_2.doSomething();
delete class2_1;
class2_1 = NULL;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
func1();
return a.exec();
}
What is the main difference of creating an object in the heap (e.g. Class2 *class2_1 = new Class2(&class1);
) and just create the object on the stack (e.g. Class2 class2_2(&class1);
)?
As far as I know, it is preferred to create the object on the stack when it is declared locally and has a short life. Also, the data is lost when the object exits the stack and in the heap, we need to call delete to free the memory. Is that correct?
Therefore, there is some advantage in using one or another?