Write a short program that shows how to defeat the slicing problem.

What will be an ideal response?

```
// to defeat the slicing problem #include using namespace std; class B {
public:
B():bPtr(new char('B')){ }
virtual void f(){ cout << "B::f() " << *bPtr << endl; }
virtual ~B(){ delete[] bPtr; }
private:
char * bPtr;
};
class D:public B
{
public:
D():B(),dPtr(new char('D')){ }
void f(){ cout << "D::f() " << *dPtr << endl; }
~D() { delete dPtr; }
private:
char * dPtr;
};
int main()
{
B *b1;
B *b = new B;
D *d = new D;
d->f(); // calls D::f()
b->f(); // calls B::f()
b1 = b; // save pointer to memory so I can delete it
b = d;
d->f(); // calls D::f()
b->f(); // calls D::f()
delete d;
delete b1;
}
/*
D::f() D
B::f() B
D::f() D
D::f() D
*/
```

Computer Science & Information Technology

You might also like to view...

During the design process, designers have to make many choices and systems help make these decisions easier

Indicate whether the statement is true or false

Computer Science & Information Technology

private fields of a superclass can be accessed in a subclass

a. by calling private methods declared in the superclass. b. by calling public or protected methods declared in the superclass. c. directly. d. All of the above.

Computer Science & Information Technology