简体   繁体   中英

C++ inheritance function overriding

I have a question (part of my homework) which im unsure of the code's behavior.

I got a class Father , which owns a function "A", function "A" prints "Hello Father".
I got a second class -> class son:public Father , which does not owns function "A".
I got a third class -> class grandson:public son , which owns function "A" which prints "Hello grandson".

Function "A" is not virtual. Please ignore compiling errors, I didnt want to put here a 80 lines of code.

I have another function :

void justPrint(const son& a) {
   a.A;
}

Now, what will be printed in the following call :

grandson jeff;
justPrint(jeff);

I'm a bit confused, son dont have the print function (A), so he suppose to call to Father::A (son is a father..)
but, we send jeff (grandson) to the function which recieves son.. and grandson is a son..

I think that it will print

"Hello Father"

But i'm so confused... Will appericiate any help and explenation..

Second thing, What will happen if i will make the following call :

justPrint(1);

I try to make a short code to solve your problem, but I don't have it (using "g++ test.cpp -fpermissive" to compile)

#include <iostream>

using namespace std;

class Father
{
    public:
    void A(){
        cout<<"Hello Father"<<endl;
    }
};

class Son : public Father
{
};

class GrandSon : public Son
{
    public:
    void A()
    {
        cout<<"Hello GrandSon"<<endl;
    }
};

void justPrint(const Son& a)
{
    a.A();
}

int main(int argc, char* argv[])
{
    GrandSon jeff;
    justPrint(jeff);
    return 0;
}

Maybe you have put A in private?


Output: Hello Father

void justPrint(const son& a) {
   a.A;
}

justPrint(1); if Class son contains single argument constructor with int as i/p.It will call that .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM