Calling Base Class Functions with Inherited Type
Posted
by
Kein Mitleid
on Stack Overflow
See other posts from Stack Overflow
or by Kein Mitleid
Published on 2013-06-27T21:06:16Z
Indexed on
2013/06/27
22:21 UTC
Read the original article
Hit count: 223
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 ¶m)
{
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;
}
© Stack Overflow or respective owner