Reputation: 1789
I'm trying to define a function which returns a pointer to a structure
#include <iostream>
using namespace std;
class abc
{
private:
struct n
{
int data;
};
public:
n* print();
};
n* abc::print()
{
n* q = new n;
q->data = 7;
return q;
}
When this program is compiled "identifier n is undefined" error is shown. Why does the program compile successfully when the same function abc is defined inside the class ?
Upvotes: 1
Views: 58
Reputation: 21576
n
is a nested class. You need to qualify it with abc::n
.
Note: The name and scope of a class is also a namespace
, since n
is nested in abc
, abc
is now like the namespace
of n
.
Full example:
#include <iostream>
using namespace std;
class abc
{
private:
struct n
{
int data;
};
public:
n* print();
};
abc::n* abc::print()
{
abc::n* q = new abc::n;
q->data = 7;
return q;
}
Upvotes: 5
Reputation: 409196
Outside of the class there is no n
symbol, so you need to fully qualify it like abc::n
.
Upvotes: 1
Reputation: 3365
Because the returned n, when defined outside the class, has a different scope. You can fix this by prefixing it with the correct scope:
abc::n* abc::print()
{
n* q = new node;
q->data = 7;
return q;
}
Upvotes: 1