Reputation: 145
I also have a similar design question now in my work assignment. I have a base class like
class base
{
protected:
update()
{
// do some stuff with a and b, call it as action A
}
int a, b;
};
class derived : public base
{
protected:
update()
{
// want to do the same action A , but with varaiables c and d
}
int c, d;
};
and the requirement is, derived class requires both the operations , such as action on "a and b" AND "c and d" aslo. Hence , is it okay to design a method like update(int, int) , so that I can pass parameters as and when required "a and b" AND "c and d" and perform action on them .And I know that I can write a helper method to perform that action, but this action is specific to this class I cant separate it from this. Can I have any other better alternative for this.
In realtime its a bigger class and the action also not on integers ,its on some objects in turn, and the varibales should be related to the class.
Upvotes: 2
Views: 323
Reputation: 264391
Yes that is perfectly valid:
class base
{
protected:
void update()
//^^^^ You forgot the return type.
{
doUpdate(a, b);
}
void doUpdate(int& x, int& y)
{
// do some stuff with x and y
// Because x and y are passed by reference they affect the original values.
}
private: // Should probaly make the member vars private
int a, b;
};
class derived : public base
{
protected:
void update()
//^^^^ You forgot the return type.
{
doUpdate(c, d);
}
private: // Should probaly make the member vars private
int c, d;
};
Upvotes: 2
Reputation: 20730
What you're asking is technically feasible, just define
void update(int& a, int &b)
and inside the update
body forgot about the class memebrs and always refer to the parameters and call it as
update(a,b)
or update(c,d)
.
The point, here, is to understand if update
is really a member function (that requires also to access other member variables) or just a static member (that leaves in the class space, but doesn't see class members itself) and if the relation between the classes is correct (that merely means embedding vs inheritance). But these aspects should be based on consideration other than just the ones related on a single call...
Upvotes: 1
Reputation: 93720
I would revisit whether your class derived
has an is-a relationship (as you show) or a has-a relationship, like this:
class contains
{
protected:
base x, y;
update() { x.update(); y.update(); }
};
Upvotes: 1