Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to store a function pointer of a base class?

The following code gives an compilation error for void b() { m = &A::a; }; stating that A::a() is protected. (Which it is - but that should be no problem)
However the compiler doesn't care when I write B::a(). Even though both mean the same I would prefer A::a() because it states explicitely that a() is defined in A.

So what is the reason why A::a() is forbidden?
EDIT
Maybe someone can find an example that would be problematic if A::a() was allowed in B::b(). If there is such an example, I will mark it as answer to the question.
/EDIT

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>

class A {
protected:
  void a(){ std::cout << "A::a()" << std::endl; };
};

typedef void (A::*f)();
class B : public A {
public:
  void b() { m = &A::a; }; // wont compile
  // void b() { m = &B::a; }; // works fine
  void c() { (this->*m)(); };
protected:
  f m;
};

int main(){
  B b;
  b.b();
  b.c();
}

// compile with
// g++ -Wall main.cpp -o main

Explanation of the code:
In B I want to store a function pointer to a method in A to be able to call that later in B::c(). And yes, this happens in real life too. :-)

like image 384
Pascal Avatar asked Feb 22 '10 12:02

Pascal


People also ask

Why can't a derived pointer reference a base object?

similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.

What can hold the address of a pointer to the base class A base class?

By default base class pointer can hold the address of base class as well as derived call we all know. But if we don't use virtual keyword in base class then the base class pointer will call methods based on the type of pointer not on based on the value it holding.

Can a base class have pointer objects?

Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.

Is derived class pointer Cannot point to base class?

The actual reason is - a derived class has all information about a base class and also some extra bit of information. Now a pointer to a derived class will require more space and that is not sufficient in base class. So the a pointer to a derived class cannot point to it.


1 Answers

Because otherwise the outside world can find this protected member: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11174.

See also http://gcc.gnu.org/ml/gcc-patches/2004-06/msg00610.html.

like image 54
kennytm Avatar answered Oct 25 '22 08:10

kennytm