473,748 Members | 11,145 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner's Question: Assignment of Objects with a constant data member possible?

It seems to me that I cannot assign objects of a class which has a constant data
member since the data member cannot be changed once the constructor calls are
completed. Is this the way it is meant to be? Am I not suppose not to have any
constant data member if I am going to have the assignment operator working for
the class?

Or am I missing something here and there is something I need to learn about?

Clear, easy to understand explanation would be very much appreciated as I am
just beginning to learn C++ features. Thank you in advance!
Jul 19 '05 #1
5 4832
"CoolPint" <co******@yahoo .co.uk> wrote...
It seems to me that I cannot assign objects of a class which has a constant data member since the data member cannot be changed once the constructor calls are completed. Is this the way it is meant to be? Am I not suppose not to have any constant data member if I am going to have the assignment operator working for the class?

Or am I missing something here and there is something I need to learn about?
You can write your own assignment operator and do whatever you think
is appropriate. I guess you need to learn about operator overloading.
Clear, easy to understand explanation would be very much appreciated as I am just beginning to learn C++ features. Thank you in advance!


What book are you reading? Does it have a chapter on operators? Does
it talk about operator overloading for your custom types? If not,
discard it and find a better one.

class HasConstData
{
int const a;
int b;
public:
HasConstData(in t b) : a(42), b(b) {}
HasConstData& operator=(HasCo nstData const& r)
{
b = r.b;
return *this;
}
};

int main()
{
HasConstData hcd1(1), hcd2(2);
hcd1 = hcd2;
}

Victor
Jul 19 '05 #2
CoolPint wrote:
It seems to me that I cannot assign objects of a class which has a constant data
member since the data member cannot be changed once the constructor calls are
completed. Is this the way it is meant to be? Am I not suppose not to have any
constant data member if I am going to have the assignment operator working for
the class?

Or am I missing something here and there is something I need to learn about?

Clear, easy to understand explanation would be very much appreciated as I am
just beginning to learn C++ features. Thank you in advance!


You need to explicitly write the assignment operator and copy
constructor methods for your class.

<example>
class X {
private:
int a_;
const int b_;
public:
// ctor
X(int a, int b) : a_(a), b_(b) { }
// copy ctor
X(const X& x) : a_(x.a_), b_(x.b_) { }
// assignment
X & operator=(const X& x) {
a_ = x.a_;
return *this;
}
};

int main()
{
X x1(1,2), x2(3,4);
X x3(x1); // copy ctor
// x3.{a_==1, b_==2}

// x2.{a_==3, b_==4}
x2 = x3; // assignment
// x2.{a_==1, b_==4}
}
</example>

--
Jim

To reply by email, remove "link" and change "now.here" to "yahoo"
jfischer_link58 09{at}now.here. com
Jul 19 '05 #3
"CoolPint" <co******@yahoo .co.uk> wrote in message
news:15******** *************** ***@posting.goo gle.com...
It seems to me that I cannot assign objects of a class which has a
constant data member since the data member cannot be changed once the
constructor calls are completed. Is this the way it is meant to be? Am I
not suppose not to have any constant data member if I am going to have the
assignment operator working for the class?

Or am I missing something here and there is something I need to learn
about?


You mean, you have a class like this

class Foo
{
const int unchangeableVal ue;
int changeableValue ;
public:
Foo (int, int);
};

Foo::Foo (int value1, int value2) :
unchangeableVal ue(value1), changeableValue (value2)
{
}

and you're trying to do an assignment like this?

Foo foo1(1, 2);
Foo foo2(3, 4);
foo1 = foo2;

This is called "copy assignment," because both objects in the assignment are
of the same type. The default method used for copy assignment is called
"memberwise copy." In this method, each member of one object is simply
assigned to the corresponding member of the other object. So this statement

foo1 = foo2;

leads to code that assigns foo2.unchangeab leValue to foo1.unchangeab leValue,
and assigns foo2.changeable Value to foo1.changeable Value. The problem, of
course, is that you can't assign foo2.unchangeab leValue to
foo1.unchangeab leValue, because unchangeableVal ue is defined to be const.

