Reputation: 11
I'm very new to C++ and I'm attempting to overload the copy constructor for my HashingTable class. I've searched and searched for hours but can't seem to figure out why it is not being called. I'm using MVS 2015. Relevant code:
class HashingTable
{
...
public:
/*
* Constructors
*/
// Default constructor
HashingTable();
// Default destructor
virtual ~HashingTable();
// Constructor requiring size of vector to create
HashingTable(int size);
// Copy constructor requiring another instance of HashingTable
explicit HashingTable(const HashingTable& ht);
}
// Copy constructor using another table instance
template <class obj_type>
HashingTable<obj_type>::HashingTable(const HashingTable& ht)
{
cout << "Copy constructor called" << endl;
*this = ht;
}
// Overload of operator=
template <class obj_type>
HashingTable<obj_type>& HashingTable<obj_type>::operator=(constHashingTable& ht)
{
cout << "In operator=..."
if (this != &ht) // no need to copy itself
{
// do some stuff to *this
}
return *this;
}
In main()
HashingTable<char*>* table2(myHashTable);
The output of "Copy constructor called" or "In operator=..." is never seen.
Upvotes: 0
Views: 240
Reputation: 48948
myHashTable
is of type HashingTable<char*>*
. The important thing here is that it is a pointer, not an object.
table2
is also a HashingTable<char*>*
, so when you do HashingTable<char*>* table2(myHashTable);
, the pointer values are being copied, the actual copy constructor of HashingTable
is never called.
You have to copy a HashingTable
object to call the constructor you declared, i.e.
HashingTable<char*> notAPointerHashTable(*myHashTable);
Upvotes: 2