Write a short program that shows how to defeat the slicing problem.
What will be an ideal response?
```
// to defeat the slicing problem #include
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
*/
```
You might also like to view...
If you would like to add data from an Excel spreadsheet to an existing Access table, you might use a(n) ________ query
Fill in the blank(s) with correct word
In Project 2013, the default for a duration of one day is ________ hours
A) 6 B) 7 C) 8 D) 10
The Navigation pane displays graphical representations of pages called:
A) locks. B) thumbnails. C) icons. D) hyperlinks.
On a personal computer with Windows Vista Premium, the ipconfig command is entered in the ____________________ window.
Fill in the blank(s) with the appropriate word(s).