Reputation: 648
I have some code that looks like this:
// original function
size_t computeAverageRating(Movie m) { // take a movie object
// compute average rating
}
// override original function
size_t computeAverageRating(size_t movieIndex) { // take the index of a movie
getMovieObject(movieIndex);
// call original function from here?
}
Is it possible to do what is being described in the comments without creating two separate methods with different names?
Upvotes: 1
Views: 3564
Reputation: 1361
As per my knowledge, if the function is defined in the parent class, then you can't use the same function name with different parameter in child class without overriding the parent class function.
If you want to use then you have to either override the method defined in the parent class, or you need to put the declaration of new function definition in parent class.
ex:
class A
{
public:
size_t computeAverageRating(Movie m) { // take a movie object
// compute average rating
}
};
class B:public A
{
public:
size_t computeAverageRating(Movie m) //this is required
{
A::computeAverageRating(m);
}
size_t computeAverageRating(size_t movieIndex)
{
getMovieObject(movieIndex);
//put your logic here
}
};
or
class A
{
public:
size_t computeAverageRating(Movie m) { // take a movie object
// compute average rating
}
virtual size_t computeAverageRating(size_t movieIndex){};
};
class B:public A
{
public:
size_t computeAverageRating(size_t movieIndex)
{
getMovieObject(movieIndex);
//put your logic here
}
};
Upvotes: 0
Reputation: 324
Should work, its a good method so why do you want to look for another method?
size_t computeAverageRating(size_t movieIndex) {
return computeAverageRating(getMovieObject(movieIndex));
}
Upvotes: 2
Reputation: 36438
Assuming getMovieObject()
actually returns a Movie
(although I'd change computeAverageRating()
to take Movie &m
to avoid copying the object):
size_t computeAverageRating(size_t movieIndex) { // take the index of a movie
Movie m = getMovieObject(movieIndex);
return computeAverageRating( m ) ;
}
Should do it.
Upvotes: 4
Reputation: 3204
What you have there is perfectly fine. The compiler will choose the best function based on the parameters, so for example:
size_t z;
Movie x;
size_t a = computeAverageRating(x);
size_t b = computeAverageRating(z);
Will get the average rating from the first function for a, then the second function for b.
Upvotes: 1