'Passing a subclass as constant reference [duplicate]

I want something akin to the following situation:

#include <iostream>
#include <string>

class Parent
{
protected:
        std::string extras = "";
public:
        virtual void print() const {std::cout << "I am the parent" << extras << std::endl;}
        virtual void setYay() {extras = ", YAY!";}
};


class Son : public Parent
{
public:
        virtual void print() const {std::cout << "I am the son" << extras << std::endl;}
};


class Daughter : public Parent
{
public:
        virtual void print() const {std::cout << "I am the daughter" << extras << std::endl;}
};

const void printer(const Parent& p)
{
        p.print();
}

Parent childCreator(std::string name)
{
        if (name.compare("Alice")) return Daughter();
        if (name.compare("Bob")) return Son();
        return Parent();
}

int main(void)
{
        Parent p = childCreator("Alice");
        p.setYay();
        printer(p);
}

I am aware that the code above will not work as intend it, since p in main will be of type Parent. However, I am unsure how to use pointers/references to get the desired effect. I could use pointers in main, but I want to ensure printer does not change the objects passed. What should I pass to printer to get the desired behavior (i.e. printer printing the correct child method, while ensuring const-ness)?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source