why C++ uses DOT to access structure members and -> to access method? - c++

I come from a Delphi/Pascal programming world but I also "play" around with C++ or C once in a while, there is a question that bothers me the most: why does C++ use "." to access a structure member and "->" to access method? in Delphi/Pascal we use "." for any of those even properties...
Someone told me it has something to do with how C++ accesses memory, however that answer is NOT enough to help me understand.
Thank you.

Your understanding is incorrect. C++ accesses data members and member functions (the term "method" is not used by C++ programmers) the same way.
. accesses a member of an object. -> accesses a member of the object that is pointed to by a pointer-to-object. foo->bar is exactly equivalent to (*foo).bar.
That is why someone told you "it has something to do with how C++ accesses memory" - because it does.

All structure members (fields and methods) are accessed same way. But, in case of pointer to structure, there is two different syntaxes for the same purpose: (*pStruct).member and pStruct->member.
In Pascal (or Delphi):
var pointerToSomeRecord: ^SomeRecord;
pointerToSomeRecord^.field := 42;
In C++:
SomeStruct* pointerToSomeStruct;
(*pointerToSomeStruct).field = 42;
But, in C++ there is also another way:
pointerToSomeStruct->field = 42;
Most C++ programmers like the later form much more.

You are confusing them.
foo->bar() is semantically equivalent to (*foo).bar() (barring operator overload.)
-> is used when the left-hand argument is a pointer.
. is used when it is a reference or otherwise not a pointer.
It has nothing whatsoever to do with the right-hand side.

You are mistaken. C++ uses dot for member access and to call methods unless you have a pointer to the object the the -> operator applies.
The -> is functionally the same as (*obj).x()

The arrow operator is an abbreviation for accessing structure members via pointer:
struct foo {
int field;
}
struct foo* ptr = ...;
This
(*ptr).field
is essentially the same as
ptr->field
This has nothting to do with accessing member functions or data fields.

Related

Access to protected member through member-pointer: is it a hack?

