Object Oriented Programming Advanced Usage – Arma Reforger
Jump to navigation
Jump to search
Casting
Casting is the act of "presenting" a value as another type. For example, if a class hierarchy is Animal > Dog > Cocker, a dog is an animal, a cocker is a dog (that is an animal), but a dog is not especially a cocker.
class Animal {}
class Dog : Animal {}
class Cocker : Dog {}
class Labrador : Dog {}
Upcasting
Upcasting means seeing the class as one of its parents:
void Method()
{
Cocker cocker = new Cocker();
Animal animal = cocker; // OK, as a cocker is an animal
string sentence = cocker; // error: cocker does -not- inherit from string
};
Downcasting
Downcasting means seeing a parent class as a specific child - this must be done by manually casting:
void Method(Dog dog)
{
Cocker cocker1 = dog; // error: "Dog" is too generic to be casted as Cocker - it could be e.g a Labrador
Cocker cocker2 = Cocker.Cast(dog); // OK: manual casting tells the code "the developer knows what he is doing"
// if 'dog' is not castable as a Cocker, null is returned - the code does not crash
Cocker cocker3;
cocker3.Cast(dog); // alternative method
}
Manual Casting
void Method()
{
float value1 = 4.9;
int value2 = value1; // value2 = 4 as integer casting -truncates- the value, not rounds it
string value3 = "result = " + (bool)value2; // "result = true", as a non-zero integer is true when casted to bool
}
Template
A template is a class that allows a generic management for multiple types. Its methods cannot assume anything about the type.
// template class Item with generic type T
class Item<Class T>
{
protected T m_data;
void Item(T data)
{
m_data = data;
}
void SetData(T data)
{
m_data = data;
}
T GetData()
{
return m_data;
}
void PrintData()
{
Print(m_data);
}
};
void Method()
{
Item<string> stringItem = new Item<string>("Hello!"); // template class Item declared with type "string". In Item<string> class, all Ts are substituted with 'string'
Item<int> intItem = new Item<int>(72); // template class Item declared with type "int". In Item<int> class, all Ts are substituted with 'int'
string_item.PrintData(); // prints "m_data = 'Hello!'"
int_item.PrintData(); // prints "m_data = 72"
}