If a function is overloaded in a derived class but the function signature is unchanged, is there any way to call the derived class' function from a base class pointer? For instance:
Given the following base and derived classes
class Base {
public:
Base(int n): n_(n) {}
~Base() {}
int get_n() {
return n_;
}
private:
const int n_;
};
class Derived : public Base {
public:
Derived(int n): Base(n), n_(n) {}
~Derived() {}
double get_n() {
return 1.5*n_;
}
private:
const int n_;
};
Is there any way to get the following to output 1.5
given that two get_n()
functions differ only in their return types?
#include <iostream>
int main() {
Base *b = new Derived(1);
std::cout << b->get_n() << std::endl;
}