473,782 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assigning to references

Hello all,

Please consider the code below. It is representative of a problem I am
having.

foo_t needs to contain a bar_t which is a class without a copy constructor
or operator=. It is not within my control to change bar_t. Furthermore, I
need to be able to update the contained bar_t at runtime (hence the
set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference? I only
want my reference member to refer to a new object; I'm not actually copying
an object. Why should operator= come into play? After all, I can pass a
reference to bar_t as a parameter just fine even though the copy constructor
is also inaccessible.

Assuming though that my compiler is behaving properly, I won't be able to
take this approach regardless of whether or not I understand why it's
disallowed. With that in mind, what's my next best alternative to create an
effect similar to what the code below attempts?

Thanks!
Dave

P.S. In case anyone is tempted to ask "What are you trying to do?", bar_t
corresponds to ofstream and foo_t corresponds to one of my application
classes. I need to contain an ofstream for logging, and I need to be able
to change that stream occassionally (i.e. start logging to a different
place).

class bar_t
{
public:
bar_t() {}

private:
bar_t(const bar_t &); // Leave undefined
bar_t &operator=(cons t bar_t &); // Leave undefined
};

class foo_t
{
public:
foo_t(): bar(initial_bar ) {}
void set_bar(bar_t &b) {bar = b;}

private:
bar_t initial_bar; // Must come *before* member bar as it is used to
initialize bar.
bar_t &bar;
};

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #1
37 3976
> Please consider the code below. It is representative of a problem I
am
having.

foo_t needs to contain a bar_t which is a class without a copy constructor or operator=. It is not within my control to change bar_t. Furthermore, I need to be able to update the contained bar_t at runtime (hence the
set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why should this be a problem since I'm trying to assign to a reference? I only want my reference member to refer to a new object; I'm not actually copying an object. Why should operator= come into play? After all, I can pass a reference to bar_t as a parameter just fine even though the copy constructor is also inaccessible.
I think the error message put you on the wrong track. The compiler isn't
complaining about the assignment operator of the bar_t class. The real
problem is that C++ references in C++ are not assignable. They must
always be initialized and cannot be reseated later.
Assuming though that my compiler is behaving properly, I won't be able to take this approach regardless of whether or not I understand why it's
disallowed. With that in mind, what's my next best alternative to create an effect similar to what the code below attempts?


If you need the bar member to reference another object at some point in
your program, the bar member must be a pointer.

[comp.lang.c++.m oderated cross-post removed since it slows down
responses]

--
Peter van Merkerk
peter.van.merke rk(at)dse.nl


Jul 19 '05 #2

Dave wrote:
Hello all, foo_t needs to contain a bar_t which is a class without a copy constructor
or operator=.

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference? I only
want my reference member to refer to a new object; I'm not actually copying
an object. Why should operator= come into play? After all, I can pass a
reference to bar_t as a parameter just fine even though the copy constructor
is also inaccessible.
You cannot do that in C++; a reference always refers to the object with
which it is initialized.
With that in mind, what's my next best alternative to create an
effect similar to what the code below attempts?


Pointers can be reassigned to refer to different objects.

HTH,
Jack
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #3

"Dave" <be***********@ yahoo.com> wrote in message
news:vq******** ****@news.super news.com...
Hello all,

Please consider the code below. It is representative of a problem I am
having.

foo_t needs to contain a bar_t which is a class without a copy constructor
or operator=. It is not within my control to change bar_t. Furthermore, I need to be able to update the contained bar_t at runtime (hence the
set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference?


not much analisys done but one thought:
references are *NOT* pointers. a reference is an alias (if you want) or a
different name for a variable. you initialise it and use it like any other
variable (use . not -> to call methods). The compiler may transform the
reference into a pointer, but this is only an implementation detail. So,
yes, you need an operator=

my 2c

/dan
<snip>

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #4
Dave wrote:
P.S. In case anyone is tempted to ask "What are you trying to do?", bar_t
corresponds to ofstream and foo_t corresponds to one of my application
classes. I need to contain an ofstream for logging, and I need to be able
to change that stream occassionally (i.e. start logging to a different
place).


NOW you're telling us :-)

std::ofstream log("foo", somemode);
.....
log.close();
log.open("bar", somemode);
.....

and in case you're afraid that someone uses your logging class in the mean
time, use two references, one unused, create the new stream and assign to
the unused reference, then assign the previously unused reference to the
previously used reference.
--

Ruurd
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #5
"Dave" <be***********@ yahoo.com> wrote in message
news:vq******** ****@news.super news.com...
Hello all,

Please consider the code below. It is representative of a problem I am
having.

foo_t needs to contain a bar_t which is a class without a copy constructor
or operator=. It is not within my control to change bar_t. Furthermore, I need to be able to update the contained bar_t at runtime (hence the
set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference? [snip]


Because you can't reassign a reference in C++. I have already given you the
answer to this problem twice now in a previous thread.

--
Cycho{HHR}
http://home.rochester.rr.com/cyhome/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #6
Hello Dave,

Dave schrieb:
Hello all,

Please consider the code below. It is representative of a problem I am
having.

foo_t needs to contain a bar_t which is a class without a copy constructor
or operator=. It is not within my control to change bar_t. Furthermore, I
need to be able to update the contained bar_t at runtime (hence the
set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference? I only
want my reference member to refer to a new object; I'm not actually copying
an object. Why should operator= come into play? After all, I can pass a
reference to bar_t as a parameter just fine even though the copy constructor
is also inaccessible.
A reference in C++ is very near what we would name an "alias" of what it is
refering to. After initialization bar **is** the object of type T it was
initialized with,
thus an assignment to it calls the copy assignment operator of T.
References as function parameters behave as a transfer capsule from its actual
argument to the function internal accessor. The call

bar_t bobject;
....
set_bar(bobject );

creates a reference which binds to bobject. This reference is now available
inside
set_bar and no copy operation takes during function entry. This case is
different from

bar_t bobject;
....
bar_t& bref = bobject;

bref = bobject;

where the (non-initialization) assignment effectivly copies bobject into itself.

References as function parameters were quite useless, if they would call the
copy assignment operator of T, because this would make them not different
from "call-by-value".
Assuming though that my compiler is behaving properly, I won't be able to
take this approach regardless of whether or not I understand why it's
disallowed. With that in mind, what's my next best alternative to create an
effect similar to what the code below attempts?


Use a pointer instead of a reference. Pointer do have two states (assigned and
not assigned) and thus can change between states (Reassignment is also allowed).

In many cases a reference is more appropriate than a pointer, because you don't
need to test, whether it is assigned or not: Once initialized it always is
assigned to the
same object!

In your case you want to allow a redirection of the target, you are "refering"
to,
so you need a pointer. This also makes you responsible for checking whether
the given pointer is a null pointer constant (not assigned) or not (assigned).

Hope that helps,

Daniel Spangenberg


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #7
"Dave" <be***********@ yahoo.com> wrote in message news:<vq******* *****@news.supe rnews.com>...
Hello all,

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference? I only


In C++, once a reference is seated, it can not be re-seated. You may
modify the referant, but you may not make it refer to a different
object.

"bar = b" calls operator= on 'bar', passing in 'b'.

It has to be this way. If 'bar=b' re-seated 'bar', how would you call
operator=?

If you want to have a reference and change what it refers to, use a
pointer:

pbar=&b;

*pbar << "hello" << endl;

joshua lehrer
factset research systems
NYSE:FDS

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #8
Hi,

Dave wrote:
The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. class bar_t
{ private: bar_t &operator=(cons t bar_t &); // Leave undefined
That's why.
You cannot assgn to bar_t, because you have explicitly forbid it.
Note that:

- you cannot "reseat" the reference, and
- the reference always denotes some object

so the instruction:

bar = b;

tries to *assign* what is denoted by 'b' to what is denoted by 'bar'. In
other words, the above instruction tries to assign one bar_t object to
another, which is explicitly forbidden.

If you need to achieve the effect of reseating (without the possibility
to assign), consider using pointers instead of references.

I've used pointers recently in exactly the same context (logging ostream
object associated with another object).
class foo_t
{
public:
foo_t(): bar(initial_bar ) {}
void set_bar(bar_t &b) {bar = b;}
bar = &b;
private:
bar_t &bar;
bar_t *bar;
};


--
Maciej Sobczak : http://www.msobczak.com/
Programming : http://www.msobczak.com/prog/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #9
Dave wrote:
foo_t needs to contain a bar_t which is a class without a copy
constructor or operator=. It is not within my control to change
bar_t. Furthermore, I need to be able to update the contained bar_t
at runtime (hence the set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible.
Why should this be a problem since I'm trying to assign to a
reference? I only want my reference member to refer to a new object;
I'm not actually copying an object. Why should operator= come into
play? After all, I can pass a reference to bar_t as a parameter just
fine even though the copy constructor is also inaccessible.


The problem is that references cannot be reassigned. Luckily enough, the
solution is simple: use a pointer.

Gerhard Menzl
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6409
by: gtz669 | last post by:
I have a class which I am using for data stroage. I declare an instance of that class in my main class which is running my java applet. I Iassign it a value in the init () function and it works fine but when I try to do the same assignment later on, it restults in a NullPointerException and I can not figure this out. Could someone please help. Thanks. Here's the code: public class A extends java.applet.Applet
5
3651
by: Dave | last post by:
Hello all, Please consider the code below. It is representative of a problem I am having. foo_t needs to contain a bar_t which is a class without a copy constructor or operator=. It is not within my control to change bar_t. Furthermore, I need to be able to update the contained bar_t at runtime (hence the set_bar() method seen below).
14
74899
by: Eric Bantock | last post by:
Very basic question I'm afraid. Once an array has been declared, is there a less tedious way of assigning values to its members than the following: myarray=8; myarray=3; myarray=4; myarray=0; myarray=0; myarray=1; myarray=8;
8
13722
by: Woody Splawn | last post by:
Lets say I have a winform that is populated with a dataset. The dataset and data table may have several rows in it. Lets say I am looking at the winform and I want to assign a value to a certain column in the associated datatable. Lets say there are 10 rows in the table and I am on row 5, and I want to assign the value to row 5, but I don't know that I am on row 5. Anyway, my method for assigning the value to the field would be: Dim Dt...
20
7012
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
2
2584
by: Bernie Hunt | last post by:
I'm having trouble assigning the reportsource value at run time. I'm running a test setup, one form with only a Crystal Viewer, called cvwMail. My report is called CustomersBasic.rpt and it draws directly from the TradeWinds.MDB test database. If I use Me.cvwMain.ReportSource = "J:\Learning\CMP 214\Crystal Test\CrystalTest \CustomersBasic.rpt to point to the file directly it works.
7
1762
by: Daniel | last post by:
I am baffled. According to the C++ faq lite it is ok to use a reference as an lvalue, and the subscript operator returns a reference. However, when I run this program, it crashes! I will go set up a different compiler and try again while I'm waiting for a reply, but I'm really curious about why this is happening. I'm using the mingw compiler that came with dev-c++ on an up to date Windows 2000 box. Any help would be greatly appreciated,...
8
4547
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I have a large class with a lot of member variables. I also have a function in the class that I would like to change ALL Of the member variables. I am trying to assign "this" to the result, but I always get the error message, "Cannot assign to '<this>' because it is read-only." I've been searching on the Internet, and I notice some C# code is violating this rule. Perhaps their code is wrong.
10
4013
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
9479
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10311
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.