0
votes

I have created a class inside a namespace now the problem occurs when i would have to use or call the namespace, What could be the possible reason for compiler error ??

namespace name1    
{   
        class show   
    {   
        int a,b;   
        void accept_data(void);   
        void display_data(void);   
        friend void use_class(void);  
    };  
}

Compiler Errors -

test1.cpp: In function ‘void use_class()’:
test1.cpp:17:6: error: ‘void name1::show::accept_data()’ is private
test1.cpp:31:16: error: within this context
test1.cpp:24:6: error: ‘void name1::show::display_data()’ is private
test1.cpp:32:17: error: within this context

2
Where is use_class declared?pmr
It is declared outside namespaceDeepak Yadav
you need to tell us what the compiler error isScott Langham
If I remove the namespace then the same program runs very easilyDeepak Yadav

2 Answers

3
votes

When you declare a friend function using an unqualified identifier (like use_class), that declaration always names a member of the nearest enclosing namespace of the class in which the declaration appears. A previous declaration of the function does not have to be visible. This means that your declaration declares a function void ::name1::use_class() to be a friend of the class ::name1::show.

If you want to declare a friend from a different namespace, you must use a qualified id.

E.g.

friend void ::use_class();

Note that unlike the unqualified case, a previous declaration of the function being befriended must be visible. e.g.

void use_class();
namespace name1 {
    class show {
    //...
    friend void ::use_class();
    //...
    };
}
0
votes

You can have this:

namespace name1    
{   
        class show   
    {   
        int a,b;   
        void accept_data(void);   
        void display_data(void);   
        friend void use_class(show&);  
    };  
}

void name1::use_class(name1::show& h)
{
h.a = 1;
h.b = 2;
}

and in main:

name1::show s;

name1::use_class(s);

I am not sure why your functions have void parameters and return values though.

UPDATE:

this compiles and works:

#include "stdafx.h"

namespace name1    
{   
        class show   
    {   
        int a,b;   
        void accept_data(void);   
        void display_data(void);   
        friend void use_class();  
    };  
}

void name1::show::accept_data()
{
    a = 1;
    b = 2;
}

void name1::show::display_data()
{
}

void name1::use_class()
{
    show s;

    s.accept_data();
    s.display_data();
}

int _tmain(int argc, _TCHAR* argv[])
{
    name1::use_class();

    return 0;
}

But, if I write it like this:

void use_class()
{
    name1::show s;

    s.accept_data();
    s.display_data();
}

I get your error. Make sure your use_class is part of same namespace.