Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I override the default copy constructor and assignment operator with template versions in C++

I asked this question about overloading the copy constructor and assignment operator with template versions and considering the confusion involving around the question (since it seems to be a compiler bug), I thought I'd try with only template copy constructor and template assignment operator to see what happens. But they are completely ignored by the compiler.

struct BaseClass
{
public:
  BaseClass() {}

  template<typename T>
  BaseClass(const T& a_other)
  {
    int i = 0; // for break point which is not hit
  }

  template<typename T>
  BaseClass& operator= (const T& a_other)
  {
    int i = 0; // for break point which is not hit
    return *this;
  }

};

struct MyClass : public BaseClass
{
};

int main()
{
  MyClass i, j;
  i = j;

  return 0;
}

Why can't I over-ride the defaults with template versions (I suspect the answer will be the defaults are a better match but I would like the template versions to act as defaults as well)? And is there anything I can do to make sure the template versions are called instead of the defaults?

like image 425
Samaursa Avatar asked Feb 28 '12 18:02

Samaursa


People also ask

Why copy constructor and assignment operator's working is different?

The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space.

Can you use the copy constructor in the assignment operator?

You can safely invoke the copy assignment operator from the constructor as long as the operator is not declared virtual.


1 Answers

template<typename T>
BaseClass(const T& a_other) 

First of all, this is not a copy-constructor. It is rather a templated constructor.

The copy-constructor should be this:

BaseClass(const BaseClass & a_other)

Notice the difference?

Note that the templated constructor doesn't define copy-constructor. The compiler will still generate a default copy-constructor for you, instead of instantiating the templated constructor.

Same argument for copy-assignment.

like image 51
Nawaz Avatar answered Sep 18 '22 01:09

Nawaz