Freddy Pierson
Freddy Pierson

Reputation: 443

Calling Base Class Functions with Inherited Type

I can't describe exactly what I want to say but I want to use base class functions with an inherited type. Like I want to declare "Coord3D operator + (Coord3D);" in one class, but if I use it with Vector3D operands, I want it to return Vector3D type instead of Coord3D.

With this line of code below, I add two Vector3D's and get a Coord3D in return, as told to me by the typeid().name() function. How do I reorganize my classes so that I get a Vector3D on return?

#include <iostream>
#include <typeinfo>
using namespace std;

class Coord3D
{
public:
        float x, y, z;
        Coord3D (float = 0.0f, float = 0.0f, float = 0.0f);
        Coord3D operator + (Coord3D &);
};

Coord3D::Coord3D (float a, float b, float c)
{
        x = a;
        y = b;
        z = c;
}

Coord3D Coord3D::operator+ (Coord3D &param)
{
        Coord3D temp;
        temp.x = x + param.x;
        temp.y = y + param.y;
        temp.z = z + param.z;
        return temp;
}

class Vector3D: public Coord3D
{
public:
        Vector3D (float a = 0.0f, float b = 0.0f, float c = 0.0f)
        : Coord3D (a, b, c) {};
};

int main ()
{
        Vector3D a (3, 4, 5);
        Vector3D b (6, 7, 8);
        cout << typeid(a + b).name();
        return 0;
}

Upvotes: 0

Views: 145

Answers (1)

Suedocode
Suedocode

Reputation: 2534

The functionality you want is in the base class, but it returns a base class (which makes sense since the Coord3D has no idea what a Vector3D is). If you are adamant about not rewriting operator+() for Vector3D (which I think is fair if you plan to have multiplication and such as well), you can instead create a copy constructor in the Vector3D class that can construct a Vector3D from the Coord3D result.

class Vector3D: public Coord3D
{
public:
        Vector3D (float a = 0.0f, float b = 0.0f, float c = 0.0f)
        : Coord3D (a, b, c) {};

        Vector3D (const Coord3D& param){ new ((Coord3D*)this) Coord3D(param); }
};

int main ()
{
        Vector3D a (3, 4, 5);
        Vector3D b (6, 7, 8);
        Vector3D c = a + b;
        cout << typeid(c).name();
        Sleep(1000);
        return 0;
}

Upvotes: 1

Related Questions