Hiding class pointers -- was it a good idea?

Walter Bright newshound1 at digitalmars.com
Wed Aug 15 14:48:26 PDT 2007


Johan Granberg wrote:
> Russell Lewis wrote:
>> I don't see any fundamental reason why classes need to
>> be reference types, other than history.
> 
> What about this situation.
> 
> //begin C++
> 
> class A{
>         int val;
> };
> class B:public A{
>         int foo;
> };
> 
> int main(int argc,char**argvs){
>         A a;
>         B b;
>         a=b;//HERE what happens to b's member foo?
> }
> 
> //end C++
> 
> it's my impression that D's classes are reference types to avoid that
> specific problem.

That's known as the 'slicing' problem. It's pernicious in that it can be 
extremely hard to expose via testing or code reviews, yet will expose 
the program to unpredictable behavior.

While it is fairly obvious in your example that it is wrong, it can 
occur in cases that are *impossible* for the compiler to detect:

	void foo(A* a)
	{
		A ax = *a;
	}

	void main()
	{
		B b;
		foo(&b);
	}

This kind of error is impossible in D.



More information about the Digitalmars-d mailing list