🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.windows.interviews
Article #330

Re: Simple Member Function Question

#330
From: juando
Date: Wed, 15 Apr 1992 11:38
68 lines
2210 bytes
>X-Envelope-to: interviews@interviews.stanford.edu, luj@sanandreas.ecn.purdue.edu

luj@sanandreas.ecn.purdue.edu (John Lu) writes
>
>I saw following in IV's code. 
>
>class Bar { /* ... */ };
>class Foo {
>public:
>    const Bar& func() const { return bar_; }
>    Bar& func() { return bar_; }
>private:
>    Bar bar_;
>};
>
>It seems to me that only the 2nd member function is enough. What's 
>rationale for having two member functions ? (guess that I still to work
>harder on my C++)
>
>Thanks,

I think a small example will explain it:

Foo a_regular_foo;
const Foo a_constant_foo;
Bar a_regular_bar;

// Initialization code or whatever.

// Foo::func() returns a reference to bar, so we could assign to it.

a_regular_bar = a_regular_foo.func(); // OK

a_regular_bar = a_constant_foo.func() // OK as long as Bar::operator=() is
				      // defined:
				      //   Bar::operator=(const &Bar)
				      //                  ^^^^^

a_regular_foo.func() = a_regular_bar; // OK: assignment to a non constant
				      // object.

a_constant_foo.func() = a_regular_bar; // Error: Assignment to constant
				       // object.

In general a call to Foo:func() will return const Bar & if the object for which
it is called is constant. This guarantees that a constant Foo is not altered by
getting its Bar and then modifying it.

Hope it helps,

Juan

------------------------------------------------------------------------

    Juan D. Martin 				(juando@cnm.us.es)

    Centro Nacional de Microelectronica
    Edificio C.I.C.A.
    Av/ Reina Mercedes s/n

					41012-SEVILLA

					    SPAIN

    Phone: 34-5-4623811
    Fax:   34-5-4624506

------------------------------------------------------------------------
Technical Details
Message-ID: <9204150955.AA29239@sparc1.cnm.us.es>
Path: arc1-ca.pugleaf.net!sparky!uunet!stanford.edu!cnm.us.es!juando

Show Full Headers
Complete Article Headers
Newsgroups: comp.windows.interviews
Path: arc1-ca.pugleaf.net!sparky!uunet!stanford.edu!cnm.us.es!juando
From: juando@cnm.us.es
Subject: Re: Simple Member Function Question
Message-ID: <9204150955.AA29239@sparc1.cnm.us.es>
X-Unparsable-Date: Wed, 15 Apr 1992 11: 55:09 UTC+0100
Sender: news@shelby.stanford.edu (USENET News System)
Organization: Internet-USENET Gateway at Stanford University
Date: Wed, 15 Apr 1992 11:38:02 GMT
Lines: 69