Can static member function of base class call its derived class object? (C++)
Can sta开发者_StackOverflowtic member function of base class call its derived class object?
Think of static
member-function as some non-member function. So yes. Whatever non-member function can do, static
member-function can do the very same thing!
Yes, though there are two things to watch out for.
The first is forward-references. If the code to your static method is in the .cpp
file, you should be able to safely #include the base and derived class headers.
<Base.h>
class Base
{
protected:
Base();
public:
virtual ~Base();
static Base* Create();
};
<Derived.h>
#include "Base.h"
class Derived : public Base
{
public:
Derived(int aParameterGoesHere);
};
<Base.cpp>
#include "Base.h"
#include "Derived.h"
Base::Base() { }
Base::~Base() { }
Base* Base::Create()
{
return new Derived(42);
}
The second thing to watch for is that private/protected members of Derived
are not accessible from Base
unless they were declared as virtual members of Base
or Base
is declared a friend class of Derived
(which is not unreasonable, considering the tight coupling):
<Derived.h>
#include "Base.h"
class Derived : public Base
{
friend Base;
private:
Derived(int aParameterGoesHere);
};
No, it can not call, because a static member function has no object assigned to it, therefore it has no its derived class object.
However, it is possible if you are using CRTP, like this :
template< T >
struct base
{
base()
{
T::foo(); // here calling a static method of derived class
}
virtual ~base(){}
};
struct A : base< A >
{
virtual ~A(){}
static void foo()
{
// do stuff
}
};
精彩评论