Topic: Conversion "Derived to Base" inconsistent?
Author: jarausch@igpm.rwth-aachen.de (Helmut Jarausch)
Date: 25 Mar 1994 11:12:29 GMT Raw View
Dear experts,
according to the ARM a Derived& (or Derived*) is (automatically)
converted to Base& (Base*,resp.).
Shouldn't the rule be changed such that a Derived& (or Derived*) is
converted to const Base& (const Base*,resp.) ?
The reason for this suggestion is the following tiny example
which breaks the type security of C++. In case the rule had been changed
as suggested this example would not work any more.
Thank you for your comments.
class B
{ int U;
public:
int P;
B( int Ui ) { U= Ui; }
};
class D : public B
{ int V;
public:
D( int Di, int Vi ) : B(Di) { V= Vi; }
};
void assign( B& Y, const B& Z )
{ Y= Z; }
int main()
{ B ObjB(1);
D ObjD(1,2);
ObjB= ObjD;
// ObjD= ObjB; // this is an error !
assign(ObjD, ObjB); // but not this one !!!
}
Helmut Jarausch
Institute of Technology
RWTH Aachen
Germany
Author: ah657@FreeNet.Carleton.CA (Michael Whiten)
Date: Sat, 26 Mar 1994 03:28:51 GMT Raw View
In a previous article, jarausch@igpm.rwth-aachen.de (Helmut Jarausch) says:
>
>class B
>{ int U;
> public:
> B( int Ui ) { U= Ui; }
>};
>
>class D : public B
>{ int V;
> public:
> D( int Di, int Vi ) : B(Di) { V= Vi; }
>};
>
>void assign( B& Y, const B& Z )
>{ Y= Z; }
>
>int main()
>{ B ObjB(1);
> D ObjD(1,2);
> ObjB= ObjD;
>// ObjD= ObjB; // this is an error !
> assign(ObjD, ObjB); // but not this one !!!
>}
The call to assign has the same effect as:
(B&) ObjD = ObjB;
in other words, you have invoked the base class assignment operator.
The type safety system was never in jeopardy.
- Mike
--