+ 1
How does inheritance in c++ work?
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.
+ 10
Sure! I am happy to help!!
+ 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.
+ 3
I appreciate this pratt, its helpful.
So basically it means deriving from a already exsting class?
+ 3
Cool thanks, i will follow you, and you could help me out when i need assistance