 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Alf P. Steinbach Guest
|
Posted: Wed Oct 26, 2005 12:10 pm Post subject: Pointers and polymorphism explained [preview, PDF, part of |
|
|
So, I got the itch to write something more...
I apologize for not doing more on the attempted "Correct C++ Tutorial"
earlier, but there were reasons.
This is an UNFINISHED and RAW document, and at the end there is even pure
mindstorming text left in, but already I think it can be very useful.
<url: http://home.no.net/dubjai/win32cpptut/special/pointers/preview/pointers_01__alpha.doc.pdf>.
What do you think?
In particular, if you find any grave errors, please do not hesitate to
comment. I always make errors. Those I agree are errors will be corrected.
Contents (so far):
1 1 Pointers.
1 1.1 Introduction to the basics.
1 1.1.1 How to obtain a pointer to a given object, and how to use that pointer.
3 1.1.2 The nullpointer value, valid and invalid pointers.
6 1.1.3 How to implement out-arguments by using pointers.
8 1.1.4 How to implement in-arguments by using pointers.
9 1.1.5 How to use C++ style references instead of C style pointers for arguments.
11 1.1.6 How to access main arguments.
12 1.1.7 Const-correctness for pointers (and references).
14 1.2 Run-time polymorphism.
14 1.2.1 Polymorphism.
16 1.2.2 The concept of linked data structures.
17 1.2.3 C-style polymorphism with simulated dynamic types (just one actual type).
19 1.2.4 Basic use of dynamic memory allocation & deallocation.
22 1.2.5 How to use function pointers to simulate dynamic types, C-style.
25 1.2.6 Using real types and inheritance for logical sub-types, mostly C-style.
32 1.2.7 Using vtables, mostly C-style (also a few words about abstract classes, etc.).
38 1.2.8 C++ virtual member functions.
45 1.2.9 C++ destructors and polymorphic delete.
49 1.2.10 Object ownership and the C++ std::auto_ptr.
53 1.2.11 C++ constructors and exception safety for new.
57 1.3 Dynamically allocated objects versus others.
58 1.3.1 Ensure dynamic allocation using C++ access specifiers and copy constructors.
61 – End Of Text –
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|
|
| Back to top |
|
 |
Robert Macy Guest
|
Posted: Wed Oct 26, 2005 4:11 pm Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Alf,
I don't think I can find errors for you, but read it I will.
Small note, the "green" color for highlighting on my screen is almost
no highlight whatsoever. Looks like the adjacent letters, unless I
really, really look at it.
Good subject, pointers.
- Robert -
|
|
| Back to top |
|
 |
Robert Macy Guest
|
Posted: Wed Oct 26, 2005 5:41 pm Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Alf,
The program called bad_pointer02.cpp on page 4 [page 6 of pdf] returns
the proper value, 43. It did not seem to yield undefined behaviour.
I use MSVC line command running on XP.
I can't see where the program is wrong. The function is called, x is
created, the pointer is set to the location, and then return...oops. I
get it. But the program still returned the proper value. hmm... Bet
this happens everytime until you count on it.
- Robert -
|
|
| Back to top |
|
 |
Mirek Fidler Guest
|
Posted: Wed Oct 26, 2005 7:14 pm Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Robert Macy wrote:
| Quote: | Alf,
The program called bad_pointer02.cpp on page 4 [page 6 of pdf] returns
the proper value, 43. It did not seem to yield undefined behaviour.
|
Actully, that is the tricky part of undefined behaviour. It often works
on one platform and fails on another.
Mirek
|
|
| Back to top |
|
 |
Alf P. Steinbach Guest
|
Posted: Thu Oct 27, 2005 12:10 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
* Robert Macy:
| Quote: |
Small note, the "green" color for highlighting on my screen is almost
no highlight whatsoever. Looks like the adjacent letters, unless I
really, really look at it.
|
Yes, that was intentionally. The idea is to make it clear, as one reads
the text, that this word or term is a new one, defined by the context.
Without drawing the eyes towards that word or term, and without making
it seem like a good idea to just skim those words or terms.
Originally they weren't even boldface.
But then I changed my mind: without boldface they appeared with _less_
contrast than the rest of the text...
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|
|
| Back to top |
|
 |
Alf P. Steinbach Guest
|
Posted: Thu Oct 27, 2005 12:19 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
* Robert Macy:
| Quote: | Alf,
The program called bad_pointer02.cpp on page 4 [page 6 of pdf] returns
the proper value, 43. It did not seem to yield undefined behaviour.
I use MSVC line command running on XP.
I can't see where the program is wrong. The function is called, x is
created, the pointer is set to the location, and then return...oops. I
get it. But the program still returned the proper value. hmm... Bet
this happens everytime until you count on it.
|
Thanks for that comment, it's appreciated.
It just so happens that with the compiler options etc. you're using,
there's nothing that changes the contents of the chunk of memory that
the local variable occupied, between the time the pointer is obtained,
and the time the pointer is used -- Undefined Behavior is allowed to
do anything, including what someone might expect it to do, or not.
One simple way to trash that memory (overwrite it with something else),
is to call some function or, even just evaluating a suitable expression.
E.g., I think something like
std::cout << "Oops!" << std::endl;
after the call to wrongAnswer(), but before displaying the contents of
*p, would do the trick.
I'll probably put in a statement like the "Oops!", to make it even more
clear that this program is really really Undefined Behavior.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|
|
| Back to top |
|
 |
Chris ( Val ) Guest
|
Posted: Thu Oct 27, 2005 1:46 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Alf P. Steinbach wrote:
| Quote: | So, I got the itch to write something more...
I apologize for not doing more on the attempted "Correct C++ Tutorial"
earlier, but there were reasons.
This is an UNFINISHED and RAW document, and at the end there is even pure
mindstorming text left in, but already I think it can be very useful.
url: http://home.no.net/dubjai/win32cpptut/special/pointers/preview/pointers_01__alpha.doc.pdf>.
What do you think?
In particular, if you find any grave errors, please do not hesitate to
comment. I always make errors. Those I agree are errors will be corrected.
|
Hi Alf,
I am very busy at the moment, but I had a very, very brief look,
and a few things caught my eye, and that was to do with wording.
I will look at the rest when I get a chance.
Btw, it's just an opinion, so don't get too heated over it :-)
1 Pointers:
A pointer is a value that identifies where some object or
function is located in the computer's memory.
// I would have said something along the lines of:
* A pointer is a special type of variable that stores an address.
* The address stored in the pointer is an integral value, which
points to a location in the computer's memory.
* Just like an address that identifies where a house is located
on your street, the pointer address in turn identifies exactly
where in memory an object of a given type can be located.
1.1 Introduction to the basics.
// Remove this line or re-phrase it (covered in the text above):
A pointer that tells where an object o is located is said to point to
o.
// A few lines down we find:
*p = 42; Assigning to the object a pointer points to.
which doesn't change p, but the object that p points to.
That's called dereferencing. (*)
I think this (*) is a little misleading - Although the operation
is called assignment, it is not clear what you are actually calling
dereferencing. Even though you mention the dereferencing operator
a few more lines down, it has not been made clear what the act of
dereferencing actually means.
AFAIU, dereferencing is the act of applying an operator to a pointer
variable, to ultimately access the undelying value of the object being
pointed to - I think this or similar explanation should be provided
for the newbie.
// <nit> In the following sentence you have:
And to make p point to o you just apply the address operator, &, to o:
In this particular context, I always new this operator to be called
the "address of" operator, rather than just the "address operator".
// For your question in the following, I would add (shown below):
p = &o; // Set p to point to o.
*p = 42; // Assign
And, for example, does the order of the two commented statements
matter?
* Yes, it does matter, and that is where one advantage of
initialisation can help, if appropriate:
int* p( &o ); // no order to worry about
Sorry I could not look at more of your tutorial (for now), but I
will when I get some more time.
Hope my opinions were useful :-)
Cheers,
Chris Val
|
|
| Back to top |
|
 |
