Search code examples
c++pointer-to-memberdefault-copy-constructor

class copy-constructor and pointer-to-member functions


I have a big program with some classes using pointer-to-member functions. The general code structure is:

#include <iostream>
using namespace std;

/**** CLASS FOO ****/
class Foo {
public:
  Foo();                       //constructor                                                                                                                            
  void Fun(){ /* stuff */ };   //some function                                                                                                                          

  void (Foo::*PointFun)();     //pointer-to-member function                                                                                                             
  inline void POINTFUN()       //for readability when calling PointFun                                                                                                  
  {
    return (this->*PointFun)();
  }
};

/**** Foo constructor ****/
Foo::Foo()
{
  PointFun = &Foo::Fun;        //define PointFun
}

/**** main program ****/
int main()
{
  Foo p;          //calls constructor
  p.Fun();        //calls some function

  p.POINTFUN();   //calls PointFun

  return 0;
}

This code compiles as it is. However, my question is: Do I need to define a copy-constructor and/or destructor in this case?

For example, I could define

Foo::Foo(const Foo& p)     //Foo copy-constructor
{
  PointFun = p.PointFun;
}

Foo::~Foo() {}             //Foo destructor

but I think this could be given by default by the compiler. Also, I am not sure about the default destructor since there is a pointer involved.


Solution

  • Do I need to define a copy-constructor and/or destructor in this case?

    No. Member-function pointers are copyable, and don't need any special treatment before destroying. The default functions will do the right thing.

    I am not sure about the default destructor since there is a pointer involved.

    You only need a destructor in the presence of a pointer if that pointer points to some resource that you need to clean up manually; for example, if you allocated something with new. In which case, you probably don't want a pointer at all, but a smart pointer, container, or other RAII object rather than juggling a pointer and hoping you don't drop it.