Reputation: 35982
Saw the following code in the project:
class Base
{
...
virtual double Function(int i) const;
...
};
class SubClass : public Base
{
virtual double Function(int i) const;
double Function(std::vector<int> vecInts) const;
double Function(std::map<int> mapInts) const;
};
I don't feel comfortable about this design. I knew we should avoid overload virtual functions but here the case is a little different.
Question> Is there a design flaw here?
Thank you
Upvotes: 5
Views: 343
Reputation: 206546
It is not a design flaw. It is perfectly fine.
int
as argument) will be called depending on actual type of the object(Last 3 outputs in below sample).Consider the sample program to make it clearer:
#include<iostream>
class Base
{
public:
virtual double Function(int i) const{std::cout<<"\nIn Base int version";}
};
class SubClass : public Base
{
public:
virtual double Function(int i) const{std::cout<<"\nIn Derived int version";}
double Function(std::string str) const{std::cout<<"\nIn Derived string version";}
double Function(double i) const {std::cout<<"\nIn Derived double version";}
};
int main()
{
SubClass obj;
obj.Function(10);
obj.Function(10.1);
obj.Function("Hello");
Base Bobj;
Bobj.Function(10.2);
Base *ptr = new Base;
ptr->Function(10.5);
Base *ptr2 = new SubClass;
ptr2->Function(10);
ptr2->Function(10.5);
delete ptr;
delete ptr2;
return 0;
}
The output is:
In Derived int version
In Derived double version
In Derived string version
In Base int version
In Base int version
In Derived int version
In Derived int version
Notice the last two outputs in specific,.
Upvotes: 3
Reputation: 5477
There is no flaw. From Effective C++, item 34:
Pure virtual functions specify inheritance of interface only.
Simple (impure) virtual functions specify inheritance of interface plus inheritance of a default implementation.
Non-virtual funcitons specify inheritance of interface plus inheritance of a mandatory implementation.
Since Function(int i) is a virtual function and not a Non-virtual function, its default implementation may be overriden in the base class. If it would be a Non-virtual function, it would then be a mandatory implementation, not to be overriden, to ensure the "is-a" relationship in the class hierarchy.
Upvotes: 1
Reputation: 258618
Nope, it's okay. Overloading virtual
functions is fine. Hiding virtual functions is what you should be cautious about.
In your case, you're overriding the base version and providing two more overloads. So no hiding occurs.
Upvotes: 8