Estefunny
Estefunny

Reputation: 43

Call non-static method from base class in static create method

I want to write a static create method, where I call a non-static method from the base class.

<BaseClass.h>

class BaseClass
{
public:
    void method();
}

<MyClass.h>

class MyClass : public BaseClass
{
    static MyClass* createMyClass();
}

<MyClass.cpp>

...
MyClass* MyClass::createMyClass()
{
    MyClass* myclass = new MyClass();
    method(); // Error, illegal call of non-static member function
    return myclass;
}
...

So do I have to call my base class method outside of my createMyClass method, or is there any possible way to call it inside?

Upvotes: 1

Views: 810

Answers (1)

cdhowie
cdhowie

Reputation: 168988

Non-static methods need to be invoked on an instance, and the compiler doesn't pretend to be smart enough to know which instance you want to invoke it on (unless you are in an instance method). You need to explicitly invoke the method on the instance of MyClass you just created:

myclass->method();

(Another way of thinking about it: in non-static context, calling a method using the syntax method(); is equivalent to this->method();. Since you don't have a "this" due to being in static context, you need to supply the "this" yourself.)

Upvotes: 7

Related Questions