1

The following code doesn't compile:

#include<iostream>

class base
{
public:
   virtual ~base() = default;
   virtual void func(const int &i) = 0;
};

class derived : public base
{
   void func(int &i)
   {
   }
};

int main(int argc, char const *argv[])
{
   std::unique_ptr<base> ptr{new derived};
   return 0;
}

giving the error test.cpp:28:34: error: allocating an object of abstract class type 'derived'

However, if I remove the pass & in the parameters for both base and derived, the code compiles, but the function signatures are still different. Why does the former not compile, but the latter does? I don't understand how the pass by reference affects the compilation in this case.

24n8
  • 1,898
  • 1
  • 12
  • 25
  • Yes, I know that's what the error is implying, but I don't understand why `derived` overrides the pure virtual function if you remove the pass by reference. – 24n8 Feb 10 '20 at 16:22
  • You do not see missing **const**, really? – Slava Feb 10 '20 at 16:23
  • 1
    @Yksisarvinen Probably means removing the ref from both. – juanchopanza Feb 10 '20 at 16:25
  • 1
    @Slava I see the missing `const`...I'm asking why if you had `base::func(const int i)` and `derived::func(int i) compiles – 24n8 Feb 10 '20 at 16:25
  • 1
    @lamanon `int &` and `const int &` are different types. – Slava Feb 10 '20 at 16:26
  • 2
    Because a function that takes `T` parameter has the same signature as a function that takes `const T` as a parameter. But `const T &` and `T &` are different signatures, and not the same thing. See the duplicate question for more information. Welcome to C++, that's just how it works. – Sam Varshavchik Feb 10 '20 at 16:26

0 Answers0