473,721 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on Constant Variables

Hi,

I have a question on constant variables. In the following code
snippet, I have a function assign() that takes in an iterator to the
private variable v, the number of stuff to assign (int n), and the
information to assign (a const pointer to a class object
Vector<TYPE>.

According to the arrow below, I put a const keyword in the function.
To my knowledge, this means that all private variables in this object
cannot be changed. however, the iterator to the private variable v is
not constant.

Can somebody explain to me why I still can change stuff in the
private variable v??

Thanks in advance

//*************** *************** *************** ***********
// Main Vector Class
template <typename TYPE>
class Vector {
vector<TYPEv;
public:

//*************** *************** *************** ***********
// Constructors and Destructor
Vector() { };
~Vector(){ };
//*************** *************** *************** ***********
// vector container functions
void assign(typename vector<TYPE>::i terator itr, const int& n, const
Vector<TYPE>& val) const { <--
for (int k=0; k<n; k++){
*itr = val[k]; itr++;
}
}

};
Sep 9 '08 #1
8 1665
Since nobody else has answered yet, I'll go ahead and take a stab at
it. My guess is that the compiler has no possible way of knowing when
it compiles "assign" that itr points to a member of this object.
Correct me if I'm wrong, but this is much like:

#include <iostream>

class A
{
public:
int n;
void foo( int& i) const
{
i = 100;
}
};

int main()
{
A a;
a.n = 5;
a.foo( a.n );
std::cout << a.n << std::endl; // Prints out 100
return 0;
}

"foo" isn't really modifying a data member, just some reference it was
passed (which, in this case, just happens to be a data member)
Sep 9 '08 #2
fa********@gmai l.com wrote:
Hi,

I have a question on constant variables.
A constant variable is a contradiction!
In the following code
snippet, I have a function assign() that takes in an iterator to the
private variable v, the number of stuff to assign (int n), and the
information to assign (a const pointer to a class object
Vector<TYPE>.
Where does it do this? Your code only shows the member function assign,
not how it is called.
According to the arrow below, I put a const keyword in the function.
To my knowledge, this means that all private variables in this object
cannot be changed. however, the iterator to the private variable v is
not constant.
Nowhere in the function is v referenced.
Can somebody explain to me why I still can change stuff in the
private variable v??
You don't appear to be.
Thanks in advance

//*************** *************** *************** ***********
// Main Vector Class
template <typename TYPE>
class Vector {
vector<TYPEv;
public:

//*************** *************** *************** ***********
// Constructors and Destructor
Vector() { };
~Vector(){ };
//*************** *************** *************** ***********
// vector container functions
void assign(typename vector<TYPE>::i terator itr, const int& n, const
Vector<TYPE>& val) const { <--
for (int k=0; k<n; k++){
*itr = val[k]; itr++;
}
}

};

--
Ian Collins.
Sep 9 '08 #3
On Sep 9, 9:31 am, Ian Collins <ian-n...@hotmail.co mwrote:
fabian....@gmai l.com wrote:
I have a question on constant variables.
A constant variable is a contradiction!
One man's variables are another man's constants. But I'm pretty
sure he means a const variable, which can be a (compile time)
constant, and is a variable according to the definition of C++;
within the definition of C++ (or most other languages), the word
"variable" has a very special meaning, which has relatively
little to do with the word's more general meaning (and an
invariant that a given variable doesn't vary makes sense).
In the following code snippet, I have a function assign()
that takes in an iterator to the private variable v, the
number of stuff to assign (int n), and the information to
assign (a const pointer to a class object Vector<TYPE>.
Where does it do this? Your code only shows the member
function assign, not how it is called.
According to the arrow below, I put a const keyword in the
function. To my knowledge, this means that all private
variables in this object cannot be changed. however, the
iterator to the private variable v is not constant.
Nowhere in the function is v referenced.
Which doesn't mean that he doesn't access it.
Can somebody explain to me why I still can change stuff in
the private variable v??
You don't appear to be.
But we don't know. He might access it through some other
expression.
//*************** *************** *************** ***********
// Main Vector Class
template <typename TYPE>
class Vector {
vector<TYPEv;
public:
//*************** *************** *************** ***********
// Constructors and Destructor
Vector() { };
~Vector(){ };
//*************** *************** *************** ***********
// vector container functions
void assign(typename vector<TYPE>::i terator itr, const int& n, const
Vector<TYPE>& val) const { <--
for (int k=0; k<n; k++){
*itr = val[k]; itr++;
}
}
};
Just a guess, but I'll bet that his problem is that the iterator
he's passing as an argument refers to v. In which case, he can
modify v. The fact that the function is const doesn't mean that
you can't modify the object; it means that the type of the this
pointer is pointer to const, so lvalue expressions derived from
the this pointer (used explicitly or implicitly) have const
type, and so cannot be used to modify the object without a
const_cast. (The fact that a function is const also means that
you can call it on a const object. If you do so, then any
attempt to modify the object is undefined behavior. But of
course, in this case, he couldn't get a non-const iterator into
the object without a const_cast somewhere along the road
either.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Sep 9 '08 #4
Hi all,

I guess I didnt ask the question properly. Let me try again. Im
writing a vector class that wraps the STL vector container. Im
considering the situation as follows: Lets say a have a vector Y of 3
elements. I want to assign it to elements 1 to 3 in a vector X. Then i
do X(1,3) = Y. So in this case, the operator overload (const int& i,
const int& j) for object X gets called first, and creates (im not sure
if this is the right name) an iterator class object VectorItr<TYPE>
(lets call it Z), and passing the principle argument of X along. Then
in (b), the consturctor for Z uses a member function of X to access
the begin interator of v, which is private in X. It sets vitr to the
begin iterator of v, and exits the constructor. The overload operator
= gets called next, and calls the function assign in question. Assign
is marked in (c). Then my original question follows:

To my knowledge, this means that all private variables in this
object
cannot be changed. however, the iterator to the private variable v is
not constant.

Can somebody explain to me why I still can change stuff in the
private variable v??

Thanks again, sorry for the first time.
//*************** *************** *************** ***********
// VectorIterators Class
// this is a class to manage iterators of the Vector Class
template <typename TYPE>
class VectorItr {
typename vector<TYPE>::i terator vitr;
int n;
public:

//assignments

VectorItr<TYPE> & operator=(const Vector<TYPE>& rhs) {
//using the iterator, populate the Vector<TYPE>
rhs.assign(vitr ,n,rhs);
return *this; //should i return this?
}

//*************** *************** *************** ***********
// Constructors and Destructor
VectorItr() { };
~VectorItr(){ };

VectorItr( Vector<TYPE>& val, const int& i, const int& j) { <------
(b)
//this constructor is used to initialize the beginning of the
//iterator, and the number of elements that need to be assigned
vitr = val.begin()+i; n = j-i+1;
}
};
//*************** *************** *************** ***********
// Main Vector Class
template <typename TYPE>
class Vector {
vector<TYPEv;
public:
VectorItr<TYPEo perator()(const int& i,const int& j)
<-------- (a)
{
return VectorItr<TYPE( *this, i, j);
}

//*************** *************** *************** ***********
// Constructors and Destructor
Vector() { };
~Vector(){ };

//*************** *************** *************** ***********
// vector container functions
void assign(typename vector<TYPE>::i terator itr, const int& n,
const
Vector<TYPE>& val) const { <----- (c)
for (int k=0; k<n; k++){
*itr = val[k]; itr++;
}
}

};
Sep 9 '08 #5
If I understand your question correctly, then this analogy should
help:

class A
{
public:
int n;
A( int i ) : n( i ) {}
void foo( A& a ) const { a.n = n; } //fine to modify another A's n
//void bar() const { n = 100; } //Error: can't modify this->n
};

int main()
{
const A a1(10);
A a2( 20 );
a1.foo( a2 );
std::cout << a2.n << std::endl; // Prints out 10
return 0;
}

Sorry if I have again misunderstood the question. That last post was
really confusing.
Sep 9 '08 #6
fa********@gmai l.com wrote:
>
Can somebody explain to me why I still can change stuff in the
private variable v??
Firstly, speaking informally, the effect of 'const' keyword used to
qualify a class method applies to _all_ data members of the class,
regardless of whether they are private or not. 'Private' has absolutely
nothing to do with the issue in question. Forget about 'private'.

Secondly, what you seem to misunderstand, is that 'const' qualifier in
C++ can be used to qualify an _access_ _path_ to certain object. When
some access path is const-qualified, it means that you can't normally
modify that object through that specific access path. At the same time
it might be perfectly possible to modify the same object using other,
alternative non-const-qualified access paths.

For example, here

int i = 5;
int* p = &i;
const int* pc = &i;

I have a variable 'i' and two access paths to that variable: '*p' and
'*pc'. The latter is const-qualified, meaning that I can't modify 'i'
through that path

*pc = 42; // ERROR

However, I can easily modify 'i' using the former access path

*p = 42; // OK

and now if I check the const-qualified access path, I'll discover that
'*pc' changed to 42.

When you declare some class method as 'const', that only means that you
can't modify the class data through the 'this' pointer. I.e. the access
path provided by '*this' is const-qualified inside the class method. If
inside your 'assign' you try to directly modify 'this->v', you'll get an
error.

void assign(typename vector<TYPE>::i terator itr, const int& n,
const Vector<TYPE>& val) const // <----- (c)
{
this->v[0] = 42; // ERROR
// or simply
v[0] = 42; // ERROR
}

This happens because of your 'const' at point (c).

However, just like I described before, if you have any alternative
non-const-qualified access paths to the inner data of your class,
there's nothing to prevent you from that data it. That's exactly what
happens in your code. An instance of your 'VectorItr' class created by
'Vector::operat or()' is nothing else than an alternative
non-const-qualified access path to the inner data of that 'Vector'
object. You pass that 'VectorItr' instance into the 'Vector::assign '
method and then use it to modify the data

void assign(typename vector<TYPE>::i terator itr, const int& n,
const Vector<TYPE>& val) const // <----- (c)
{
*itr = 42; // OK
}

'const at (c) can't prevent it because it has absolutely nothing to do
with it. You provided 'assign' with a way to circumvent the "protection "
provided by 'const'. It is specifically _you_ who did it, so you really
shouldn't be surprised at all.

--
Best regards,
Andrey Tarasevich
Sep 9 '08 #7
Andrey Tarasevich wrote:
>
However, just like I described before, if you have any alternative
non-const-qualified access paths to the inner data of your class,
there's nothing to prevent you from that data it.
Should be:
However, just like I described before, if you have any alternative
non-const-qualified access paths to the inner data of your class,
there's nothing to prevent you from modifying that data.
--
Best regards,
Andrey Tarasevich
Sep 9 '08 #8
Dear all,

Thank you everybody who replied on this post. I think I resolved my
confusing.

Thanks again.

On Sep 9, 10:32 am, Andrey Tarasevich <andreytarasev. ..@hotmail.com>
wrote:
Andrey Tarasevich wrote:
However, just like I described before, if you have any alternative
non-const-qualified access paths to the inner data of your class,
there's nothing to prevent you from that data it.

Should be:
However, just like I described before, if you have any alternative
non-const-qualified access paths to the inner data of your class,
there's nothing to prevent you from modifying that data.

--
Best regards,
Andrey Tarasevich
Sep 10 '08 #9

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

Similar topics

7
1421
by: Jan Bernatik | last post by:
Hi I have a function called from another one, which runs in loop, so that is it called very often something like this: void my_function(int x) { int temp; temp = x * some_const;
6
12357
by: Prasad | last post by:
Where are the const variables actually stored in memory. I mean If they are stored in data segment(external & static variables)or stack segment(local) how the compiler knows that it is read only memory.
6
1607
by: Alfonso Morra | last post by:
Hi, I have a function declared thus: int foo( int, int ); In the definition, I want to have a variable that is expensive to create. I want to be able to save the state of this variable accross calls - so I declare the var as a static - nothing new here.
3
1269
by: C# Learner | last post by:
Should constant class member variables be held like this: public class Foo { public const int ConstVar = 100; } Or like this: public class Foo
6
1291
by: Simon Harvey | last post by:
Hi, Is there any benefit to declaring variables as constants other than not being able to overwrite them by mistake? Thanks Simon
5
2099
by: Zach | last post by:
When it is being said that, "value types are created on the stack or inline as part of an object". If a value type is created in an object, and that object is being called, the value type in that object, is still created on the stack, I would say, so I don't understand this inline business. Apart from the fact that it is my understanding that "inline" as it exists in C++ doesn't exist in C#. Could someone please shed some light on this...
4
6741
by: Hans | last post by:
Hi, I want to define a couple of constant strings, like in C: #define mystring "This is my string" or using a const char construction. Is this really not possible in Python? Hans
6
1628
by: lazy | last post by:
hi, I have some constants defined in a php script say config.php. I want to use the variables there defined in other scripts. couple of questions regd that: 1. Is there an alternative to including config.php and declaring the variables that will be used as global. This seems very inefficient. 2.Moreover these variables are constants, is there a way to make the variables unmodifiable in config.php so that scripts that use them ,
6
1488
by: vaclavpich | last post by:
Hi, I have a question on constant variables. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // #include <cstdlib> #include <iostream> using namespace std; const static char* STATIC_CONST_NAME = "Hello";
0
9214
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
9130
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
8005
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6668
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
5977
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
4484
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
4751
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2572
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2129
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.