We all know members specified protected from a base class can only be accessed from a derived class own instance. This is a feature from the Standard, and this has been discussed on Stack Overflow multiple times:
Cannot access protected member of another instance from derived type's scope
;
Why can't my object access protected members of another object defined in common base class?
And others.
But it seems possible to walk around this restriction with member pointers, as user chtz has shown me:
struct Base { protected: int value; };
struct Derived : Base
{
void f(Base const& other)
{
//int n = other.value; // error: 'int Base::value' is protected within this context
int n = other.*(&Derived::value); // ok??? why?
(void) n;
}
};
Live demo on coliru
Why is this possible, is it a wanted feature or a glitch somewhere in the implementation or the wording of the Standard?
From comments emerged another question: if Derived::f is called with an actual Base, is it undefined behaviour?
The fact that a member is not accessible using class member access expr.ref (aclass.amember) due to access control [class.access] does not make this member inaccessible using other expressions.
The expression &Derived::value (whose type is int Base::*) is perfectly standard compliant, and it designates the member value of Base. Then the expression a_base.*p where p is a pointer to a member of Base and a_base an instance of Base is also standard compliant.
So any standard compliant compiler shall make the expression other.*(&Derived::value); defined behavior: access the member value of other.
is it a hack?
In similar vein to using reinterpret_cast, this can be dangerous and may potentially be a source of hard to find bugs. But it's well formed and there's no doubt whether it should work.
To clarify the analogy: The behaviour of reinterpret_cast is also specified exactly in the standard and can be used without any UB. But reinterpret_cast circumvents the type system, and the type system is there for a reason. Similarly, this pointer to member trick is well formed according to the standard, but it circumvents the encapsulation of members, and that encapsulation (typically) exists for a reason (I say typically, since I suppose a programmer can use encapsulation frivolously).
[Is it] a glitch somewhere in the implementation or the wording of the Standard?
No, the implementation is correct. This is how the language has been specified to work.
Member function of Derived can obviously access &Derived::value, since it is a protected member of a base.
The result of that operation is a pointer to a member of Base. This can be applied to a reference to Base. Member access privileges does not apply to pointers to members: It applies only to the names of the members.
From comments emerged another question: if Derived::f is called with an actual Base, is it undefined behaviour?
Not UB. Base has the member.
Just to add to the answers and zoom in a bit on the horror I can read between your lines. If you see access specifiers as 'the law', policing you to keep you from doing 'bad things', I think you are missing the point. public, protected, private, const ... are all part of a system that is a huge plus for C++. Languages without it may have many merits but when you build large systems such things are a real asset.
Having said that: I think it's a good thing that it is possible to get around almost all the safety nets provided to you. As long as you remember that 'possible' does not mean 'good'. This is why it should never be 'easy'. But for the rest - it's up to you. You are the architect.
Years ago I could simply do this (and it may still work in certain environments):
#define private public
Very helpful for 'hostile' external header files. Good practice? What do you think? But sometimes your options are limited.
So yes, what you show is kind-of a breach in the system. But hey, what keeps you from deriving and hand out public references to the member? If horrible maintenance problems turn you on - by all means, why not?
Basically what you're doing is tricking the compiler, and this is supposed to work. I always see this kind of questions and people some times get bad results and some times it works, depending on how this converts to assembler code.
I remember seeing a case with a const keyword on a integer, but then with some trickery the guy was able to change the value and successfully circumvented the compiler's awareness. The result was: A wrong value for a simple mathematical operation. The reason is simple: Assembly in x86 does make a distinction between constants and variables, because some instructions do contain constants in their opcode. So, since the compiler believes it's a constant, it'll treat it as a constant and deal with it in an optimized way with the wrong CPU instruction, and baam, you have an error in the resulting number.
In other words: The compiler will try to enforce all the rules it can enforce, but you can probably eventually trick it, and you may or may not get wrong results based on what you're trying to do, so you better do such things only if you know what you're doing.
In your case, the pointer &Derived::value can be calculated from an object by how many bytes there are from the beginning of the class. This is basically how the compiler accesses it, so, the compiler:
Doesn't see any problem with permissions, because you're accessing value through derived at compile-time.
Can do it, because you're taking the offset in bytes in an object that has the same structure as derived (well, obviously, the base).
So, you're not violating any rules. You successfully circumvented the compilation rules. You shouldn't do it, exactly because of the reasons described in the links you attached, as it breaks OOP encapsulation, but, well, if you know what you're doing...

Global Operator "->" overload C++