Robert Macy Guest
|
Posted: Thu Oct 27, 2005 2:21 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
I got all the way through the first section!
I especially like your comment about reading the code from right to
left. I've been doing that technique with much of the help from the MS
website, not on a line basis, but on a conceptual basis. Right to
left? then it dawned on me that math is right to left. As in, C equals
A plus B etc. As opposed to A plus B equals C. Then I remembered, that
our math [numbers] came from Arabic origins which is also right to
left. All making more sense now.
However, I am stuck at one concept. On page 13 [page 15 of pdf] there
is a section of code that varies from ok to "not ok" at the last line.
I tried compiling the code into a simple program, test.cpp. On MSVC
line command on the XP, the compiler first would not accept a constant
*unless* the constant is initialized to some value. Nice check. And
sure enough, as you predicted, the compiler would not process the line
16
/* from page 15
*/
#include <iostream> // std::cout
#include <ostream> // std::endl
int main()
{
int o;
int const oConst = 1; // must initialize a constant
int* p = &o;
int const* pConst = &oConst;
pConst = p; // ok
pConst = pConst; // ok
p = p; // ok
p = pConst; // won't compile ??
}
/*
Line 16 prevents this from compiling
test.cpp(16) : error C2440: '=' : cannot convert from 'const int *' to
'int *'
Conversion loses qualifiers
*/
For me, it looked like pConst=p; should cause a problem. I must be
missing what the equals sign means here.
- Robert -
|
|
| Back to top |
|
 |
