1

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.

vagoberto
  • 2,372
  • 20
  • 30

2 Answers2

0

Default copy constructor calls copy constructor on each member variable so it generates the following code automatically:

Foo::Foo(const Foo& p)
    : PointFun(p.PointFun)
{}

Each destructor (including the default one) automatically calls destructor on each member variable. For raw pointer, that does nothing.

Since your code has nothing dynamically allocated, you just obtain pointers on methods, it will work correctly.

StenSoft
  • 9,369
  • 25
  • 30
0

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.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644