The Wayback Machine - https://web.archive.org/web/20241124165435/https://www.geeksforgeeks.org/does-overloading-work-with-inheritance/
Open In App

Does overloading work with Inheritance?

Last Updated : 20 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: 

C++
 
#include <iostream>
using namespace std;
class Base
{
public:
    int f(int i)
    {
        cout << "f(int): ";
        return i+3;
    }
};
class Derived : public Base
{
public:
    double f(double d)
    {
        cout << "f(double): ";
        return d+3.3;
    }
};
int main()
{
    Derived* dp = new Derived;
    cout << dp->f(3) << '\n';
    cout << dp->f(3.3) << '\n';
    delete dp;
    return 0;
}

The output of this program is: 

f(double): 6.3
f(double): 6.6

Instead of the supposed output: 

f(int): 6
f(double): 6.6

Overloading doesn’t work for derived class in the C++ programming language. There is no overload resolution between Base and Derived. The compiler looks into the scope of Derived, finds the single function “double f(double)” and calls it. This is name hiding, and not overloading it never disturbs the (enclosing) scope of Base. In C++, there is no overloading across scopes and derived class scopes are not an exception to this general rule. (See this for more examples)

Reference: technical FAQs on www.stroustrup.com 

Now consider the Java version of this program: 

Java
class Base
{
    public int f(int i)
    {
        System.out.print("f (int): ");
        return i+3;
    }
}
class Derived extends Base
{
    public double f(double i)
    {
        System.out.print("f (double) : ");
        return i + 3.3;
    }
}
class myprogram3
{
    public static void main(String args[])
    {
        Derived obj = new Derived();
        System.out.println(obj.f(3));
        System.out.println(obj.f(3.3));
    }
}

The output of the above program is: 

f (int): 6
f (double): 6.6


So in Java, overloading works across scopes, contrary to C++. The Java compiler determines the correct version of the overloaded method to be executed at compile time based upon the type of arguments used to call the method and the parameters of the overloaded methods of both these classes that receive the values of arguments used in call and executes that overloaded method.

Finally, let us try to get the output of the following C# program: 

C#
 
using System;                     
class Base
{
    public int f(int i)
    {
        Console.Write("f (int): ");
        return i + 3;
    }
}
class Derived : Base
{
    public double f(double i)
    {
        Console.Write("f (double) : ");
        return i+3.3;
    }
} 
class MyProgram
{   
    static void Main(string[] args)
    {
        Derived obj = new Derived();
        Console.WriteLine(obj.f(3));
        Console.WriteLine(obj.f(3.3));
        Console.ReadKey(); // write this line if you use visual studio
    }
}

Note: Console.ReadKey() is used to halt the console. It is similar to getch() in C/C++. 
The output of the above program is: 

f(double) : 6.3
f(double): 6.6

Instead of the assumed output: 

f(int) : 6
f(double) : 6.6

Explanation: Here, the object we are creating is of the derived class, so the compiler will give preference to the derived class first and will perform implicit type casting if needed. So as soon as the compiler comes to “Console.WriteLine(obj.f(3));”, it will check for parameter compatibility. Here, the value 3 is of type int which is compatible with the parameter type double of derived class function f. So the compiler will perform the implicit type conversion of int to double. Hence the output f(double) : 6.3 will come. 

Now when the compiler comes to “Console.WriteLine(obj.f(3.3));”, again it will give preference to the derived class first and will find it callable. So it will evaluate the derived class function f. Hence the output f(double): 6.6 will come.

Now let’s take another case where we are putting the base class function f into derived class and vice-versa as shown below:

C#
using System;                     
class Base 
{ 
    public double f(double i) 
    { 
        Console.Write("f (double) : "); 
        return i+3.3; 
    } 
} 

class Derived : Base 
{ 

    public int f(int i) 
    { 
        Console.Write("f (int): "); 
        return i + 3; 
    } 
    
} 

class MyProgram 
{ 
    static void Main(string[] args) 
    { 
        Derived obj = new Derived(); 
        Console.WriteLine(obj.f(3)); 
        Console.WriteLine(obj.f(3.3)); 
        Console.ReadKey(); // write this line if you use visual studio 
    } 
} 

Output: 

f (int): 6
f (double) : 6.6

