c++ private function in namespace code example

Example 1: private and public in namespace cpp

// thing.cpp

namespace thing
{
    namespace   // anonymous namespace
    {
        int x = 1;
        int y = 2;

        int sum(int a, int b)
        {
            return a + b;
        }
    }

    int getX() 
    {
        return x;
    }

    int getSum()
    {
        return sum(x, y);
    }
};

Example 2: private and public in namespace cpp

#include <cstdio>
#include "thing.hpp"

int main(int argc, char **argv)
{
    printf("%d\n", thing::getX());     // OK
    printf("%d\n", thing::getSum());   // OK
    printf("%d\n", thing::sum(1, 2));  // error: ‘sum‘ is not a member of ‘thing’    
    printf("%d\n", thing::y);          // error: ‘y‘ is not a member of ‘thing’    
}

Tags:

Cpp Example