Marcus Kwok Guest
|
Posted: Thu Oct 27, 2005 5:04 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Robert Macy <macy (AT) california (DOT) com> wrote:
| Quote: | However, I am stuck at one concept. On page 13 [page 15 of pdf] there
is a section of code that varies from ok to "not ok" at the last line.
I tried compiling the code into a simple program, test.cpp. On MSVC
line command on the XP, the compiler first would not accept a constant
*unless* the constant is initialized to some value. Nice check. And
sure enough, as you predicted, the compiler would not process the line
16
int o;
int const oConst = 1; // must initialize a constant
int* p = &o;
int const* pConst = &oConst;
[snip]
p = pConst; // won't compile ??
test.cpp(16) : error C2440: '=' : cannot convert from 'const int *' to
'int *'
Conversion loses qualifiers
For me, it looked like pConst=p; should cause a problem. I must be
missing what the equals sign means here.
|
When you try to assign "regular pointer = pointer to const", then that
implies that pointer should be allowed to change the object pointed to.
Trying to change a const object is very bad, so it was decided to
prevent that at compile time.
--
Marcus Kwok
|
|
| Back to top |
|
 |
BobR Guest
|
Posted: Thu Oct 27, 2005 5:50 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Robert Macy wrote in message
| Quote: |
However, I am stuck at one concept. On page 13 [page 15 of pdf] there
is a section of code that varies from ok to "not ok" at the last line.
I tried compiling the code into a simple program, test.cpp. On MSVC
line command on the XP, the compiler first would not accept a constant
*unless* the constant is initialized to some value. Nice check. And
sure enough, as you predicted, the compiler would not process the line
16
/* from page 15
*/
#include <iostream> // std::cout
#include <ostream> // std::endl
int main()
{
int o;
int const oConst = 1; // must initialize a constant
int* p = &o;
int const* pConst = &oConst;
pConst = p; // ok
pConst = pConst; // ok
p = p; // ok
p = pConst; // won't compile ??
}
/*
Line 16 prevents this from compiling
test.cpp(16) : error C2440: '=' : cannot convert from 'const int *' to
'int *'
Conversion loses qualifiers
*/
For me, it looked like pConst=p; should cause a problem. I must be
missing what the equals sign means here.
- Robert -
|
// p is pointing to memory that can be *read* or written to (RW).
*p = 43; // should be no problem.
pConst = p; // should not cause a problem. The 'int' *can* be read.
// *pConst = 43; // should cause a problem. "assignment of read-only
location"
// The 'int' is constant (RO), not the pointer to it.
int * const pcConst = &o;
// pcConst = p; // should cause a problem. The pointer is const.
// "assignment of read-only variable `pcConst' "
*pcConst = 43; // should not cause a problem. What it points to is RW.
int const * const pccConst = &oConst;
// pccConst = p; // nope. The pointer is const.
// *pccConst = 43; // nope. What it points to is RO.
--
Bob R
POVrookie
|
|
| Back to top |
|
 |
