Slicing problem when copying derived class

A pointer to a derived class implicitly converts to a pointer to its public base class. When applied to a copy operation, this simple and necessary rule leads to a trap for the unwary. Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct Base {
 int b; 
Base(const Base&); 
// ... 
}; 
struct Derived : Base 
{ 
int d; 
Derived(const Derived&); 
// ... 
};
 
void naive(Base∗ p) 
{ Bb2=∗p; //mayslice: invokes Base::Base(const Base&) 
// ... 
} 
void user() 
{ 
Derived d; 
naive(&d); 
Base bb = d; // slices: invokes Base::Base(const Base&), not Derived::Der ived(const Derived&) 
// ... 
}


The above para is from The C++ Programming Language book, 4th edition. Now why this problem only to copy operations. Doesn't this issue occur for move operations?
Topic archived. No new replies allowed.