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.
This phenomenon is called **object slicing**.

Basically, when you are passing `item` (of type `B`) to `setItem` (which takes a `A`), you are losing *every* information of `B`, because a `B` cannot be stored in a `A`.

So, when you call `printClassName`, it only knows about that function from `A`, so it calls it from `A`.

---

One possible solution is to pass pointers to the objects, instead of the raw data. This will call `printClassName` of `B` in your example, because no slicing occurs.