rxu rxu - 3 months ago 7
C++ Question

a Function that accepts both a class and a derived class as the argument

How to make a function F that accepts both a class A, and a class B derived from A, for its only argument?

The constructors and destructors for class A and class B are different.

Answer

Declare the argument like reference or const reference to an object of class A.

class A
{
    //...
};

class B : public A
{
    //...
};

void f( const A &a );

or

void f( const A *a );

Or like an rvalue reference.

Here is a demonstrative program

#include <iostream>
#include <string>

struct A
{
    virtual ~A() = default;
    A( const std::string &first ) : first( first ) {}
    virtual void who() { std::cout << first << std::endl; }
    std::string first;
};

struct B : A
{
    B( const std::string &first, const std::string &second ) : A( first ), second( second ) {}
    void who() { A::who(); std::cout << second << std::endl; }
    std::string second;
};

void f( A &&a )
{
    a.who();
}

int main() 
{
    f( A( "A" ) );
    f( B( "A", "B" ) );

    return 0;
}

Its output is

A
A
B