static function definition

S

Senthilvel

Hi all,
I was thinking that all static members(both data members and functions)
should be defined.
I try to use a static function without defining it
1. outside the class - it gives an error and thats is what i expected.
2. inside the class, ie inside another member function, but it compiles.Why
is that??

Does not the compiler need the definition of Init to generate the code for
Foo ???
I looked into the TCPPPL but didn't find an answer...Can somebody kindly
explain where my understanding
goes wrong ???

#include <iostream>

using namespace std;

class A
{
public:
static void Init();
void Foo() { Init(); }
};

int main()
{
A::Init(); --->Gives an error that Init is an unresolved external symbol.
A a;
a.Foo(); ---> Fine,Also gives an error.
return 0;
}


Here is the actual code that started my confusion..


template<class B,class D> class IsDerivedFrom1
{
class No{};

class Yes{ No no[2]; };
public:
static Yes Test(B* pb);
static No Test(...);

public:
enum { Is = sizeof(Test(static_cast<D*>(0))) > sizeof(No) };

};

Is the declaration of Test is enough to resolve the overload in the
initialisation of the
enum value Is ???

Thanks and Best Regards,
Senthilvel.
 
J

John Harrison

Senthilvel said:
Hi all,
I was thinking that all static members(both data members and functions)
should be defined.
I try to use a static function without defining it
1. outside the class - it gives an error and thats is what i expected.
2. inside the class, ie inside another member function, but it compiles.Why
is that??

Does not the compiler need the definition of Init to generate the code for
Foo ???
I looked into the TCPPPL but didn't find an answer...Can somebody kindly
explain where my understanding
goes wrong ???

#include <iostream>

using namespace std;

class A
{
public:
static void Init();
void Foo() { Init(); }
};

int main()
{
A::Init(); --->Gives an error that Init is an unresolved external symbol.
A a;
a.Foo(); ---> Fine,Also gives an error.
return 0;
}


Here is the actual code that started my confusion..


template<class B,class D> class IsDerivedFrom1
{
class No{};

class Yes{ No no[2]; };
public:
static Yes Test(B* pb);
static No Test(...);

public:
enum { Is = sizeof(Test(static_cast<D*>(0))) > sizeof(No) };

};

Is the declaration of Test is enough to resolve the overload in the
initialisation of the
enum value Is ???

Yes it is. If you don't actually call Test, you don't need to define it.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,171
Messages
2,570,935
Members
47,472
Latest member
KarissaBor

Latest Threads

Top