Alf P. Steinbach Guest
|
Posted: Thu Oct 27, 2005 11:44 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
* Chris ( Val ):
| Quote: | * Alf P. Steinbach:
url: http://home.no.net/dubjai/win32cpptut/special/pointers/preview/pointers_01__alpha.doc.pdf>.
What do you think?
I am very busy at the moment, but I had a very, very brief look,
and a few things caught my eye, and that was to do with wording.
I will look at the rest when I get a chance.
Btw, it's just an opinion, so don't get too heated over it :-)
1 Pointers:
A pointer is a value that identifies where some object or
function is located in the computer's memory.
// I would have said something along the lines of:
* A pointer is a special type of variable that stores an address.
* The address stored in the pointer is an integral value, which
points to a location in the computer's memory.
* Just like an address that identifies where a house is located
on your street, the pointer address in turn identifies exactly
where in memory an object of a given type can be located.
|
Well, I basically like your idea of pointing out (!) that a pointer is
effectively integral: you can increment and decrement pointers, and
there are no pointer values in between the values so generated (although
for some pointers these operations give undefined behavior).
There are however two reasons why I think it would not be a good idea to
mention that. First and foremost, the standard reserves the term
"integral type" to mean bool, char, wchar_t, and the signed and unsigned
integer types (the term integral type is defined in paragraph 3.9.1/7),
i.e.,
a pointer type is _not_ integral
in the standard's definition of the term. Second reason, I'd rather not
get into a discussion of raw arrays at this point, both because there's
so much said about that topic, and because the beginner is much better
served by using e.g. std::vector and std::string instead.
Regarding "special" and "variable": nope, a pointer is neither special
nor necessarily a variable. We often say that e.g. a function returns a
pointer to such and such. The function does not return a variable.
Regarding "an object": nope, a pointer does not necessarily point to an
object. ;-)
Actually I took pains to explain that last in detail, most of the ways
that a valid C++ pointer need _not_ point to an object. But then I
goofed on the introductory sentence! So thanks also for focusing on
that sentence. But how should it be rephrased? Perhaps put in the word
"basically" or some such, in parenthesis?
| Quote: | 1.1 Introduction to the basics.
// Remove this line or re-phrase it (covered in the text above):
A pointer that tells where an object o is located is said to point to
o.
|
It defines the term "point to" (shown in bold green), not yet covered.
| Quote: | // A few lines down we find:
*p = 42; Assigning to the object a pointer points to.
which doesn't change p, but the object that p points to.
That's called dereferencing. (*)
I think this (*) is a little misleading - Although the operation
is called assignment, it is not clear what you are actually calling
dereferencing. Even though you mention the dereferencing operator
a few more lines down, it has not been made clear what the act of
dereferencing actually means.
|
Thanks -- perhaps just replace "that" by "applying *"?
| Quote: | AFAIU, dereferencing is the act of applying an operator to a pointer
variable, to ultimately access the undelying value of the object being
pointed to - I think this or similar explanation should be provided
for the newbie.
// <nit> In the following sentence you have:
And to make p point to o you just apply the address operator, &, to o:
In this particular context, I always new this operator to be called
the "address of" operator, rather than just the "address operator".
|
Not sure.
| Quote: | // For your question in the following, I would add (shown below):
p = &o; // Set p to point to o.
*p = 42; // Assign
And, for example, does the order of the two commented statements
matter?
* Yes, it does matter, and that is where one advantage of
initialisation can help, if appropriate:
int* p( &o ); // no order to worry about
|
Here I think I'll leave it as-is. In order to present a clean example I
deliberately did not use initialization. The example as-is shows that a
pointer variable isn't necessarily initialized at the point of
declaration. Bringing in C++ direct initializer syntax would just
confuse things, I think. Better with a minimal, clean example.
I hold to that guideline throughout the tutorial and this document.
For example, from a "best possible C++" view most of the classes I
present would benefit greatly from using constructors, access specifiers
and so on. But that would not help get across the points I want to get
across, it would just add more extranous things to deal with for the
reader (who possibly hasn't yet been introduced to those features, and
anyway does not necessarily see what their usage is all about in any
particular example). Instead I've chosen to present the minimum number
of concepts at a time, with minimum extranous clutter.
| Quote: | Sorry I could not look at more of your tutorial (for now), but I
will when I get some more time.
Hope my opinions were useful
|
Yes, they were. Thank you,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|
|
| Back to top |
|
 |
