Nice trick or illegal construct?

R

rmilh

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
 
I

Ivan Vecerina

rmilh 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? ....
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
 
A

Andre Caldas

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.
 
C

Clark S. Cox III

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.
 

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
474,202
Messages
2,571,057
Members
47,664
Latest member
RoseannBow

Latest Threads

Top