0

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.

user3327134
  • 11
  • 1
  • 3
  • `HashingTable* table2(myHashTable);` declares a pointer to `HashingTable`, not an actual `HashingTable` object. – aschepler Aug 05 '16 at 21:37
  • I would make `explicit` the constructor with `int` instead of copy constructor... – Jarod42 Aug 05 '16 at 21:49
  • 1
    `HashingTable` is not a template, so you cannot write `template HashingTable`. Also your code would not compile, there are missing semicolons and so on. Please post [real code](http://stackoverflow.com/help/mcve). – M.M Aug 05 '16 at 22:18

1 Answers1

2

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);
Rakete1111
  • 47,013
  • 16
  • 123
  • 162