From 8810989191264337546
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f78e5,ae9b53b574601927
X-Google-Attributes: gidf78e5,public
From: abell@atl.mindspring.com (Andrew C. Bell)
Subject: Re: friend operator and the this pointer
Date: 1996/10/21
Message-ID: <32683f48.1804638@news.atl.mindspring.com>#1/1
X-Deja-AN: 191201348
references: <3265ACC9.590D@mailhost.netrunner.net>
x-original-date: Sat, 19 Oct 1996 02:55:39 GMT
x-server-date: 19 Oct 1996 02:53:28 GMT
organization: MindSpring Enterprises
x-auth: PGPMoose V1.1 PGP comp.std.c++
newsgroups: comp.std.c++
originator: austern@isolde.mti.sgi.com


Fabio Ortiz <jfabio@mailhost.netrunner.net> wrote:
>Hi, I have the following:
> class A { [...] };
>class B: public A
>{
>	 [...]
>	virtual void display( ostream& o)
>	{
>		o << (A*) this;
>		o << myValue;
>	}

You don't want to display a pointer to A; replace the first line of
the function with
	o << (A &) *this;
Also, display should *not* be virtual; otherwise, when you "fix" what
you have here, the C << operator calls display on a B, which because
it's virtual, calls C::display(..), which starts the loop all over
again.

>this code only displays the parameter value. It do not call the other
>operators << for some reason. Is There any thing wrong with the cast.

You left out enough, and enough was wrong, that this cannot have been
a straight copy of your source.  Without that I cannot tell you what
exactly caused the results you got.

>Friend functions are not inherited does this mean that I can not call
>them through the this pointer using the cast?.

Even a temporary created by casting has all "rights and privileges" of
that class, including friend relationships.  (If it did not, you would
get a compiler error anyway, not a replacement of the function call
with a no-op.)

>Does it make sense to make a private method virtual, it can not be
>called from the derived functions

Well, in this case it definitely didn't (just take out all your
virtuals.)  However, access control is relevant only for "direct" use.

For example:

class A { private: virtual void Foo() {} public: void Goo() { Foo(); }
};
class B : public A { public: virtual void Foo() {} };

void Bar(B *b)
{
	b->Foo(); // legal
	A *a = b;
	a->Foo(); // compiler error -- cannot access private member
	a->Goo(); // legal -- will call B::Foo() if b truly pointed to
// a B 
}

"private" does not hide the names, it just restricts the access.

Results all verified with MSVC++ 4.2.

Andrew Bell
abell@mindspring.com andrewb@graphsoft.com
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your 
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu 
]



