C++ Blog

Saturday, October 08, 2005

What is “Slicing Problem”?

class base {}
class derived: public base {}

class base baseObj;
class derived derivedObj;

baseObj = derivedObj;
/* Only baseObj features will be copied leaving all the extra features in derivedObj this is called slicing */

derivedObj = baseObj;
/* Down slicing only baseObj features will copied and all the others will have unknown values, this is not safe to do this and C++ provides an casting operator for doing this, it is called as dynamic_cast */

Pass by Reference

There will not be any splicing if we pass by reference. Slicing normally happens when one object is assigned to another. If we pass a value by reference then there is no assignment that is taking place and the objects themselves get passed as an argument. So there will be no slicing.

Slicing is not related to pointers or members, it is related with objects themselves.

What one should take care, when writing a C++ class with pointer members?

a. Mainly constructor, Copy constructor (for deep copy), assignment operator and destructor,
b. If a class which has pointer members is inherited then the destructor should be made virtual.
c. Memory leak is the main concern so de-allocation of memory is really import if there is a pointer member.

Difference between new and malloc?

1. When new is used, class constructor will be called but malloc don’t know anything about class so it just allocates chunk of bytes.
2. One disadvantage of new is that there is no way to reallocate memory. With malloc you can use realloc to extend the amount of memory.
3. new returns pointer to the object type, but malloc returns void *
4. When malloc failed to allocate memeory it returns a NULL value, but if new fails to allocate memory it throws an exception.
5. new gurantees allocating memory equivalent to the size of the object or required size.
For example;
Obj* obj = (Obj*)malloc(sizeof(int*3)); // This is allowed syntax but it may not be satisfying the memory requirement of Obj
6. new is an operator can be overloaded.