One solution would be to define unchangeableVal ue to be non-const. But that
may not be what you want.

Another solution might be to define unchangeableVal ue as a static member of
Foo. Static members aren't involved in copy assignment. But the side
effect would be that every instance of Foo would have the same
unchangeableVal ue. This may or may not be acceptable to you.

Another solution would be to "overload" the copy assignment operator for
Foo. In other words, substitute your own copy-assignment operation for the
default memberwise-copy operation.

You overload the assignment operator by adding a new member function to Foo.
The name of this function is "operator=" :

class Foo
{
int const unchangeableVal ue;
int changeableValue ;
public:
Foo (int, int);
Foo &operator= (Foo const &);
};

// constructor
Foo::Foo (int value1, int value2) :
unchangeableVal ue(value1), changeableValue (value2)
{
}

// copy assignment
Foo &Foo::operat or= (Foo const &other)
{
// we're ignoring unchangeableVal ue
changeableValue = other.changeabl eValue;
return *this;
}

Now this statement

foo1 = foo2;

leads to this function call:

foo1.operator=( foo2);

Since operator= doesn't attempt to assign to unchangeableVal ue, it's legal.

Hope that helps. Let us know if you have further questions.

Regards,

Russell Hanneken
rh*******@pobox .com
Jul 19 '05 #4
Thank you Russell. You clearly explained what I was asking about.
While I was pondering with the situation, I came up with similar
solutions to yours including overloaded assignment operator which
doesn't assign the constant variable.

So is this the feature of the language which is meant to be like this?
I see that alternative solutions can be formed but what I am trying to
learn here the features of the language and possible situations where
the features can be useful. With regard to assignment of objects with
a constant data member,
I guess that's how it is designed to be.

For example,
class Person {
const unsigned reg_number;
char *name;
Date birthday;
};

If the application requires the registration number to be set just
once and to be made constant after that, the assignment operator
should not be allowed, I guess and the feature seems to make sense...

"Russell Hanneken" <rh*******@pobo x.com> wrote in message news:<n_******* *********@newsr ead4.news.pas.e arthlink.net>.. .
"CoolPint" <co******@yahoo .co.uk> wrote in message
news:15******** *************** ***@posting.goo gle.com...
It seems to me that I cannot assign objects of a class which has a
constant data member since the data member cannot be changed once the
constructor calls are completed. Is this the way it is meant to be? Am I
not suppose not to have any constant data member if I am going to have the
assignment operator working for the class?

Or am I missing something here and there is something I need to learn
about?


You mean, you have a class like this

class Foo
{
const int unchangeableVal ue;
int changeableValue ;
public:
Foo (int, int);
};

Foo::Foo (int value1, int value2) :
unchangeableVal ue(value1), changeableValue (value2)
{
}

and you're trying to do an assignment like this?

Foo foo1(1, 2);
Foo foo2(3, 4);
foo1 = foo2;

This is called "copy assignment," because both objects in the assignment are
of the same type. The default method used for copy assignment is called
"memberwise copy." In this method, each member of one object is simply
assigned to the corresponding member of the other object. So this statement

foo1 = foo2;

leads to code that assigns foo2.unchangeab leValue to foo1.unchangeab leValue,
and assigns foo2.changeable Value to foo1.changeable Value. The problem, of
course, is that you can't assign foo2.unchangeab leValue to
foo1.unchangeab leValue, because unchangeableVal ue is defined to be const.

One solution would be to define unchangeableVal ue to be non-const. But that
may not be what you want.

Another solution might be to define unchangeableVal ue as a static member of
Foo. Static members aren't involved in copy assignment. But the side
effect would be that every instance of Foo would have the same
unchangeableVal ue. This may or may not be acceptable to you.

Another solution would be to "overload" the copy assignment operator for
Foo. In other words, substitute your own copy-assignment operation for the
default memberwise-copy operation.

You overload the assignment operator by adding a new member function to Foo.
The name of this function is "operator=" :

