This question is best described in code. I have a class called Vertex
that contains an instance of a class called Params
:
class Params {
virtual Params operator + (Params const& p) = 0;
};
class Vertex {
public:
Params operator + (Params const& ap) const {
return p + ap
};
virtual float eval() = 0;
private:
Params const p;
};
I also have a class called EllParams
which is derived from Params
and EllVertex
which is derived from Vertex
. What I'm wondering is how to deal with the private member variable p
in Vertex
in EllVertex
: I want it to be of type EllParams
. Is there some way of making p
virtual/overriding it? Or should I look to templates for a solution?
Well...you need to initialize the Params
in Vertex
somehow. So make it a parameter on the Vertex
constructor. Then your EllVertex
will pass an EllParams
to the parent constructor from its constructor and that will be how the private Vertex.p
is initialized.
For example:
class Params {
virtual Params operator + (Params const& p) = 0;
};
class Vertex {
public:
Params operator + (Params const& ap) const {
return *p + ap
};
virtual float eval() = 0;
protected:
Vertex(Params* inputParams) : p(inputParams) {}
private:
Params* const p;
};
Notice that I have changed your p
member variable to a pointer. That way, you don't have to ensure that a correct copy constructor is defined for Params
or any subclasses.
This question is best described in code. I have a class called Vertex
that contains an instance of a class called Params
:
class Params {
virtual Params operator + (Params const& p) = 0;
};
class Vertex {
public:
Params operator + (Params const& ap) const {
return p + ap
};
virtual float eval() = 0;
private:
Params const p;
};
I also have a class called EllParams
which is derived from Params
and EllVertex
which is derived from Vertex
. What I'm wondering is how to deal with the private member variable p
in Vertex
in EllVertex
: I want it to be of type EllParams
. Is there some way of making p
virtual/overriding it? Or should I look to templates for a solution?
Well...you need to initialize the Params
in Vertex
somehow. So make it a parameter on the Vertex
constructor. Then your EllVertex
will pass an EllParams
to the parent constructor from its constructor and that will be how the private Vertex.p
is initialized.
For example:
class Params {
virtual Params operator + (Params const& p) = 0;
};
class Vertex {
public:
Params operator + (Params const& ap) const {
return *p + ap
};
virtual float eval() = 0;
protected:
Vertex(Params* inputParams) : p(inputParams) {}
private:
Params* const p;
};
Notice that I have changed your p
member variable to a pointer. That way, you don't have to ensure that a correct copy constructor is defined for Params
or any subclasses.
0 commentaires:
Enregistrer un commentaire