4

Is it possible to define function or method outside class declaration? Such as:

class A 
{
    int foo;
    A (): foo (10) {}
}

int A::bar () 
{
    return foo;
}        
Rakete1111
  • 42,521
  • 11
  • 108
  • 141
ska
  • 47
  • 1
  • 3

3 Answers3

5

It is possible to define but not declare a method outside of the class, similar to how you can prototype functions in C then define them later, ie:

class A 
{
    int foo;
    A (): foo (10) {}
    int bar();
}

// inline only used if function is defined in header
inline int A::bar () { return foo; }   
Vality
  • 6,336
  • 3
  • 25
  • 47
  • @Rakete1111 I think, but I dont remember too well that it is implicit if the body is inside the class declaration, but not if done outside like this (honestly reason enough for me just to declare inlines inside the class normally) – Vality Oct 07 '16 at 16:36
  • 2
    @Rakete1111 No. You'll end up with _multiple definition_ errors, otherwise. – πάντα ῥεῖ Oct 07 '16 at 16:37
3

Yes, but you have to declare it first in the class, then you can define it elsewhere (typically the source file):

// Header file
class A 
{
    int foo = 10;
    int bar(); // Declaration of bar
};

// Source file
int A::bar() // Definition of bar 
{
    return foo;
} 
Rakete1111
  • 42,521
  • 11
  • 108
  • 141
3

You can define a method outside of your class

// A.h
#pragma once
class A 
{
public:
    A (): foo (10) {}
    int bar();
private:
    int foo;
};

// A.cpp
int A::bar () 
{
    return foo;
}

But you cannot declare a method outside of your class. The declaration must at least be within the class, even if the definition comes later. This is a common way to split up the declarations in *.h files and implementations in *.cpp files.

Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
  • 3
    I like this answer a lot, but please dont use pragma once, it encourages people to use non-standard language extensions (assuming it didn't become standard while I wasn't looking in which case disregard this.) – Vality Oct 07 '16 at 16:34
  • 3
    @Vality No it hasn't, but every major compiler implements it, so it is not *that* big of a problem :) – Rakete1111 Oct 07 '16 at 16:35
  • 3
    @Vality Normally I'd agree with you, I almost always prefer being standard compliant. However in the case of `#pragma once` I don't expect any major compiler to ever not support it. http://stackoverflow.com/questions/787533/is-pragma-once-a-safe-include-guard – Cory Kramer Oct 07 '16 at 16:36