static_cast confusion

static_cast confusion

Post by Chandra Sh » Thu, 26 Jun 2003 07:49:29


> Derived& Derived::operator=(const Derived& inDerived)

coz, static_cast<Base> results into creation of a temporary obj of type Base


this is same as *(static_cast<Base*>(this)) = inDerived;


yes, u r right, see the above. but ideally u shud use dynamic_cast for
polymorphic classes..
 
 
 

static_cast confusion

Post by buds » Thu, 26 Jun 2003 19:36:23

Hi all,

Following is the assigment operator of a derived class

Derived& Derived::operator=(const Derived& inDerived)
{
//to assign to the base class object the following statement

static_cast<Base&>(*this)=inDerived;//works fine

static_cast<Base> (*this)=inDerived;//calls the base class copy constructor.

*((Base*)this) = inDerived;//works fine

return (*this);
}

I thought the static_cast was equivalent to the C-style cast.
Then why this behavior. Can anyone please help me with this

TIA
Buds

 
 
 

static_cast confusion

Post by Rolf Magnu » Thu, 26 Jun 2003 19:39:23


This invokes the base class's assignment operator.


Right.


With this, you tell the compiler "hey, I know that 'this' is a pointer
to Derived, but that's not really true. Actually it's a Base, so treat
the pointer as if it were a Base.". It's equivalent to:

*reinterpret_cast<Base*>(this) = inDerived;//works fine

Don't expect that to work generally.


No. The C style cast is equivalent to any combination of static_cast,
const_cast and reinterpret_cast that would be needed for the specific
conversion.
 
 
 

static_cast confusion

Post by Rolf Magnu » Thu, 26 Jun 2003 21:01:03


Hmm. I guess I was wrong then.


Why? You need dynamic_cast to cast from base to derived, not the other
way round.
 
 
 

static_cast confusion

Post by Ron Natali » Thu, 26 Jun 2003 23:57:41


You are wrong. Some C style casts are NOT the same as static_cast (but it's
immaterial here).


The base class copy constructor is called because in order to cast Derived
to Base, a temporary Base object is created and that is what is assigned into.
 
 
 

static_cast confusion

Post by Ron Natali » Fri, 27 Jun 2003 00:00:21


\
Huh? The C cast should do a static cast here. The cast works generally
provided that Base is a public base class of Derived.
 
 
 

static_cast confusion

Post by Rolf Magnu » Fri, 27 Jun 2003 00:21:48


Yes, I think you're right. Sorry.
 
 
 

static_cast confusion

Post by Mirek Fidl » Sat, 28 Jun 2003 23:54:40


"buds" < XXXX@XXXXX.COM > pe v diskusn prpevku

constructor.

It is. Problem is that second static_cast transforms into

(Base)(*this) = inDerived;

which, following rules for casting is equivalent for

Base(*this) = inDerived;

which means "create temporary object of Base type using Base(const
Base&) copy constructor and use its operator= .

Mirek