Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert derived class to base class

I'm trying to refresh my memory but can't find answers with Google.

public class BaseClass {     public virtual void DoSomething()     {         Trace.Write("base class");     } }  public class DerivedClass : BaseClass {     public override void DoSomething()     {         Trace.Write("derived class");     } } 

If I create an instance of derived class, how do I convert it to it's base class so that when DoSomething() is called, it uses the base class's method only?

A dynamic cast still calls the derived class's overridden method:

DerivedClass dc = new DerivedClass();  dc.DoSomething();  (dc as BaseClass).DoSomething(); 

Output: "derived class"

like image 434
Levitikon Avatar asked Nov 30 '11 16:11

Levitikon


People also ask

Can you convert a pointer from a derived class to its base class?

[19.4] Is it OK to convert a pointer from a derived class to its base class? Yes.

Can you cast from base class to derived?

Likewise, a reference to base class can be converted to a reference to derived class using static_cast . If the source type is polymorphic, dynamic_cast can be used to perform a base to derived conversion.

Can we create a base class object from derived class?

No, it is not possible. Consider a scenario where an ACBus is a derived class of base class Bus.

Can a derived class be a base class C++?

class B { }; class D : public B // public derivation { }; You can use both a structure and a class as base classes in the base list of a derived class declaration: If the derived class is declared with the keyword class , the default access specifier in its base list specifiers is private .


2 Answers

Although this sounds irrational but it works

 DerivedClass B = new DerivedClass();  BaseClass bc = JsonConvert.DeserializeObject<BaseClass>(JsonConvert.SerializeObject(B)); 
like image 130
Sugar Bowl Avatar answered Oct 03 '22 00:10

Sugar Bowl


You can't - that's entirely deliberate, as that's what polymorphism is all about. Suppose you have a derived class which enforces certain preconditions on the arguments you pass to an overridden method, in order to maintain integrity... you don't want to be able to bypass that validation and corrupt its internal integrity.

Within the class itself you can non-virtually call base.AnyMethod() (whether that's the method you're overriding or not) but that's okay because that's the class itself deciding to potentially allow its integrity to be violated - presumably it knows what it's doing.

like image 24
Jon Skeet Avatar answered Oct 03 '22 00:10

Jon Skeet