Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

definition of static class function outside of class definition

Tags:

c++

Consider the followin simple class definition -

    // file A.h
#include <iostream>
class A {
public:
  static int f();
  static const int aa;
};


    // file A.cpp
#include "a.h"
using namespace std;
const   int A::aa = 10;
int A::f() {
    return A::aa;
}

And this is my main file -

    // main.cpp file
#include "a.h"
#include "b.h"
using namespace std;
const int A::aa = 100;
int A::f();
int main() {
    cout << A::aa << "\n";
    cout << A::f() << "\n";
}

When I try to compile main.cpp, the compiler complains that the declaration of A::f() in main.cpp outside the class is a declaration, not a definition. Why is this? I do not intend to define A::f() in main.cpp. It is defined in A.cpp and the linker should link the declaration of A::f() in main.cpp with its definition in A.cpp. So I do not understand why am I getting this error. Note this is a compilation error.

like image 414
user236215 Avatar asked Feb 28 '12 01:02

user236215


People also ask

How do you define a static function outside the class?

So you'd use static (or, alternatively, an unnamed namespace) when writing a function that's only intended for use within this unit; the internal linkage means that other units can define different functions with the same name without causing naming conflicts.

Is it possible to define a static member outside the class?

According to Static data members on the IBM C++ knowledge center: The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.

Why static methods should be defined outside the class?

A static method without a class does not make any sense at all. The static keywords signals that this method is identical for all instances of the class. This enables you to call it.. well.. statically on the class itself instead of on one of its instances.

Why define a function outside a class?

Defining a member function outside a class allows to separate the interface and its realization.


2 Answers

C++11 standard §9.3 [class.mftc] p3:

[...] Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.

Aside from that, you'll get a linker error due to multiple definitions of A::aa, but it seems that you expected that, judging from your last sentence.

like image 107
Xeo Avatar answered Sep 22 '22 13:09

Xeo


The class and it's members are already defined, you just have to include the file into your main (which you've done). You do not need to declare or redefine it.

like image 33
Nick Rolando Avatar answered Sep 20 '22 13:09

Nick Rolando