Click to See Complete Forum and Search --> : calling non-static methods statically
ireland
March 15th, 2005, 08:36 AM
Why is it possible to call a non-static method with static syntax , is it only for inherited classes ?
Base::func() //virtual function
{
..
}
Derived:func() //Base is the parent
{
if(//something)
//do something
else
Base::func(); //call the base class version
}
Hobson
March 15th, 2005, 08:41 AM
Calling is NOT static. Derrived class has 2 versions of func(): its own, and from base class, but hidden, overriden. When you write Base::func() in derrived class, its same as this->(Base::func()) call, which calls overriden method, and invisible without using scope operator.
Hope made it clear
Hob
ireland
March 15th, 2005, 08:48 AM
Thanks.
So it's only allowed within inherited classes or could it be used with non-related classes (maybe if forward declaration were used) ?
class ClassC; //forward declaration
ClassA::func()
{
ClassC::somefunc(); //not related
}
Hobson
March 15th, 2005, 09:02 AM
in this way ClassC::somefunc() should be declared as static. In 'unrelated' way it is possible to do like:
class Base
{
public:
int func();
}
class Derived: public Base
{
public:
int func();
}
class Unrelated
{
int somefunc()
{
Derived obj;
return obj.(Base::func());
}
}
As you see, it is NOT static, because function has to be called for some object ('obj' in this example). In your first example the object for which the function was called is pointed by 'this', and its possible because derrived class contains object of its base class. In your second example, ClassC::somefunc() is not called for any object, even for 'this', since 'this' cannot point to object of unrelated class ClassC.
Quite complicated
cilu
March 15th, 2005, 09:19 AM
I think you are actually confused by the scope operator :: .
class base
{
public:
void foo() { cout << "base foo" << end; } // not-virtual
virtual void goo() {cout << "base goo " << endl; } // virtual
static void moo() { cout << "base moo" << endl; }
};
class derived : public base
{
public:
void goo()
{
base::goo();
// :: is used to indicate that the goo function called is the one
// from the base class; otherwise you get an infinite recursion
// becase goo from derived will be called
cout << "derived goo " << endl;
}
static void moo2() { cout << "derived moo2" << endl; }
void hoo()
{
base::moo(); // calls moo from base, which is static
}
};
int main()
{
base::moo(); // OK, call static moo from base
derived::moo2(); // ok, call static moo2 from derived
base::foo(); // WRONG, foo is not static
base b;
b.foo(); // ok
b.goo(); // ok prints "base goo"
derived d;
d.goo(); // ok, calls goo from derived, prints "base goo" followed by "derived goo"
d.base::goo(); // ok, calls goo from base, prints "base goo"
d.moo2(); // ok
d::moo2(); // wrong, d is not a namespace or class
return 0;
}
Hope this helps you.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.