Question Using child of object in child class

atsamy

New member
Joined
Feb 3, 2023
Messages
1
Programming Experience
10+
Hello All, so i have a parent class that has a variable from a parent class like so
C#:
Class Vehicle
{
      public TireBase Tire;
}

Class Tire
{
      public Pump()
      {
      }
}

Class MotorbikeTire:Tire
{
      public Pump()
      {
             //different implementation
      }
   
      public Fix()
      {
      }
}

Class Motorbike:Vehicle
{
       Public Motorbike()
       {
              Tire = new MotorbikeTire();
       }
}
so from class MotorBike i need to call functions inside MotorbikeTire without having to cast Tire into MotorbikeTire everytime, is there a way to do this.
 
Last edited by a moderator:
Solution
As long as Tire.Pump() is declared as virtual, there is no need to downcast.

But if you need to access MotorBikeTire.Fix(), you will have to downcast.

An alternative is to use interfaces and use the Bridge pattern, but that tends to also make things more verbose.
Welcome to the forum. In the future, please put code in code tags, not quote tags. The code tags will help preserve the indents and provide some syntax coloring.
 
As long as Tire.Pump() is declared as virtual, there is no need to downcast.

But if you need to access MotorBikeTire.Fix(), you will have to downcast.

An alternative is to use interfaces and use the Bridge pattern, but that tends to also make things more verbose.
 
Last edited:
Solution
Note that you have to provide a return type for a method. Only constructor definitions do not have return types, but the cosntructor has the same name as the class. This is wonky:

C#:
Class Tire //should be "public class"
{
      public Pump()  //should be either "public Tire" or "public void Pump" or some type name where "void" is
 
without having to cast Tire into MotorbikeTire everytime

See if you can call those operations without needing it to be known that it is a motorbike tire, or provide a property that does the casting

C#:
Class Motorbike:Vehicle
{
       private MotorbikeTire MotorBikeTire => Tire as MotorbikeTire;
       Public Motorbike()
       {
              Tire = new MotorbikeTire();
       }

       void Blah(){
         Tire.Pump(); // all Tire have a pump method; you dont need to cast it to a MotorBikeTire to use Pump. MotorbikeTire.Pump will be used if the object in Tire is a MotorbikeTire

          MotorbikeTire.SomeSpecificMethodOfAMBTNotPresentOnANormalTire();
      }
}
 
Back
Top Bottom