Alf P. Steinbach Guest
|
Posted: Thu Oct 27, 2005 11:59 am Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
* Robert Macy:
| Quote: |
However, I am stuck at one concept. On page 13 [page 15 of pdf] there
is a section of code that varies from ok to "not ok" at the last line.
I tried compiling the code into a simple program, test.cpp. On MSVC
line command on the XP, the compiler first would not accept a constant
*unless* the constant is initialized to some value. Nice check.
|
Thanks, will fix.
| Quote: | ...
For me, it looked like pConst=p; should cause a problem. I must be
missing what the equals sign means here.
|
The equals sign is just an ordinary assignment.
The assignment is accepted because you can't do any "harm" via the
pConst pointer.
But you're right that there _is_ a problem, namely that with the pConst
pointer in hand one might be expecting that it points to an unchanging
object. Then someone uses the p pointer that it came from, to change
that object, and whoops. The problem here is not the changing object,
but the expectation of an unchanging object.
A pointer to const does _not_ guarantee an unchanging object.
What it guarantees (except for using low-level features to circumvent
the rules) is that the object can't be changed via _that_ pointer, that
some code that only has _that_ pointer in hand, can't change the pointed
to object.
This should perhaps be discussed in greater detail.
I just said, look at it, then look at it again, until it's "obvious"...
;-)
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|
|
| Back to top |
|
 |
Sigurd Stenersen Guest
|
Posted: Thu Oct 27, 2005 12:25 pm Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Alf P. Steinbach wrote:
| Quote: | Regarding "special" and "variable": nope, a pointer is neither special
nor necessarily a variable. We often say that e.g. a function
returns a pointer to such and such. The function does not return a
variable.
|
Actually, a function like the one you describe here doesn't return a
pointer. It returns a pointer *value*, which in this case is a constant
with a very short life expectancy (i.e. if you don't use it right away, it's
gone).
--
Sigurd
http://utvikling.com
|
|
| Back to top |
|
 |
Sigurd Stenersen Guest
|
Posted: Thu Oct 27, 2005 12:35 pm Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
Chris ( Val ) wrote:
| Quote: | * The address stored in the pointer is an integral value, which
points to a location in the computer's memory.
|
You imply a linear address space, and that is not necessarily correct.
Also, arithmetics are different for pointers than for integral types. For
instance, if you add 1 to a pointer the internal representation may increase
by any amount (depending on the size of what's pointed to).
--
Sigurd
http://utvikling.com
|
|
| Back to top |
|
 |
Alf P. Steinbach Guest
|
Posted: Thu Oct 27, 2005 12:53 pm Post subject: Re: Pointers and polymorphism explained [preview, PDF, part |
|
|
* Sigurd Stenersen:
| Quote: | Alf P. Steinbach wrote:
Regarding "special" and "variable": nope, a pointer is neither special
nor necessarily a variable. We often say that e.g. a function
returns a pointer to such and such. The function does not return a
variable.
Actually, a function like the one you describe here doesn't return a
pointer. It returns a pointer *value*, which in this case is a constant
with a very short life expectancy (i.e. if you don't use it right away, it's
gone).
|
Actually, it returns a pointer.
Depending on the context, the word "pointer" can mean
* A pointer value.
* A pointer variable.
* A pointer type.
The last usage is not very common in ordinary programming, but abounds
in the standard.
And the list above is not exhaustive. For example, we differentiate
between "raw pointers" and "smart pointers". Where "pointer" denotes a
more general _concept_, and is restricted to a specialization of that
concept by prepending a qualification.
So, it would be wrong, terminologically, to define pointer as
"variable".
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|