How does inheritance in c++ work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does inheritance in c++ work?

22nd Apr 2019, 5:22 AM
Gerald Mbuthia
Gerald Mbuthia - avatar
5 Answers
+ 10
Gerald Mbuthia, yes, Exactly! First, we create a base class which has all of the basic properties and methods. After that, we derive classes from the base class. After doing so, the derived class will have similar properties to the base class. And if the derived class changes its properties, it does not affect the base class.
22nd Apr 2019, 12:58 PM
Edwin Pratt
Edwin Pratt - avatar
+ 10
Sure! I am happy to help!!
22nd Apr 2019, 1:11 PM
Edwin Pratt
Edwin Pratt - avatar
+ 9
"Inheritance allows us to define a class based on another class." Let's say we have a class called Animal. The Animal class contains basic properties like sound, number of legs, name, etc. Now, say we want to create a Dog class based on the Animal class. Doing so, we say that the Dog class inherits properties from the Animal class. // The "base" class class Animal { public: std::string sound = "Meow"; int legs = 2; }; // Inherited (derived) class class Dog : Animal {}; int main() { // Create new object Dog dog = new Dog(); // Override properties dog.legs = 4; dog.sound = "Woof"; return 0; } Because Dog was inherited from Animal, we don't have to redefine the properties.
22nd Apr 2019, 7:43 AM
Edwin Pratt
Edwin Pratt - avatar
+ 3
I appreciate this pratt, its helpful. So basically it means deriving from a already exsting class?
22nd Apr 2019, 12:36 PM
Gerald Mbuthia
Gerald Mbuthia - avatar
+ 3
Cool thanks, i will follow you, and you could help me out when i need assistance
22nd Apr 2019, 1:10 PM
Gerald Mbuthia
Gerald Mbuthia - avatar