Home > Development > C++ Slicing

C++ Slicing


Coming from a C# background you never need to worry about issues like as you always pass objects by reference and there is no such thing as copy constructors, assignment operator overloads and the obvious one is that all objects are on the heap meaning that assigning a to b means b and a point to the same thing.

In c++ you have the choice to create an object on the free store or create it on the stack. When objects are store on the stack and a is assigned to b then the copy constructor or the asignment overload will run and copy the object to the other object doing a memberwise / shallow copy.

This becomes a problem when you have a function that takes a base class object without reference semantics. You think that it supports polymorphism but it does not. when you invoke the virtual method it always calls the super classes methods. Why? This is because it was copied to a super class object and all reference to the sub class was lost.

Example as follows:

#include <iostream>
#include <string>

using namespace std;

class Super{
public:
    virtual void printMessage();
};

class Sub : public Super{
public:
    virtual void printMessage();
};

void Super::printMessage(){
    cout << "Super Message" << endl;
}

void Sub::printMessage(){
    cout << "Sub Message" << endl;
}

void evilSlicing(Super s){
    s.printMessage();
}

int main(int argc, char *argv[])
{
    Super* super = new Super();
    super->printMessage();
    delete super;

    Sub* sub = new Sub();
    sub->printMessage();

    Super* pm = new Sub();
    pm->printMessage();

    evilSlicing(*pm);
    return 0;
}

Blair…

Advertisements
Categories: Development Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: