I have the following class, which includes a copy constructor:
Header File: Fred.h
namespace foo {
class Fred {
private:
int _x;
int _y;
public:
Fred(); // Default constructor
Fred(Fred const &other); // Copy constructor
Fred(int x, int y); // Regular parameters
~Fred(); // Destrcutor
};
}
Implementation File: Fred.cpp
#include "Fred.h"
#include <iostream>
foo::Fred::Fred(){
_x = 0;
_y = 0;
std::cout << "Calling the default constructor\n";
}
foo::Fred::Fred(Fred const &other){
_x = other._x;
_y = other._y;
std::cout << "Calling the copy constructor";
}
foo::Fred::Fred(int x, int y){
_x = x;
_y = y;
std::cout << "Calling the convenience constructor\n";
}
foo::Fred::~Fred(){
std::cout << "Goodbye, cruel world!\n";
}
I was expecting to see the destructor called when it got out of scope, instead, the copy constructor was called and then the destructor. Why was a copy created? Am I leaking memory?
using namespace foo;
int main(int argc, const char * argv[])
{
{
Fred f2 = *new Fred();
} // I was expecting to see a destructor call only
return 0;
}