Question: I am having trouble using virtual functions with objects declared using automatic storage duration. Here is a reproducible scenario:

```
#include <iostream>

class A {
    public:
        A() {}
        virtual ~A() {}
        virtual void printClassName() {
            std::cout << "A" << std::endl;
        }
};

class B : public A {
    public:
        B() : A() {}
        ~B() {}
        void printClassName() {
            std::cout << "B" << std::endl;
        }
};

class Test {
    private:
        A item;

    public:
        Test() {}
        ~Test() {}
        void setItem(A item) {
            this->item = item;
        }
        A getItem() {
            return this->item;
        }
};

int main() {
    Test t;
    B item;

    t.setItem(item);
    t.getItem().printClassName();

    return 0;
}

```

This prints "A", while I would expect it to print B. I'm curious as to why.

Thank you in advance!

Answer: 
You're [slicing](https://stackoverflow.com/q/274626/2069064) here:

```
void setItem(A item) {
    this->item = item;
}

```

The `B` part is sliced off when you pass `item` into `setItem()`, so you're losing the base part of this. If `A` were abstract, this would be a more obvious error (since you can't store an abstract class by value). 

Instead, you'll want to to store the item as a pointer.
Just to make it clear, to avoid object slicing in this case you should change `void setItem(A item)` to `void setItem(A& item)` and `A getItem()` to
`A& getItem()`. 

This (passing/returning by reference) preserves dynamic types and is almost certainly what you would intend in this case

**EDIT:** I overlooked the fact that the object you're storing is also of type `A`. This cannot work. You need to have it as a pointer in order for it to be able to have a different dynamic type from its static type (or reference, but then it would have to be initialised in the constructor).

So to change to using a pointer, you could try to change `A item` in `Test` to `A* item`. Then set/get become:

```
    void setItem(A& item) {
        this->item = &item;
    }
    A& getItem() {
        return *(this->item);
    }

```

This gives you the desired output. This is OK if you're just testing polymorphic behaviour, but would need to be considered very careful for an actual design (for example you may want to consider whether there should be shared ownership using `std::shared_ptr`).