class Foo
{
int const unchangeableVal ue;
int changeableValue ;
public:
Foo (int, int);
Foo &operator= (Foo const &);
};

// constructor
Foo::Foo (int value1, int value2) :
unchangeableVal ue(value1), changeableValue (value2)
{
}

// copy assignment
Foo &Foo::operat or= (Foo const &other)
{
// we're ignoring unchangeableVal ue
changeableValue = other.changeabl eValue;
return *this;
}

Now this statement

foo1 = foo2;

leads to this function call:

foo1.operator=( foo2);

Since operator= doesn't attempt to assign to unchangeableVal ue, it's legal.

Hope that helps. Let us know if you have further questions.

Regards,

Russell Hanneken
rh*******@pobox .com

Jul 19 '05 #5
CoolPint writes:
It seems to me that I cannot assign objects of a class which has a constant data member since the data member cannot be changed once the constructor calls are completed. Is this the way it is meant to be? Am I not suppose not to have any constant data member if I am going to have the assignment operator working for the class?

Or am I missing something here and there is something I need to learn about?
Clear, easy to understand explanation would be very much appreciated as I am just beginning to learn C++ features. Thank you in advance!


Based on the amount of time that has elapsed since you made your post, I
think most others are in the same boat I am, they don't understand your
question. How about posting some code that illustrates your
problem/concern/misapprehension ?
Jul 19 '05 #6

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

Similar topics

16
2616
by: Edward Diener | last post by:
Is there a way to override the default processing of the assignment operator for one's own __value types ? I realize I can program my own Assign method, and provide that for end-users of my class, but I would like to use internally my own = operator for some of my value types, so I can say "x = y;" rather than "x.Assign(y);". The op_Assign operator seems impossibly broken since it takes __value copies of the two objects. Perhaps there is...
15
1929
by: PhilB | last post by:
Hello experts, I am a complete beginner in C++ (although I know C). I am trying to compile the code below, and I get the following error. Can anyone explain to me my mistake? Thanks! PhilB myprog2.cpp: In method `Line::Line (Point, Point)': myprog2.cpp:32: no matching function for call to `Point::Point ()'
8
2833
by: john smith | last post by:
I have a question about the best way to use constants in C++. There seem to be variations in the way that they are used, and I am confused as to what I should be using. Basically since the constant is used in only one class, should I try to scope it to just that class? to the file? what are the thoughts out there. 1.) I have seen people declare in their .h file
10
1832
by: chresan | last post by:
Hello, I have a question about polymorphism in c++. I have much experience in other programming languages, but not very much in c++. I found an unexpected behavior in following code #include <iostream> using namespace std; class Abstract
6
13382
by: Neil Zanella | last post by:
Hello, I would like to know whether the following C fragment is legal in standard C and behaves as intended under conforming implementations... union foo { char c; double d; };
25
2578
by: tsaar2003 | last post by:
Hi Pythonians, To begin with I'd like to apologize that I am not very experienced Python programmer so please forgive me if the following text does not make any sense. I have been missing constants in Python language. There are some workarounds available, for example the const-module. To me, this looks quite cumbersome and very unintuitive. For the interpreter, in the efficiency-wise, I just cannot tell.
20
4040
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
12
6251
by: hweekuan | last post by:
hi, it seems i can't assign the const variable u in class A, one way to solve the problem may be to build a copy constructor. however, why does C++ or vector class not like this code? my g++ is: gcc version 4.0.1 (Apple Inc. build 5465). thanks for the help. summary of compile error: --------------------------------------- cpp.C:4: error: non-static const member 'const unsigned int A::u',
17
2324
by: Ben Bacarisse | last post by:
candide <toto@free.frwrites: These two statements are very different. The first one is just wrong and I am pretty sure you did not mean to suggest that. There is no object in C that is the same as its address. The second one simply depends on a term that is not well-defined. Most people consider the type to be an important part of the notion of
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
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
9367
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
9319
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,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6795
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
6073
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
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2780
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.