Private data access using friend

J

Jaspreet

I am working on a code which is similar to the following snippet:

#include <iostream>

using namespace std;

class def;

class abc
{
friend class def;
private:
int p;
};

class def
{
public:
void gg()
{
abc a1;
a1.p = 20;
}
};

int main()
{
def d1;
}

I apologise for the cryptic names of the classes. My doubt is how can I
access the private member p of class abc in gg() method of def class.
Friend class can access the private data of the other class but here I
am trying to acess the private data using an object. Is that valid ?
The code compiles fine on VC 6.0. I know VC6.0 is not a compiler one
should be using if he needs to learn C++ but since I am working on
mobile applications, I have to use VC6.0.

Is this a case of a broken compiler ? I do not think so because the
code also compiles fine on Metrowerks Codewarrior which is based on
gcc.

Please let me know.
 
V

Victor Bazarov

Jaspreet said:
I am working on a code which is similar to the following snippet:

#include <iostream>

using namespace std;

class def;

Everything up until here is unnecessary in your particular program. Try
not to include extraneous stuff in your code. It makes it much more
readable.
class abc
{
friend class def;
private:
int p;
};

class def
{
public:
void gg()
{
abc a1;
a1.p = 20;
}
};

int main()
{
def d1;
}

I apologise for the cryptic names of the classes. My doubt is how can I
access the private member p of class abc in gg() method of def class.

Why do you doubt that?
Friend class can access the private data of the other class

That includes anything that is declared private.
> but here I
am trying to acess the private data using an object. Is that valid ?

Of course!
The code compiles fine on VC 6.0. I know VC6.0 is not a compiler one
should be using if he needs to learn C++ but since I am working on
mobile applications, I have to use VC6.0.

For testing your code you can always turn to VC++ v8 Express Edition,
which is free and much closer to the Standard, or to the online compiler
provided by Comeau Computing (www.comeaucomputing.com/tryitout).
Is this a case of a broken compiler ? I do not think so because the
code also compiles fine on Metrowerks Codewarrior which is based on
gcc.

I hope I have.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top