Reputation: 159
class Vec
{
double dim[];
public:
Vec(void);
~Vec(void);
virtual void Add(Vec vector) = 0;
};
I want to replace the Vec
in Vec::Add()
with "any class that inherits from Vec
".
Is there a way to do that?
Upvotes: 1
Views: 159
Reputation: 490108
Change the parameter to a reference to const Vec:
virtual void Add(Vec const &vector) = 0;
A class (publicly) derived from Vec
can be passed by reference to the base class.
Also, since you apparently plan to use Vec
as a base class, you probably want to make its dtor virtual too. Otherwise, if you attempt to destroy an object of the derived type via a pointer or reference to the base, you'll get undefined behavior.
Upvotes: 5
Reputation: 258568
Yes, you pass a pointer or a reference to a Vec
:
class Vec
{
double dim[];
public:
Vec(void);
~Vec(void);
virtual void Add(Vec* vector) = 0;
};
Conversion from a pointer to a class
that derives from Vec
to a Vec*
is implicit.
If you pass by value, you run into object slicing and the behavior won't be what you expect.
Upvotes: 2
Reputation: 26873
Use const reference to Vec, or a pointer to Vec
class Vec
{
double dim[];
public:
virtual void Add(const Vec& vector) = 0;
};
Upvotes: 2