Are you shocked to see the expected output? How is it possible? 
Well, we have an answer to these questions. As the object we have created is of the derived class, the C# compiler will give first preference to derived and if it does not find any compatibility, then it goes for the base class. So when the compiler comes to “Console.WriteLine(obj.f(3));”, it will check the derived class method f and finding it callable, the compiler will execute this and the output f (int): 6 comes. Now when the compiler comes to “Console.WriteLine(obj.f(3.3));”, it will check the derived class method and find out that it is not suitable as the value 3.3 (double) is not compatible with the int data type. Hence the compiler will now prefer the base class and there it will find the best match, so it will execute that one. So the output for that one will be f (double) : 6.6.

The reason is the same as explained in the case of the C++ program. In C#, just like in C++, there is no overload resolution between class Base and class Derived. Also, there is no overloading across scopes and derived class scopes are not an exception to this general rule. This is same as C++ because C# is designed to be much closer to C++, according to Anders Hejlsberg, the creator of the C# language.


 



Previous Article
Next Article

Similar Reads

Does C support function overloading?
First of all, what is function overloading? Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java. But C doesn't support this feature not because of OOP, but rather because
2 min read
How does Duff's Device work?
Duff’s device is a trick to express loop unrolling directly in C or C++ without extra code to treat the leftover partial loop.The trick is to use a switch statement where all but one of the cases labels are in the middle of a while loop. Further, all cases fall through to the end of the while loop. Despite the impression, it makes Duff’s device is
6 min read
C++ | Operator Overloading | Question 10
How can we restrict dynamic allocation of objects of a class using new? (A) By overloading new operator (B) By making an empty private new operator. (C) By making an empty private new and new[] operators (D) By overloading new operator and new[] operators Answer: (C) Explanation: If we declare new and [] new operators, then the objects cannot be cr
1 min read
C++ | Operator Overloading | Question 2
Which of the following operators cannot be overloaded (A) . (Member Access or Dot operator) (B) ?: (Ternary or Conditional Operator ) (C) :: (Scope Resolution Operator) (D) .* (Pointer-to-member Operator ) (E) All of the above Answer: (E) Explanation: See What are the operators that cannot be overloaded in C++?Quiz of this Question
1 min read
C++ | Function Overloading and Default Arguments | Question 5
Which of the following in Object Oriented Programming is supported by Function overloading and default arguments features of C++. (A) Inheritance (B) Polymorphism (C) Encapsulation (D) None of the above Answer: (B) Explanation: Both of the features allow one function name to work for different parameter. Quiz of this Question
1 min read
C++ | Function Overloading and Default Arguments | Question 2
Output? #include<iostream> using namespace std; int fun(int x = 0, int y = 0, int z) { return (x + y + z); } int main() { cout << fun(10); return 0; } (A) 10 (B) 0 (C) 20 (D) Compiler Error Answer: (D) Explanation: All default arguments must be the rightmost arguments. The following program works fine and produces 10 as output. #include
1 min read
C++ | Function Overloading and Default Arguments | Question 3
Which of the following overloaded functions are NOT allowed in C++? 1) Function declarations that differ only in the return type int fun(int x, int y); void fun(int x, int y); 2) Functions that differ only by static keyword in return type int fun(int x, int y); static int fun(int x, int y); 3)Parameter declarations that differ only in a pointer * v
1 min read
C++ | Function Overloading and Default Arguments | Question 4
Predict the output of following C++ program. include<iostream> using namespace std; class Test { protected: int x; public: Test (int i):x(i) { } void fun() const { cout << "fun() const " << endl; } void fun() { cout << "fun() " << endl; } }; int main() { Test t1 (10); const Test t2 (20); t1.fun(); t
1 min read
C++ | Operator Overloading | Question 3
Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written? 1) Comparison Operator ( == ) 2) Assignment Operator ( = ) (A) Both 1 and 2 (B) Only 1 (C) Only 2 (D) None of the two Answer: (C) Explanation: Assign operator is by default available in all user defined classes even
1 min read
C++ | Function Overloading and Default Arguments | Question 5
Output of following program? #include <iostream> using namespace std; int fun(int=0, int = 0); int main() { cout << fun(5); return 0; } int fun(int x, int y) { return (x+y); } (A) Compiler Error (B) 5 (C) 0 (D) 10 Answer: (B) Explanation: The statement "int fun(int=0, int=0)" is declaration of a function that takes two arguments with de
1 min read
C++ | Operator Overloading | Question 4
Which of the following operators should be preferred to overload as a global function rather than a member method? (A) Postfix ++ (B) Comparison Operator (C) Insertion Operator << (D) Prefix++ Answer: (C) Explanation: cout is an object of ostream class which is a compiler defined class. When we do "cout << obj" where obj is an obje
1 min read
C++ | Operator Overloading | Question 6
Predict the output #include<iostream> using namespace std; class A { int i; public: A(int ii = 0) : i(ii) {} void show() { cout << i << endl; } }; class B { int x; public: B(int xx) : x(xx) {} operator A() const { return A(x); } }; void g(A a) { a.show(); } int main() { B b(10); g(b); g(20); return 0; } (A) Compiler Error (B) 10 2
1 min read
C++ | Operator Overloading | Question 7
Output of following program? #include <iostream> using namespace std; class Test2 { int y; }; class Test { int x; Test2 t2; public: operator Test2 () { return t2; } operator int () { return x; } }; void fun ( int x) { cout << "fun(int) called"; } void fun ( Test2 t ) { cout << "fun(Test 2) called"; } int main()
1 min read
C++ | Operator Overloading | Question 10
Predict the output? #include<stdlib.h> #include<stdio.h> #include<iostream> using namespace std; class Test { int x; public: void* operator new(size_t size); void operator delete(void*); Test(int i) { x = i; cout << "Constructor called \n"; } ~Test() { cout << "Destructor called \n"; } }; void* Test
2 min read
C++ | Operator Overloading | Question 9
#include<iostream> using namespace std; class Point { private: int x, y; public: Point() : x(0), y(0) { } Point& operator()(int dx, int dy); void show() {cout << "x = " << x << ", y = " << y; } }; Point& Point::operator()(int dx, int dy) { x = dx; y = dy; return *this; } int main() { Point p
1 min read
C++ | Operator Overloading | Question 10
Which of the following operator functions cannot be global, i.e., must be a member function. (A) new (B) delete (C) Conversion Operator (D) All of the above Answer: (C) Explanation: new and delete can be global, see following example. #include #include #include using namespace std; class Myclass { int x; public: friend void* operator new(size_t siz
1 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
Increment (++) and Decrement (--) Operator Overloading in C++
Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types. Why Operator Overloading? Let's say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the re
4 min read
C++ program to compare two Strings using Operator Overloading
Pre-requisite: Operator Overloading in C++Given two strings, how to check if the two strings are equal or not, using Operator Overloading. Examples: Input: ABCD, XYZ Output: ABCD is not equal to XYZ ABCD is greater than XYZ Input: Geeks, Geeks Output: Geeks is equal to Geeks Approach: Using binary operator overloading. Declare a class with a string
3 min read
Operator Overloading '<<' and '>>' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Matrix operations using operator overloading
Pre-requisite: Operator OverloadingGiven two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.Examples: Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}} Output: Addition of two given Matrices is: 2 4 6 8 10 22 2 4 6 Subtraction of
13 min read
Advantages and Disadvantages of Function Overloading in C++
Function overloading is one of the important features of object-oriented programming. It allows users to have more than one function having the same name but different properties. Overloaded functions enable users to supply different semantics for a function, depending on the signature of functions. Advantages of function overloading are as follows
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(>>/<<) Overloading in C++ We can't directly use the Input/Output Operators (>
2 min read
C++ Logical (&&, ||, !) Operator Overloading
Prerequisites: OperatorsOperator Overloading Logical operators are used for combining two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false. In C++, there are 3 logical operators: Logical AND (&&): This operator returns true o
3 min read
C++ Bitwise Operator Overloading
Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ takes two numbers as operands and does AND on every bi
7 min read
Typecast Operator Overloading in C++
In C++, the typecast operator can be overloaded to customize the behavior of casting operators to define how user-defined data types can be converted into other types. This enables developers to define how instances of a class are converted to other types, providing more control over implicit type conversions. By overloading typecast operators, dev
6 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
Overloading stream insertion (<>) operators in C++
In C++, stream insertion operator "<<" is used for output and extraction operator ">>" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be overloaded as a global function. And if we want to
2 min read
Function Overloading and float in C++
Although polymorphism is a widely useful phenomena in C++ yet it can be quite complicated at times. For instance consider the following code snippet: C/C++ Code #include&lt;iostream&gt; using namespace std; void test(float s,float t) { cout &lt;&lt; &quot;Function with float called &quot;; } void test(int s, int t) { cout
2 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Practice Tags :
three90RightbarBannerImg