By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,171 Members | 1,004 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

Nice trick or illegal construct?

P: n/a

As you can see in this example the coder did't think it is necessary
to have an instance of a Derived to be able to set Base member prot.
Is it legal?

class Base
{
protected:

int prot;
};

class Derived : public Base
{
public:

using Base::prot;
};

int main()
{
Base base;
//instance of derived not needed to access protected member?
static_cast<Derived&>(base).prot = 1;
return 0;
}

Robert Milharcic
Jul 23 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
"rmilh" <rm***@mailaddr.com> wrote in message
news:uq********************************@4ax.com...
As you can see in this example the coder did't think it is necessary
to have an instance of a Derived to be able to set Base member prot.
Is it legal? .... Base base;
//instance of derived not needed to access protected member?
static_cast<Derived&>(base).prot = 1;


Not a good idea.
Formally, casting a base class instance as a derived type triggers
undefined behavior (even though the above code is likely to work
"as expected" on many platforms).
Cheers, Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 23 '05 #2

P: n/a
rmilh wrote:
static_cast<Derived&>(base).prot = 1;


dynamic_cast is more appropriate for classes
Jul 23 '05 #3

P: n/a
Hello!
Is it legal?

class Base *snip*
class Derived : public Base *snip*
int main()
{
Base base;
//instance of derived not needed to access protected member?
static_cast<Derived&>(base).prot = 1;
return 0;
}


This only works because Base starts at the "begining" of Derived. If you
had:
class Derived: public A, public Base, public C
{
...
}

Then I think it would not work.

Andre Caldas.
Jul 23 '05 #4

P: n/a
On 2005-04-09 02:22:37 -0400, rmilh <rm***@mailaddr.com> said:

As you can see in this example the coder did't think it is necessary
to have an instance of a Derived to be able to set Base member prot.
Is it legal?
No.
class Base;
class Derived : public Base; Base base;
static_cast<Derived&>(base)


Your cast is undefined behavior.

--
Clark S. Cox, III
cl*******@gmail.com

Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.