I want to overload "->" operator globally for pointers. Is it possible?
A *var1 = new A(21);
int x = var1->someInt;
In that code it has to be triggered when reaching "var1"s "someInt" variable.
Actually I am trying to check the pointer before reaching its members. Also, I am trying to implement this system on a written code, so I don't want to change too much thing in the actual code.
I want to overload "->" operator globally. Is it possible?
No it is impossible.
Perhaps you might define a "root" class in your library or program (which would define that operator ->), and have all your classes inherit from it.
BTW, I am not sure you will be able to define your isPointerValid function in all cases (including the address of valid automatic variables of any class type), and efficiently.
There are many cases where you could not define such a function (e.g. union-s used in tagged union types; you don't easily know what member of a union is currently active. arbitrary casts; ...); .
For existing code and classes, the builtin meaning of -> (which you usually cannot redefine) has already been used to compile the code using them.
As described in C++17 standard draft in section 16.5.6 (emphasis mine):
An operator function shall either be a non-static member function or
be a non-member function that has at least one parameter whose type
is a class, a reference to a class, an enumeration, or a reference to
an enumeration.
Hence, it is not possible to overload an operator which doesn't take any arguments.

Why can't you call functions on a pointer object?

Edit: sorry about the stupid title; by "pointer object" I think I mean dereferenced object pointer (if that's any clarification).
I'm new to C++, and I've been trying to get used to its idiosyncrasies (coming from Java).
I know it's not usually necessary, but I wanted to try passing an object by its pointer. It works, of course, but I was expecting this to work too:
void test(Dog * d) {
*d.bark();
}
And it doesn't. Why is this? I found out that I can do the following:
void test(Dog * d) {
Dog dawg = *d;
dawg.bark();
}
and it works flawlessly. It seems so redundant to me.
Any clarification would be appreciated. Thanks!
Imo . has precedence over dereference * , thus:
(*d).bark();
or, for pointers, as stated in other replies - use ->
d->bark();
be sure to check for null :)
Just to clarify the situation, you can use either (*pointer).member(), or pointer->member() -- a->b is equivalent to (*a).b.
That, of course, is assuming you're dealing with "real" (built-in) pointers. It's possible to overload operator-> to do something different. Overloads of operator-> are somewhat restricted though, which generally prevents people from doing too strange of things with them. The one thing you might run into (e.g., with old implementations of some iterators) is simply failing to support operator-> at all, so trying to use it will result in a compile error. Though such implementations are (mostly?) long gone, you might still see some (typically older) code that uses (*iterator).whatever instead of -> because of this.
You have to use the -> operator on pointers. The . operator is for non-pointer objects.
In your first code snippet, try d->bark();. Should work fine!
EDIT: Other answers suggest (*d).bark();. That will work as well; the (*d) dereferences the pointer (ie. turns it into a normal object) which is why the . operator works. To use the original pointer, simply d, you must use the -> operator as I described.
Hope this helps!
Its all in the parentheses:
(*d).bark();
Everyone is missing one point to answer: Operator Precedence.
The precedence of operator. is higher than that of (unary) pointer indirection (*) opeartor. That's why brackets are needed. It's just like putting parenthesis around + to get correct average:
int nAverage = (n1+n2) / 2;
For pointer indirection case, you are lukcy that compiler is giving you error!
You need to use -> operator when using pointers, i.e. code should be d->bark();.

C++ proper usage, this pointer [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should I make explicit use of the this pointer?
I'm wondering about the proper usage of the "this" pointer.
I've seen someone create a class constructor with the argument passed variable passed in named 'data'.
However he had a private member variable named 'data' already thus he simply used:
this->data = data;
would have worked to simply use
data = data_in
(if the parameter was named data_in), and no need to invoke the "this" pointer and reference the member type.
Now I'm wondering, is this proper usage? Using this->member to reduce on naming complexity? I mean it works and I see that it accomplishes what was intended but I'm wondering if some of you more experienced C++ guys and girls can say a word or two if this is common practice?
Also, out of curiosity I've instrumented the code just to see what happens under the hood, and it seems the "this" pointer is invoked anyhow. I guess that's the way references to the class object are done anyways.
In most cases, specifically dereferencing the this pointer to access a non-static data-member of the class instance is unnecessary, but it can help with naming confusion, especially when the data-members of the class are defined in a separate header file from the code-module. However, it is necessary to use the this pointer if you are accessing a non-static data-member that is a member of a base-class that is a templated class. In other words, in a situation like:
template<typename T>
class base_class
{
protected:
int a;
};
template<typename T>
class derived_class : public base_class<T>
{
void function()
{
a = 5; //this won't work
this->a = 5; //this will work
}
};
you'll note that you must use the this pointer in order to properly resolve the inherited non-static data-member from the template base-class. This is due to the fact that base_class<T>::a is a dependent name, in this case dependent on the template parameter T, but when used without the this pointer, it is treated as a non-dependent name, and is therefore not looked up in the dependent base-class namespace. Thus without the specific dereference of the this pointer, you'll end up with a compiler error like "a was not declared in this scope", or something similar.
No accessing a class member as:
this->member = something;
is same as accessing the member by itself,
member = something;
The compiler sees both as same and their is no overhead involved. Even if you use the second format the compiler does the same as first format under the hood.
In short, trying to use either of the two formats with aim of improving performance is useless. Ofcourse, You might have to use the first format in some template cases( accessing non-static data members of a templated Base class) but that is not for performance.
Essentially identical, except as Jason pointed out.
The nice part is that if you use this-> most editors will code complete for you, saving you typing.
It is "correct", but it is also poor practice. Naming parameters the same as class members is a bad idea. Intentionally creating naming conflicts is a bad idea.
Scoping operators are designed for when naming conflicts are unavoidable, such as when overriding a base member, or when using two libraries with identifier names chosen independently. Don't consider them free license for doing stupid things.
Unless you're practicing for an obfuscated code contest. Then by all means introduce naming collisions.

Why is const-correctness specific to C++?

Disclaimer: I am aware that there are two questions about the usefulness of const-correctness, however, none discussed how const-correctness is necessary in C++ as opposed to other programming languages. Also, I am not satisfied with the answers provided to these questions.
I've used a few programming languages now, and one thing that bugs me in C++ is the notion of const-correctness. There is no such notion in Java, C#, Python, Ruby, Visual Basic, etc., this seems to be very specific to C++.
Before you refer me to the C++ FAQ Lite, I've read it, and it doesn't convince me. Perfectly valid, reliable programs are written in Python all the time, and there is no const keyword or equivalent. In Java and C#, objects can be declared final (or const), but there are no const member functions or const function parameters. If a function doesn't need to modify an object, it can take an interface that only provides read access to the object. That technique can equally be used in C++. On the two real-world C++ systems I've worked on, there was very little use of const anywhere, and everything worked fine. So I'm far from sold on the usefulness of letting const contaminate a codebase.
I am wondering what is it in C++ that makes const necessary, as opposed to other programming languages.
So far, I've seen only one case where const must be used:
#include <iostream>
struct Vector2 {
int X;
int Y;
};
void display(/* const */ Vector2& vect) {
std::cout << vect.X << " " << vect.Y << std::endl;
}
int main() {
display(Vector2());
}
Compiling this with const commented out is accepted by Visual Studio, but with warning C4239, non-standard extension used. So, if you want the syntactic brevity of passing in temporaries, avoiding copies, and staying standard-compliant, you have to pass by const reference, no way around it. Still, this is more like a quirk than a fundamental reason.
Otherwise, there really is no situation where const has to be used, except when interfacing with other code that uses const. Const seems to me little else than a self-righteous plague that spreads to everything it touches :
The reason that const works in C++ is
because you can cast it away. If you
couldn't cast it away, then your world
would suck. If you declare a method
that takes a const Bla, you could pass
it a non-const Bla. But if it's the
other way around you can't. If you
declare a method that takes a
non-const Bla, you can't pass it a
const Bla. So now you're stuck. So you
gradually need a const version of
everything that isn't const, and you
end up with a shadow world. In C++ you
get away with it, because as with
anything in C++ it is purely optional
whether you want this check or not.
You can just whack the constness away
if you don't like it.
Anders Hejlsberg (C# architect), CLR Design Choices
Const correctness provides two notable advantages to C++ that I can think of, one of which makes it rather unique.
It allows pervasive notions of mutable/immutable data without requiring a bunch of interfaces. Individual methods can be annotated as to whether or not they can be run on const objects, and the compiler enforces this. Yes, it can be a hassle sometimes, but if you use it consistently and don't use const_cast you have compiler-checked safety with regards to mutable vs. immutable data.
If an object or data item is const, the compiler is free to place it in read-only memory. This can particularly matter in embedded systems. C++ supports this; few other languages do. This also means that, in the general case, you cannot safely cast const away, although in practice you can do so in most environments.
C++ isn't the only language with const correctness or something like it. OCaml and Standard ML have a similar concept with different terminology — almost all data is immutable (const), and when you want something to be mutable you use a different type (a ref type) to accomplish that. So it's just unique to C++ within its neighboring languages.
Finally, coming the other direction: there have been times I have wanted const in Java. final sometimes doesn't go far enough as far as creating plainly immutable data (especially immutable views of mutable data), and don't want to create interfaces. Look at the Unmodifiable collection support in the Java API and the fact that it only checks at run time whether modification is allowed for an example of why const is useful (or at least the interface structure should be deepend to have List and MutableList) — there is no reason that attempting to mutate an immutable structure can't be a compile-type error.
I don't think anybody claims const-correctness is "necessary". But again, classes are not really necessary either, are they? The same goes for namespaces, exceptions,... you get the picture.
Const-correctness helps catch errors at compile time, and that's why it is useful.
const is a way for you to express something. It would be useful in any language, if you thought it was important to express it. They don't have the feature, because the language designers didn't find them useful. If the feature was there, it would be about as useful, I think.
I kind of think of it like throw specifications in Java. If you like them, you would probably like them in other languages. But the designers of the other languages didn't think it was that important.
Well, it will have taken me 6 years to really understand, but now I can finally answer my own question.
The reason C++ has "const-correctness" and that Java, C#, etc. don't, is that C++ only supports value types, and these other languages only support or at least default to reference types.
Let's see how C#, a language that defaults to reference types, deals with immutability when value types are involved. Let's say you have a mutable value type, and another type that has a readonly field of that type:
struct Vector {
public int X { get; private set; }
public int Y { get; private set; }
public void Add(int x, int y) {
X += x;
Y += y;
}
}
class Foo {
readonly Vector _v;
public void Add(int x, int y) => _v.Add(x, y);
public override string ToString() => $"{_v.X} {_v.Y}";
}
void Main()
{
var f = new Foo();
f.Add(3, 4);
Console.WriteLine(f);
}
What should this code do?
fail to compile
print "3, 4"
print "0, 0"
The answer is #3. C# tries to honor your "readonly" keyword by invoking the method Add on a throw-away copy of the object. That's weird, yes, but what other options does it have? If it invokes the method on the original Vector, the object will change, violating the "readonly"-ness of the field. If it fails to compile, then readonly value type members are pretty useless, because you can't invoke any methods on them, out of fear they might change the object.
If only we could label which methods are safe to call on readonly instances... Wait, that's exactly what const methods are in C++!
C# doesn't bother with const methods because we don't use value types that much in C#; we just avoid mutable value types (and declare them "evil", see 1, 2).
Also, reference types don't suffer from this problem, because when you mark a reference type variable as readonly, what's readonly is the reference, not the object itself. That's very easy for the compiler to enforce, it can mark any assignment as a compilation error except at initialization. If all you use is reference types and all your fields and variables are readonly, you get immutability everywhere at little syntactic cost. F# works entirely like this. Java avoids the issue by just not supporting user-defined value types.
C++ doesn't have the concept of "reference types", only "value types" (in C#-lingo); some of these value types can be pointers or references, but like value types in C#, none of them own their storage. If C++ treated "const" on its types the way C# treats "readonly" on value types, it would be very confusing as the example above demonstrates, nevermind the nasty interaction with copy constructors.
So C++ doesn't create a throw-away copy, because that would create endless pain. It doesn't forbid you to call any methods on members either, because, well, the language wouldn't be very useful then. But it still wants to have some notion of "readonly" or "const-ness".
C++ attempts to find a middle way by making you label which methods are safe to call on const members, and then it trusts you to have been faithful and accurate in your labeling and calls methods on the original objects directly. This is not perfect - it's verbose, and you're allowed to violate const-ness as much as you please - but it's arguably better than all the other options.
You're right, const-correctness isn't necessary. You can certainly write all your code without the const keyword and get things to work, just as you do in Java and Python.
But if you do that, you'll no longer get the compiler's help in checking for const violations. Errors that the compiler would have told you about at compile-time will now be found only at run-time, if at all, and therefore will take you longer to diagnose and fix.
Therefore, trying to subvert or avoid the const-correctness feature is just making things harder for yourself in the long run.
Programming is writing in a language that will be ultimately processed by the computer, but that is both a way of communicating with the computer and other programmers in the same project. When you use a language, you are restricted to the concepts that can be expressed in it, and const is just one more concept you can use to describe your problem, and your solution.
Constantness enables you to express clearly from the design board to the code one concept that other languages lack. As you come from a language that does not have it, you may seem puzzled by a concept you have never used --if you never used it before, how important can it be?
Language and thought are tightly coupled. You can only express your thoughts in the language you speak, but the language also changes the way you think. The fact that you did not have the const keyword in the languages you worked with implies that you have already found other solutions to the same problems, and those solutions are what seems natural to you.
In the question you argued that you can provide a non mutating interface that can be used by functions that do not need to change the contents of the objects. If you think about it for a second, this same sentence is telling you why const is a concept you want to work with.
Having to define a non-mutating interface and implement it in your class is a work around the fact that you cannot express that concept in your language.
Constantness allows you to express those concepts in a language that the compiler (and other programers) can understand. You are establishing a compromise on what you will do with the parameters you receive, the references you store, or defining limits on what the users of your class are allowed to do with the references you provide. Pretty much each non-trivial class can have a state represented by attributes, and in many cases there are invariants that must be kept. The language lets you define functions that offer access to some internal data while at the same time limits the access to a read-only view that guarantees no external code will break your invariants.
This is the concept I miss more when moving to other languages. Consider an scenario where you have a class C that has among others an attribute a of type A that must be visible to external code (users of your class must be able to query for some information on a). If the type of A has any mutating operation, then to keep user code from changing your internal state, you must create a copy of a and return it. The programmer of the class must be aware that a copy must be performed and must perform the (possibly expensive) copy. On the other hand, if you could express constantness in the language, you could just return a constant reference to the object (actually a reference to a constant view of the object) and just return the internal element. This will allow the user code to call any method of the object that is checked as non-mutating, thus preserving your class invariants.
The problem/advantage, all depends on the point of view, of constantness is that it is viral. When you offer a constant reference to an object, only those methods flagged as non-mutating can be called, and you must tell the compiler which of the methods have this property. When you declare a method constant, you are telling the compiler that user code that calls that method will keep the object state. When you define (implement) a method that has a constant signature, the compiler will remind you of your promise and actually require that you do not internally modify the data.
The language enables you to tell the compiler properties of your methods that you cannot express any other way, and at the same time, the compiler will tell you when you are not complying with your design and try to modify the data.
In this context, const_cast<> should never be used, as the results can take you into the realm of undefined behavior (both from a language point of view: the object could be in read-only memory, and from a program point of view: you might be breaking invariants in other classes). But that, of course, you already know if you read the C++FAQ lite.
As a side note, the final keyword in Java has really nothing to do with the const keyword in C++ when you are dealing with references (in C++ references or pointers). The final keyword modifies the local variable to which it refers, whether a basic type or a reference, but is not a modifier of the referred object. That is, you can call mutating methods through a final reference and thus provide changes in the state of the object referred. In C++, references are always constant (you can only bind them to an object/variable during construction) and the const keyword modifies how the user code can deal with the referred object. (In case of pointers, you can use the const keyword both for the datum and the pointer: X const * const declares a constant pointer to a constant X)
If you are writing programs for embedded devices with data in FLASH or ROM you can't live without const-correctness. It gives you the power to control the correct handling of data in different types of memory.
You want to use const in methods as well in order to take advantage of return value optimization. See Scott Meyers More Effective C++ item 20.
This talk and video from Herb Sutter explains the new connotations of const with regards to thread-safety.
Constness might not have been something you had to worry about too much before but with C++11 if you want to write thread-safe code you need to understand the significance of const and mutable
In C, Java and C# you can tell by looking at the call site if a passed object can be modified by a function:
in Java you know it definitely can be.
in C you know it only can be if there is a '&', or equivalent.
in c# you need to say 'ref' at the call site too.
In C++ in general you can't tell this, as a non-const reference call looks identical to pass-by-value. Having const references allows you to set up and enforce the C convention.
This can make a fairly major difference in readability of any code that calls functions. Which is probably enough to justify a language feature.
Anders Hejlsberg (C# architect): ... If you declare a method that takes a non-const Bla, you can't pass it a const Bla. So now you're stuck. So you gradually need a const version of everything that isn't const, and you end up with a shadow world.
So again: if you started to use "const" for some methods you usually forced to use this in most of your code. But the time spent for maintaining (typing, recompiling when some const is missing, etc.) of const-correctness in code seems greater than for fixing of possible (very rare) problems caused by not using of const-correctness at all. Thus lack of const-correctness support in modern languages (like Java, C#, Go, etc.) might result in slightly reduced development time for the same code quality.
An enhancement request ticket for implementing const correctness existed in the Java Community Process since 1999, but was closed in 2005 due to above mentioned "const pollution" and also compatibility reasons: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070
Although C# language has no const correctness construct but similar functionality possibly will appear soon in "Microsoft Code Contracts" (library + static analysis tools) for .NET Framework by using [Pure] and [Immutable] attributes: Pure functions in C#
Actually, it's not... not entirely, anyway.
In other languages, especially functional or hybrid languages, like Haskell, D, Rust, and Scala, you have the concept of mutability: variables can be mutable, or immutable, and are usually immutable by default.
This lets you (and your compiler/interpreter) reason better about functions: if you know that a function only takes immutable arguments, then you know that function isn't the one that's mutating your variable and causing a bug.
C and C++ do something similar using const, except that it's a much less firm guarantee: the immutability isn't enforced; a function further down the call stack could cast away the constness, and mutate your data, but that would be a deliberate violation of the API contract. So the intention or best practice is for it to work quite like immutability in other languages.
All that said, C++ 11 now has an actual mutable keyword, alongside the more limited const keyword.
The const keyword in C++ (as applied to parameters and type declarations) is an attempt to keep programmers from shooting off their big toe and taking out their whole leg in the process.
The basic idea is to label something as "cannot be modified". A const type can't be modified (by default). A const pointer can't point to a new location in memory. Simple, right?
Well, that's where const correctness comes in. Here are some of the possible combinations you can find yourself in when you use const:
A const variable
Implies that the data labeled by the variable name cannot be modified.
A pointer to a const variable
Implies that the pointer can be modified, but the data itself cannot.
A const pointer to a variable
Implies that the pointer cannot be modified (to point to a new memory location), but that the data to which the pointer points can be modified.
A const pointer to a const variable
Implies that neither the pointer nor the data to which it points can be modified.
Do you see how some things can be goofy there? That's why when you use const, it's important to be correct in which const you are labeling.
The point is that this is just a compile-time hack. The labeling just tells the compiler how to interpret instructions. If you cast away from const, you can do whatever you want. But you'll still have to call methods that have const requirements with types that are cast appropriately.
For example you have a funcion:
void const_print(const char* str)
{
cout << str << endl;
}
Another method
void print(char* str)
{
cout << str << endl;
}
In main:
int main(int argc, char **argv)
{
const_print("Hello");
print("Hello"); // syntax error
}
This because "hello" is a const char pointer, the (C-style) string is put in read only memory.
But it's useful overall when the programmer knows that the value will not be changed.So to get a compiler error instead of a segmentation fault.
Like in non-wanted assignments:
const int a;
int b;
if(a=b) {;} //for mistake
Since the left operand is a const int.