Re: copy constructor
On Jun 17, 12:43 am, Irek Szczesniak <irek.szczesn...@gmail.com>
wrote:
Hi,
I need to count the number of objects that my class creates with the
copy constructor. Therefore I could create my own copy constructor
where I'll keep track of the number of created objects by increasing a
static integer variable. If I do this, then I would need to implement
what the default constructor does for me. Is there nonetheless some
way of using the default copy constructor, so I don't need to
implement it?
Sure, inherit your class from the copy counting class:
#include <iostream>
#include <ostream>
template< class T >
class copy_counter
{
public:
copy_counter()
{
}
copy_counter(copy_counter< T > const&)
{
++copies;
}
static size_t copies;
};
template< class T > size_t copy_counter< T >::copies = 0;
class my_class
: public copy_counter< my_class >
{
public:
explicit my_class(std::string const& data = "")
: data(data)
{
}
private:
std::string data;
};
int
main()
{
my_class obj1("obj1");
my_class obj2(obj1);
my_class obj3(obj2);
std::cout << my_class::copies << " copies of my_class created" <<
std::endl;
}
$ ./a.out
2 copies of my_class created
$
The template hack allows you to count copies of objects of different
classes separately :-)
--
Regards,
Alex Shulgin
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]