0
Follow
0
View

Get properties of derived class from base class argument

dickens_csl 注册会员
2023-01-24 23:40

You need to define a virtual function "bool amIaB()" in both base and derived class that returns "isB".

hyf19861005 注册会员
2023-01-24 23:40

My recommendation is that you use polymorphism by creating a virtual "print" function that your global Print function calls:

class A
{
    int x = 69;

public:
    virtual ~A() = default;  // Needed for polymorphic classes

    virtual void print(std::ostream& out) const
    {
        out << x;
    }
};

class B : public A
{
    int y = 420;

public:
    void print(std::ostream& out) const override
    {
        out << y;
    }
};

void Print(A const& o)
{
    o.print(std::cout);
    std::cout << std::endl;
}

int main()
{
    A a;
    B b;

    Print(a);
    Print(b);
}

About the Author

Question Info

Publish Time
2023-01-24 23:40
Update Time
2023-01-24 23:40

Related Question