Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual function overloading

Lets say that we have :

Class A
{
public:
   virtual void print(){ std::cout<<" A "<<endl; }
}

Class B : public A
{
public:
   virtual void print(int x){ std::cout<<" B "<<endl;}

}

I thought that the definition in Class B of function print will hide the function print from class A. But the following code works and prints " A "

int main()
{

A * a = new B;

a->print();

return 0;
}  

If I write the main function like this it doesnt work :

int main()
{

B b;

b.print();

return 0;
}  

What i Want to know is...in my first main() example I have a B object that calls print()...shouldnt then print() be hidden and have an error like in the second main() example

like image 531
dragosb Avatar asked Apr 24 '26 22:04

dragosb


2 Answers

The member function print() in B is not overriding the print() in A because it has a different signature. Therefore, when calling print() in your first, unedited version of main(), there is only one matching function to call, as pointed out by user juanchopanza: A::print().

EDIT: To summarize:

  • Polymorphic behavior: If A::print() and B::print() had the same signature, the appropriate print() would be chosen at runtime as long as you reference the object through pointers or references.

  • Function overloading: Since a class is a scope and functions do not overload across scopes, the functions from base classes are hidden by functions of the same name in a derived class. For this, the type of the variable you are using to refer to your object is the one that matters, not the type of the object itself. Therefore, in your second example you get an error that there is no matching function to call, but in your first example, only one function is in scope.

like image 152
blackbird Avatar answered Apr 27 '26 15:04

blackbird


The issue here is name lookup. In a call like A *a = new B; a->print() the compiler looks at the type of a, which is A*, and looks in the class A for a member function named print. It finds it and it calls it. Similarly, with B *b = new B; b->print(); the compiler looks in class B for a member function named print; it finds print(int), which can't be called with no arguments. And because it found a function named print in B it stops looking; it doesn't go into A to find A::print(). That's name hiding.

The key here is that name lookup starts with the declared type of the object; in these two examples the types are A* and B*, respectively. Lookup does not pay attention to the actual type of the thing that a pointer or reference points to or refers to.

like image 35
Pete Becker Avatar answered Apr 27 '26 15:04

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!