-3

I am having trouble figuring out why this program works. I wrote it based on my notes (OOPP and classes) but I do not understand how exactly it works? I would appreciate any help!

Here is the code:

#include <iomanip>
#include <iostream>

using namespace std; 

class Base{
    public:
        void f(int) {std::cout<<"i";}
};
class Derived:Base{
    public:
        void f(double){std::cout<<"d";}
};
int main(){
    Derived d;
    int i=0; 
    d.f(i);
}

I have tried making cout statements to show me how everything is passed and runs, but it will not allow me to cout anything.

  • 1
    [Your code outputs `d`](https://wandbox.org/permlink/gNWFf0YVe1xMXQEe). If you want overload resolution to consider the member functions from `Base` you can say `using Base::Derived;` in `Derived` [like this](https://wandbox.org/permlink/7NizyvpxUdltDmCw) – Ryan Haining Nov 17 '22 at 03:45
  • 1
    but what is your actuall question - what output are you expecting? – Neil Butterworth Nov 17 '22 at 05:06
  • 1
    **StackOverflow is not an *"introduction to C++"*.** These trivial things are explained in any beginner [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Jason Nov 17 '22 at 06:25
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Nov 17 '22 at 06:38

1 Answers1

1

This program defines a class called Base, which has a member function called f that takes an int parameter. It also defines a class called Derived, which inherits from Base and has a member function called f that takes a double parameter.

In the main function, an object of type Derived is created, and an int variable is initialized to 0. The member function f is then called on the Derived object, passing in the int variable as a parameter.

When the member function f is called on the Derived object, the compiler looks for a matching function signature in the Derived class. Since there is a function with the same name and parameter list in the Derived class, that function is called. The function in the Derived class prints out a "d", indicating that it was called.

Igor
  • 474
  • 2
  • 10