#include <iostream> using namespace std; // Base class (Parent) class Vehicle { public: void start() { cout << "Vehicle started" << endl; } }; // Derived class (Child) class Car : public Vehicle { public: void playMusic() { cout << "Music is playing" << endl; } }; // Main function int main() { Car myCar; // Accessing parent class method myCar.start(); // Accessing child class method myCar.playMusic(); return 0; }Output:
Short Explanation:
Vehicle
is the base (parent) class.-
It has a method
start()
that prints"Vehicle started"
. -
Car
is the derived (child) class, which inherits fromVehicle
. -
Car
has its own methodplayMusic()
that prints"Music is playing"
. -
In
main()
, we create aCar
object (myCar
). -
This object can use both:
-
The parent’s method
start()
. -
The child’s method
playMusic()
.
-
So we can say, this is an example of Single Inheritance in C++, where one class inherits from another.
If you found this post useful:
⮕ Share it with others who might benefit.
⮕ Leave a comment with your thoughts or questions—I’d love to hear from you.
⮕ Follow/Subscribe to the blog for more helpful guides, tips, and insights.
Comments
Post a Comment