How do you return a pointer to a base class with a virtual function?

I have an Element base class, a derived class called Vector, and I'm trying to override two virtual functions from Element in Vector.

//element.h
template <class T>
class Element
{
public:
Element();

virtual Element& plus(const Element&);
virtual Element& minus(const Element&);
};

and in another file

//Vector.h
#include "Element.h"

template <class T>
class Vector: public Element<T> {
T x, y, z;

public:

//constructors
Vector();
Vector(const T& x, const T& y = 0, const T& z =0);
Vector(const Vector& u);

...

//operations
Element<T>& plus(const Element<T>& v) const;
Element<T>& minus(const Element<T>& v) const;
... 

};

//sum
template <class T>
Element<T>& Vector<T>::plus(const Element<T>& v) const
{
Element<T>* ret = new Vector((x + v.x), (y + v.y), (z + v.z));
return *ret;
}

//difference
template <class T>
Element<T>& Vector<T>::minus(const Element<T>& v) const
{
Vector<T>* ret = new Vector((x - v.x), (y - v.y), (z - v.z));
return *ret;
}

but i always get

error: 'const class Element' does not have a member named 'x'

So, can I define my virtual functions for accepting Vector & as an argument, or is there a way to access Vector data elements via a pointer to an element?

I'm still pretty new to inheritance polymorphism, fyi.

EDIT: static_cast ( ) - . , , : : "const class Element" "x"

:   //       & Vector:: plus (const Element & v) const   {    * ret = static_cast * > ( new ((x + v.x), (y + v.y), (z + v.z)));   return * ret;   }

//difference 
template <class T> 
Element<T>& Vector<T>::minus(const Element<T>& v) const 
{ 
Element<T>* ret = new Vector<T>(static_cast<Vector*>((x - v.x), (y - v.y), (z - v.z)));
return *ret; 
} 

, , , . ?

+1
2

, : Element - 'x', x Vector, . :

Element<T>& plus(const Element<T>& v) const     {
const Vector<T> & vect = dynamic_cast<const Vector<T> &>(v);
Vector<T>* ret = new Vector((x + vect.x), (y + vect.y), (z + vect.z));
return *ret;
}

: , .

+1

Vector &

; , .

Vector ?

, Element& Vector&, static_cast, dynamic_cast.

static_cast, , Vector. , , Vector&.

dynamic_cast, , Vector:

const Vector<T>& w = dynamic_cast<const Vector<T>&>(v);

, , Vector , std::bad_cast. ( ), cast null .

, , , : , .

+1

Source: https://habr.com/ru/post/1750915/


All Articles