A Comparison of the Concept of C++ Reference Format and Parent-Child Overriding in Java

Asked 2 years ago, Updated 2 years ago, 96 views

I'm studying c++ for the first time! When there is a function test that overrides the function of A in B when A is a child class, parent B is a child class,

A ref = new B; ref.test();

I thought that function A's test would be executed if you do

In Java, we learned that overriding a function of a child is executed when a function of a parent is called.

Is that what I understood in C++ right? So, if I execute the parent's function when the parent receives the child-type object in C++, the parent's function will be executed?

c++ reference value

2022-09-22 21:11

1 Answers

If you override both C++ and Java, your child's function is the same, but the behavior is different when you transform it.

#include <iostream>
 
using namespace std;
 
class Animal {
public:
    "An animal eats it." " << endl; }
};
 
class Dog : public Animal {
public:
    voidate() { cout << "Dogs Eat" << endl;}
};
 
int main()
{
    Dog dog;
    dog.eat();
    Animal& AnimalRef = dog;
    AnimalRef.eat();
    return 0;
}

If you run it like this,

 dog eats
Animals eat.

It is printed as shown in . In the first line, the dog class overrides the eating of the Animal class and outputs 'dog eats' but if you convert the Dog object to Animal as in the second line output, the animal's eating function is executed.

However, in Java, the function is always run on an object basis (child class basis) even if a type transformation occurs.

class CodeRunner{
    public static void main(String[] args){
        Dog dog = new Dog();
        dog.eat();
        Animal animal = dog;
        animal.eat();
}
}

class Animal{ 
    The public void at(){System.out.println ("Animal Eat").");}
}

class Dog extends Animal{
    public voidate(){System.out.println ("Dogs Eat").");}
}

When executing the above code, only two lines of 'dog eating' are printed.

 dog eats.
The dog eats.

In summary,


2022-09-22 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.