0

Suppose that we have a class

class Abstract {
    Abstract( void );
    virtual ~Abstract( void ) = 0;

    virtual void VirtualFunction( void ) = 0;

    static void CallsVirtual( void ) {
        VirtualFunction();
    }
};
class Concrete : public Abstract {
    Concrete( void ) {}
    ~Concrete( void ){}
    virtual void VirtualFunction( void ) {/* Do virtual function-y stuff */}
};

int main( void ) {
    Concrete _concrete;
    Abstract& _abstractReference = _concrete;

    _abstractReference.callsvirtual();
}

Which virtual member function is invoked when a base class static member function is called through a base class pointer to a derived class?

2 Answers 2

4

Neither. You'll get a compiler error. You can't call non-static methods or access non-static members from a static method.

//...
virtual void VirtualFunction( void ) = 0;

static void CallsVirtual( void ) {
    VirtualFunction();   // Nope!
}
//...
3
  • this is what i expected since static members functions dont have a this pointer Aug 28, 2012 at 16:10
  • 1
    You can access non-static members in a static function. But you'll need an explicit object to do so. Aug 28, 2012 at 16:13
  • so if CallsVirtual took a base class pointer as an argument i guess i could circumvent it e.g. CallsVirtual( Abstract& that ) { that.VirtualFunction; } but that takes away from making it static in the first place =) Aug 28, 2012 at 16:18
0

A non-static member function is invoked by using the this pointer. The this pointer is implicitly passed to each of the member functions.
However, for static member functions the this pointer is not passed at all.Hence you cannot call a non-static member function through a static member function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.