Well as written, your assignment creates a memory leak.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
class Stupid
{
int size;
int *array;
public:
Stupid(){
cout << "default ctor Stupid at " << reinterpret_cast<void*>(this) << endl;
}
Stupid(int arraysize)
{
cout << "Overload ctor Stupid at " << reinterpret_cast<void*>(this) << endl;
size = arraysize;
array = new int[size];
}
~Stupid()
{
cout << "default dtor Stupid at " << reinterpret_cast<void*>(this) << endl;
delete array;
}
};
class Container
{
private:
Stupid s;
int size;
public:
Container(int stupidsize)
{
cout << "Overload ctor Container at " << reinterpret_cast<void*>(this) << endl;
size = stupidsize;
s = Stupid(size);
}
};
int main ( ) {
Container c(3);
}
$ g++ foo.cpp
$ ./a.out
default ctor Stupid at 0x7ffc5bd53bf0
Overload ctor Container at 0x7ffc5bd53bf0
Overload ctor Stupid at 0x7ffc5bd53bb0
default dtor Stupid at 0x7ffc5bd53bb0
default dtor Stupid at 0x7ffc5bd53bf0
*** Error in `./a.out': double free or corruption (fasttop): 0x00000000011cc030 ***
s gets default constructed at the point your container is constructed, but the assignment completely trashes it.
If you have non-trivial ctor and dtor, you probably need the copy assignment ctor as well.
Rule of three (C++ programming) - Wikipedia
> I need to do Stupid *s and then use s = new Stupid(size);
Well it's one way I suppose.
It might be a good way if size is large and perhaps in some way optional or needed later. Then you don't immediately waste a lot of resources creating something you might not need.
Another way is to just use an initialisation list.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
class Stupid
{
int size;
int *array;
public:
Stupid(){
cout << "default ctor Stupid at " << reinterpret_cast<void*>(this) << endl;
size = 0;
array = 0;
}
Stupid(int arraysize)
{
cout << "Overload ctor Stupid at " << reinterpret_cast<void*>(this) << endl;
size = arraysize;
array = new int[size];
}
~Stupid()
{
cout << "default dtor Stupid at " << reinterpret_cast<void*>(this) << endl;
delete array;
}
};
class Container
{
private:
Stupid s;
int size;
public:
Container(int stupidsize) : s(stupidsize)
{
cout << "Overload ctor Container at " << reinterpret_cast<void*>(this) << endl;
size = stupidsize;
//s = Stupid(size); // s is now constructed in the initialisation list
}
};
int main ( ) {
Container c(3);
}