0

I have an explicit function that takes a reference to the base type of a class. What is the proper way to pass that in?

I am currently doing a static cast:

#include <iostream>

using namespace std;

struct Base
{
    Base() { cout << "Base Constructor" << endl; }
    Base(Base const& c) { cout << "Base-Base Constructor" << endl; }
};

struct Derived : public Base
{
    Derived() { cout << "Derived Constructor" << endl; }
    explicit Derived(Base const& c) { cout << "Derived-Base Constructor" << endl; }
    Derived(Derived const& c) { cout << "Derived-Derived Constructor" << endl; }
};

int main()
{
    Base B;
    cout << "\n";
    Derived D;
    cout << "\n";
    Base* test1 = new Derived(D);
    cout << "\n";
    Base* test3 = new Derived(static_cast<Base>(D));
    cout << "\n";
    Base* test2 = new Derived(B);
    cout << "\n";


    return 0;
}

but that calls the copy constructor of the base class.

I could pass *static_cast<Base*>(&D), but that seems a bit hackish. I feel like I am just overlooking a simple way to do this. Thanks.

Cory-G
  • 1,025
  • 14
  • 26

1 Answers1

5

Use this:

static_cast<Base&>(D)

Or this:

static_cast<const Base&>(D)
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
IdeaHat
  • 7,641
  • 1
  • 22
  • 53