MSDN const_cast sample

G

George2

Hello everyone,


In MSDN sample for const_cast,

http://msdn2.microsoft.com/en-us/library/bz6at95h(VS.80).aspx

There is a statement like this,

--------------------
On the line containing the const_cast, the data type of the this
pointer is const CCTest *. The const_cast operator changes the data
type of the this pointer to CCTest *
--------------------

I think in a const member function, like void printNumber() const, the
type of this pointer is const pointer to current type, so we use this
const_cast to remove its const properties.

For a non-const member function, I think this pointer should not be a
const pointer, right?

So, conclusion is,

1. in const member function, this pointer is a const pointer;
2. in non-const member function, this pointer is a non-const pointer.

Right?


thanks in advance,
George
 
J

Jim Langston

George2 said:
Hello everyone,


In MSDN sample for const_cast,

http://msdn2.microsoft.com/en-us/library/bz6at95h(VS.80).aspx

There is a statement like this,

--------------------
On the line containing the const_cast, the data type of the this
pointer is const CCTest *. The const_cast operator changes the data
type of the this pointer to CCTest *
--------------------

I think in a const member function, like void printNumber() const, the
type of this pointer is const pointer to current type, so we use this
const_cast to remove its const properties.

For a non-const member function, I think this pointer should not be a
const pointer, right?

So, conclusion is,

1. in const member function, this pointer is a const pointer;
2. in non-const member function, this pointer is a non-const pointer.

Right?

My simple test (which may or may not work in your implementation) seems to
suggest this.

Output is:
class Foo *
class Foo const *

#include <iostream>

class Foo
{
public:
void ShowType() { std::cout << typeid(this).name() << "\n"; }
void ShowTypeConst() const { std::cout << typeid(this).name() << "\n"; }
private:
};

int main()
{
Foo Bar;
Bar.ShowType();
Bar.ShowTypeConst();
}

But, yes, in a const member function, the this* is const.
 
V

Victor Bazarov

Jim said:
[..]

But, yes, in a const member function, the this* is const.

I'd probably say that "the *this is const". I am sure you
meant to dereference the pointer.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top