The best way to understand inheritance in C++ is to take a look at a simple code example. Let's consider a context from finance, specifically stock assets. If you're familiar with finance, you know that each stock can be considered as an asset with additional characteristics, such as its ticker symbol.
In the code here, we first define an Asset
parent class that holds a value. We then create a Stock
class that is derived from the Asset
class. The Stock
class introduces an additional property - the ticker symbol. This is a perfect example of inheritance, where the Stock
class reuses the code in the Asset
class and extends it with its characteristics.
Our main
function then creates a Stock
object, representing Apple's shares, with a ticker 'AAPL' and a value of 150. We can then use the methods defined in both the Asset
and Stock
classes, showing how inheritance allows efficient code reusability and extension.
xxxxxxxxxx
using namespace std;
// Parent class
class Asset {
public:
Asset(int val):value(val) {}
int Get() { return value; }
private:
int value;
};
// Child class - Stock derived from the class Asset
class Stock : public Asset {
public:
Stock(const string &name,int val):Asset(val),ticker(name) {}
const string &Ticker() { return ticker; }
private:
string ticker;
};
int main() {
Stock apple("AAPL", 150);
cout << "The stock " << apple.Ticker() << " is worth $" << apple.Get() << endl;
return 0;
}