user2553620
user2553620

Reputation: 77

overriding functions in c++

#include <iostream>

using namespace std;

class Base {
public:
virtual void some_func(int f1)
{
cout <<"Base is called: value is : " << f1 <<endl;
}
};

class Derived : public Base {
public:
virtual void some_func(float f1)
{
cout <<"Derived is called : value is : " << f1 <<endl;
}
};


int main()
{
int g =12;
float f1 = 23.5F;

Base *b2 = new Derived();
b2->some_func(g);
b2->some_func(f1);
return 0;

}

Output is :

Base is called: value is : 12
Base is called: value is : 23

Why is the second call b2->some_func(f1) calling Base class's function,even though there is a version with float as argument available in Derived class?

Upvotes: 2

Views: 170

Answers (2)

Medinoc
Medinoc

Reputation: 6608

  1. It's not actually overridden, since its arguments don't have the same type.
  2. Since it's not overridden, your pointer to Base only knows the int method, so it performs a narrowing conversion (there should be a warning) and calls Base::some_func(int).

Upvotes: 4

Anand Rathi
Anand Rathi

Reputation: 786

you have confused overloading with overriding , For overriding , the signature of the function must remain same. please check the c++ documentation again .. hope this is helpful

Upvotes: 2

Related Questions