Use one class method that implements other class methods as well as its own
I'm Programing in C++, and I have 3 classes that inherit from each other:
Hatchback -> Car -> Vehicle;
I want to print the attributes from each class using a void print()
method,
Each class has a Print method that prints its own attributes.
void Vehicle::print()
{
// Vehicle attributes
}
void Car::print()
{
// Car attributes
}
void Hatchback::print()
{
// Hatchback Attributes
}
I create an object that initialises ALL attributes from ALL classes in one constructor:
Hatchback hatchback("L880UCD", "Vauhall", "Corsa",
"White", "None", "Car", "Hatchback",
3, 5, "Manual", 3, 2, 1);
The problem is, i want to print all the attributes using one print method, so when i call,
object.print();
it runs through the vehicle print method, then the Car print method, then the Hatchback Print method.
I Know that i COULD print all the attributes from the Hatchback print method because everythings inherited. If possible i would like to avoid printing all 3 classes data in one class method... I would rather each class deal with its OWN methods and functions!
Not only that, i have A LOT of other classes including Car, Bus and Lorry that ALL inhert from Vehicle, and Container, Tanker, Flatbed, Motorbike, Transit ETC 开发者_JS百科ETC that ALL inhert from Car, Lorry and Bus.
So I don't want to write Print Vehicle in every single bottom derived class!
If there is a way to do this, i would appreciate a response very much.
I've tried using Virtual Functions but come to the conclusion that they just choose which method to use at run time rather than amalgamating the print functions.
Thanks for reading! Sorry if its a Vague or Noob Question... I'm new to Stack Overflow! :)
If you are asking if you can call a base class method from a derived class, then yes, you can:
void Vehicle::print() {
std::cout << "Vehicle attributes" << std::endl;
}
void Car::print() {
Vehicle::print();
std::cout << "Car attributes" << std::endl;
}
Have Hatchback::print() call Car::print() which can then call Vehicle::Print()
In Car::print() print out the car attributes and then call Vehicle::print(). In Hatchback::print() print out the hatchback attribtues and then call Car::print() And so on
精彩评论