简体   繁体   中英

Member function definition outside of class

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;
}        

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; }   

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;
} 

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.

/* Yes we can declare a method/function inside the class and can define it outside the class with using Class name with scope resoultion operator before it like. */

class Calculator{
    int num1,num2;
public:
    void setData(int x, int y){
        num1 = x; num2 = y;
    }
    //Declaration of sum function inside the class
    int sum();
};
// Definition of sum function outside the class
int Calculator::sum(){
    return num1+num2;
}

/* I want to extend this question : So why we define member function outside the class. What is the point to define it outside the class. If we declare it inside the class. Is it going to make any difference. */

Yes, it is possible to define a member function out side the class. There are 2 ways to define member function.

We can define inside the class definition Define outside the class definition using the scope operator.

To define a member function outside the class definition we have to use the

scope resolution:: operator along with the class name and function name. For more you can read the best example with explanation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM