I am learning OOP and have a question about what is exactly happening with the code below.
I have the classic Dog
Animal
example going. Dog
inherits Animal
.
public class Animal
{
public string Name { get; set; }
public virtual string Speak()
{
return "Animal Speak";
}
public string Hungry()
{
return this.Speak();
}
}
public class Dog : Animal
{
public override string Speak()
{
return "Dog Speak";
}
public string Fetch()
{
return "Fetch";
}
}
Both questions are based on this assignment: Animal a = new Dog();
Animal
and set it to a Dog
reference. Is there a specific term for this? a.Hungry()
, the output is "Dog Speak." If the output is "Dog Speak", why can I not call a.Fetch()
? What is the term for what's happening here?Any help and further reading on the particular topic would be greatly appreciated.
Inheritance is one of the key features of Object-oriented programming in C++. It allows us to create a new class (derived class) from an existing class (base class). The derived class inherits the features from the base class and can have additional features of its own.
Inheritance is the ability to define new classes based on existing classes in order to reuse and organize code. You can easily implement single inheritance in C by literally embedding the inherited class attribute structure as the first member of the derived class attribute structure.
Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.
Which is the correct syntax of inheritance? Explanation: Firstly, keyword class should come, followed by the derived class name. Colon is must followed by access in which base class has to be derived, followed by the base class name.
Dog
as if it were an Animal
. (Thanks to Matt Burland for reminding me that this is the appropriate term.)Animal
, and as such you can only access members that the compiler knows an Animal
can access, i.e. Speak
and Hungry
. It doesn't know that the Animal
is a Dog
, so it can't call Fetch
. The variable would need to be of type Dog
for you to be able to call Fetch
on it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With