How do you return a pointer to a base class with a virtual function?
Posted
by Nick Sweet
on Stack Overflow
See other posts from Stack Overflow
or by Nick Sweet
Published on 2010-06-17T04:16:40Z
Indexed on
2010/06/17
4:23 UTC
Read the original article
Hit count: 256
I have a base class called Element, a derived class called Vector, and I'm trying to redefine 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' has no member named 'getx'
So, can I define my virtual functions to take Vector& as an argument instead, or is there a way for me to access the data members of Vector through a pointer to Element?
I'm still fairly new to inheritance polymorphism, fyi.
© Stack Overflow or respective owner