foo.h
#include "class1.h"
class foo{
private:
class1* class1ObjectPointer;
public:
foo();
virtual ~foo();
void foomethod();
}
foo.cpp (VERSION 1)
#include "foo.h"
foo::foo()
{
this->class1ObjectPointer = new class1();
}
foo::~foo()
{
if( this->class1ObjectPointer != NULL ){
delete class1ObjectPointer;
this->class1ObjectPointer = NULL;
}
}
foo::foomethod(){
*(this->class1ObjectPointer) = some_method();
//suppose some method returns an object of class1
}
foo.cpp (VERSION 2)
#include "foo.h"
foo::foo()
{
this->class1ObjectPointer = NULL;
}
foo::~foo()
{
if( this->class1ObjectPointer != NULL ){
delete class1ObjectPointer;
this->class1ObjectPointer = NULL;
}
}
foo::foomethod(){
class1 object;
object = some_method();
//suppose some method returns an object of class1
this->class1ObjectPointer = new class1(object); // copy constructor
}
Which pointer assignment is better in the following cases:
- objects of class1 always have fixed size (e.g. a class with fixed variables in it)
- objects of class1 may have members with variable size (e.g. a class that has a matrix in it which can potentially have different sizes)
Would you suggest any other and better way of doing what I did in these snippets?