Click here to Skip to main content
15,885,216 members
Everything / Inheritance

Inheritance

inheritance

Great Reads

by GProssliner
cobj is a preprocessor based generator for interface based polymorphism
by Mark Pelf
Tutorial on “Prototypal Inheritance” in JavaScript language
by Martin ISDN
Solid JavaScript from facts to rules
by tonyt
namespace System{ public static class SystemExtensionMethods { public static string GetAncestry( this object target ) { return string.Join( " -> ", target.GetTypes().Reverse().Select( t => FormatName( t ) ).ToArray() ); } public...

Latest Articles

by Mark Pelf
Tutorial on “Prototypal Inheritance” in JavaScript language
by Lee P Richardson
How to secure external web APIs
by Martin ISDN
Solid JavaScript from facts to rules
by gfazzola
In this article I will explain the implementation of an infrastructure to host and manage windows services in a practical and interactive way.As a practical example of the solution will be implemented a dynamic ip update client of DucDNS

All Articles

Sort by Score

Inheritance 

7 Jun 2016 by GProssliner
cobj is a preprocessor based generator for interface based polymorphism
10 Dec 2012 by CPallini
A C++ abstract class is not, by default an interface, i.e. it may contain functionality implementation as well.As documentation[^] states:A class that contains at least one pure virtual function is considered an abstract class.that is it might contain method implementations as...
24 Apr 2015 by Sergey Alexandrovich Kryukov
Please see my comment to the question.Please see my past answers:Append a picture within picturebox[^],draw a rectangle in C#[^],How do I clear a panel from old drawing[^].Other problems could be solved as you face them, but it's still better to make a good plan.—SA
30 Jul 2011 by «_Superman_»
Add a default constructor to the CExchangeRate class - CExchangeRate(void);
22 Oct 2013 by CPallini
It is inherited but hidden, see the answer to this Stack Overflow question: "operator= and functions that are not inherited in C++?"[^].
1 Nov 2023 by Mark Pelf
Tutorial on “Prototypal Inheritance” in JavaScript language
23 Mar 2011 by CPallini
That's the constructor of the derived class 'constructorA' with parameter of type 'Game' which in turn calls,in its initializer list, the base class ('base') constructor with same argument type, passing it its argument.Such a mechanism is often useful.
23 Mar 2011 by Wendelius
It calls the base classes constructor with the parameter passed to the derived class constructor. The advantage is for example if you have multiple derived classes and you want to use same constructor in each so you can define the logic in the base class.
23 Mar 2011 by Sergey Alexandrovich Kryukov
It means that a constructor of a class uses a constructor of its base class to pass a variable of the type Game before further initialization.—SA
17 Dec 2012 by Espen Harlinn
A constructor starts by invoking constructors for its bases, then constructors for its members, and then executing its code (if any)".Whether you class has virtual member functions, pure or otherwise, has nothing to do with this. One thing to be aware of though, is that it's impossible to...
22 Oct 2013 by Sergey Alexandrovich Kryukov
It is of course inherited as everything. The only problem is that the operator you defined is hidden by the default operator. You can easily see it if you cast a to Foo. Also note that Foo "=" returns the type Foo, and your code would require it to return Bar. There is no such operator, and this...
31 Mar 2016 by Sascha Lefèvre
You can't create instances of static classes:Book myBook = new Book();-> Remove the static modifier from your three "book-classes".Variables declared in methods can't have modifiers because they're automatically and always only visible within that method:public string input;The...
2 Jan 2020 by Martin ISDN
Solid JavaScript from facts to rules
31 Jul 2010 by tonyt
namespace System{ public static class SystemExtensionMethods { public static string GetAncestry( this object target ) { return string.Join( " -> ", target.GetTypes().Reverse().Select( t => FormatName( t ) ).ToArray() ); } public...
1 Sep 2010 by Al-Farooque Shubho
Unfortunately, we still lack a true Object Oriented database, and, databases are still Relational. That's why we need Object Relational mapper (ORM) between the application and the database to do database operations.But, you can implement the similar relationship in the database, that you...
16 Mar 2011 by Henry Minute
If you want to use your Enter_DataGridView in other projects, it should be declared as public. public class Enter_DataGridView { ................... }
7 Apr 2011 by #realJSOP
There is no "better" way to do it. Here are my personal rules0) If you are bound by coding guidelines relating to constructors, follow them. Period.Otherwise...1) If you are editing an existing file, follow the coding style used in the file2) If you are creating a new file, do...
7 Apr 2011 by Sergey Alexandrovich Kryukov
1) This is can be used as an accessor; you are right. If you need to modify the field of the already constructed class instance, what else can we do? We can use this accessor or side effect from some (non-const) instance (non-static) function called on this instance.2) This form of writing...
9 Apr 2011 by AspDotNetDev
There are many different uses for the constructs you've described, and it would be much easier to choose between them given a usage scenario. However, one thing I will note is that your third item is making use of an initialization list.Initialization lists can be used to pick which parent...
10 May 2011 by Nagy Vilmos
class ShapeExercise { // add code}class Shape { // add code String getName() { // add code } void setName(String aName) { // add code }}class EqualSides extends Shape { // add code}class UnequalSides extends Shape { ...
8 Jun 2012 by codeBegin
Interfaces in C#.Interface is a contract that defines the signature of the functionality. So if a class is implementing a interface it says to the outer world, that it provides specific behavior. Example if a class is implementing ‘Idisposable’ interface that means it has a...
29 Jun 2012 by Sergey Alexandrovich Kryukov
This is something which could called generic specialization, by the analogy with C++ template specialization.It looks like your efforts are useless until you work with generic methods; it is not possible to specialize the implementation via overriding for a concrete type. I want to give you...
18 Jun 2013 by Ron Beyer
Nothing from the standpoint of functionality since both your classes have the same methods. The difference would be if the derived class had methods that the base class did not, you would not be able to access them in the first case without casting...
10 Oct 2013 by Andreas Gieriet
The generic definition has a where clause that tells the compiler that the actual TNode type must implement IComparable. So, the compiler knows that the instanciated generic type has a CompareTo(...) method.You can only instanciate BinaryTreeNode with a type that fulfills that...
31 Oct 2013 by Pratik Bhuva
here there are methods with same parameter and return type.and You are calling method of class not of interface."An interface contains only the signatures of methods, properties, events or indexers." - MSDNSo interface is just for signature.In your case Compiler will only check that...
21 Dec 2013 by OriginalGriff
No, you can't.The whole idea of Generics is that they are type unspecific - they are general purpose rather than linked to a specific class: so you can declare a List class that work as a collection of a generic class, and it will work the same with an integer and an SqlCommand.Declaring...
2 Oct 2015 by Wendelius
The parameters in the derived class are different from the method in the abstract class.Since the definition in the base class is public virtual decimal CalcTuition(int intCreditHours, decimal decBaseRate, decimal decGraduateFee, int intExcessCredits, decimal...
13 Jan 2017 by CPallini
Have also a look at typeid operator[^].
2 Sep 2019 by Afzaal Ahmad Zeeshan
Quote: as you guys can see class `Employee` extends `Person` thus it will have all it's fields and method right ? Only if you will do, Employee e = (Employee)p; Then, after a cast, you can see Java being printed. Currently, there is no connection between what p is having and what e contains....
29 Jan 2022 by Greg Utas
You can look up what the standard has to say about dynamic_cast when multiple inheritance is involved, but I'm going to live dangerously and not bother. The first (hidden) data member of every object that has a virtual function is a vptr. It...
8 Nov 2010 by DanielWehrle
Hi,I have an abstract class like:abstract class MyAbstractClass { public abstract String Name {get;} public void doBasicFunktion(){ //Do Something }}Now I want to implement the abstract class but have an additional private set for the property.class...
22 Aug 2011 by Simon Bang Terkildsen
You cannot inherit from a class with no public or protected constructors.You get the first error because the compiler can't find a public default constructor of PrintSystemJobInfo.And you get the second error because when you define no constructor the default constructor of the base is used...
22 Aug 2011 by Shameel
From MSDN, we see that the System.Printing.PrintSystemJobInfo does not have a public constructor (most probably it's private or internal), so you cannot inherit the class. You can get an instance of the class using the static Get() method.However, if you must create an instance, you can try...
3 Feb 2012 by Stefan_Lang
Check out http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.9[^] or http://www.cprogramming.com/tutorial/virtual_inheritance.html[^]Note that to solve your problem, both intermediate derived classes must inherit virtually, not just one of them.
18 Mar 2012 by ProEnggSoft
The preferred approach in .NET is to use Dispose pattern for clean up of unmanaged resources, as it is not certain at what time Finalize method is called by the GC. Please go through the following articlesImplementing IDisposable and the Dispose Pattern...
4 Nov 2012 by Sergey Alexandrovich Kryukov
There is one way: you can create an assembly during run time, using System.Reflection.Emit, and, in this assembly, create a type with required features (it could be a class derived from some existing type) and later use it using System.Reflection — in in the same runtime. Please...
4 Nov 2012 by Andreas Gieriet
See http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License[^].The challenge: a customer must be enabled to replace your delivered LGLP based library by his own one. This is for example technically not fully given for languages that do inline code from the LGPL library (e.g. templates...
2 Aug 2013 by Maarten Kools
The IsReadOnly[^] property is implemented explicitely. That means you can only call this property when the object is explicitly cast to an ICollection.More info about explicit interface implementation can be found here[^]
9 Dec 2013 by Richard MacCutchan
Since you have inherited from the Calculator class, you have also inherited all its public and protected variables. So, you can access them directly by name, anywhere inside your class. See this tutorial[^] for a fuller description of the rules on i nheritance.
23 Dec 2013 by BillWoodruff
Console.WriteLine(i);Console...
10 Mar 2014 by OriginalGriff
Multiple inheritance is a pain.There is a lot of discussion of this out there: a quick Google[^] will give you over 100,000 hits.This is a good reason: http://stackoverflow.com/questions/225929/what-is-the-exact-problem-with-multiple-inheritance[^]
25 Sep 2014 by johannesnestler
Hi Member,You can't stop assigning a derived object to it's base class pointer. That's the nature of OOP...So your question doesn't make sense. If BillWoodruf was right in guessing what you really want, I'd like to add that you could use code like this (maybe also have a look at...
26 Jul 2015 by Sergey Alexandrovich Kryukov
First of all, the rule to have all abstract members overridden any any non-abstract class is not just about direct derived class, this is about all the derived classes. But you are right: once a member is implemented and made non-abstract, you can inherit it in next level of hierarchy instead of...
17 Mar 2016 by Sascha Lefèvre
No, it's not possible in the way you want it and that's for a good reason: You would violate one of the OOP-principles: Polymorphism (computer science) - Wikipedia[^]A great answer to exactly the same question on StackOverflow from Eric Lippert, one of the C# language designers: c# - How to...
21 Mar 2016 by Jochen Arndt
There is no instance of the base class. There is only an instance of the derived class. Because the member variables of the base class are part of the derived class (located in memory before the additional members of the derived class) they can be accessed by functions of the base class....
9 Jun 2016 by BillWoodruff
edit ... after consulting my notes ...MS clearly warns about using a Form that inherits from a Form with a TableLayoutPanel on it:The TableLayoutPanel control does not support visual inheritance in the Windows Forms Designer. A TableLayoutPanel control in a derived class appears as "locked"...
11 Mar 2018 by OriginalGriff
Suppose you have three classes: class A {} class B : A { public string S { get; set ; } } class C : B { public string S2 { get; set ; } } So C is derived from B which is derived from A. That means that instances of both C & B are instances of A plus a bit, and that a C instance is also an...
29 Mar 2018 by OriginalGriff
First off, Interfaces don't provide multiple inheritance: interfaces are not classes, they are a contract, and you can't "inherit" from an interface. As to why C# doesn't support MI, the most likely reasons is "because the benefits do not overweigh the complexity involved in implementing it" -...
4 Jul 2019 by OriginalGriff
Because you have said it should: Window Styles - Windows applications | Microsoft Docs[^] Look at the bit you add to the style (WS_SIZEBOX).
26 Jun 2020 by Lee P Richardson
How to secure external web APIs
23 Jul 2010 by johannesnestler
OriginalGriff has made a nice and small class. But I don't think I would use this code in an application. Most times when I want to know about the inheritance chain of an object is while I'm coding. So a quick and nice (commandline?) tool would be a better fit, I think. The problem with...
1 Sep 2010 by yekta_68
Hi,How can I implement inheritance in tables on a relational database?Eg. I have the members class that is a super class and it has only user name attribute.My child classes are: admin_users and other_users that derived from members super class.These child classes consists of...
7 Apr 2011 by MNMR
Hello people.Who can explain, why when we need to set some data members in some class, sometimes we use:1) accesors like void setSomeData(int mydata){itsdata = mydata}; // if we use default constructor??? 2) sometimes we use constructors like myConstructor(int mydata){itsdata = mydata}...
22 Aug 2011 by BobJanova
How about an extension method?public DateTime GetTimeJobSubmittedCustom(this PrintSystemJobInfo target){ return target.TimeJobSubmitted + get the time zone offset from settings;}You can get the current time zone from the locale settings somewhere.
2 Dec 2011 by strogg
The SetScrollPos just does that. Wont update the window.You can use the SendMessage() function to get/set scroll position. Here's the interopPrivate Declare Auto Function RtfScroll _ Lib "user32.dll" Alias "SendMessage" ( _ ByVal hWnd As IntPtr, _ ...
12 Feb 2012 by CDP1802
No, it's better not to do that. Inheritance creates a far too strong dependence between the application logic and the data access logic. Just try to estimate the work involved when you have to rewrite the data access classes when migrating to another database. Instead, the DAOs should expose an...
18 Mar 2012 by Clifford Nelson
The perfered method for the disposal of resources is the Dispose method, not the destructor. When finished using a resource, and this is only required if a class needs to dispose of some resource, then call the Dispose method when finished using the class that is using the resource. That means...
16 May 2012 by Wendelius
If I understood correctly, you can cast an object instance to your interface like:testinterface someVar = originalVar as testinterface;after that someVar should contain the variable as your interface if the original instance implemented the interface. If it didn't, someVar is null.
28 Jul 2012 by Christian Graus
Are you going between forms ? The easiest way to do this, is to create your forms as controls and show them one at a time, so you don't get the effect that Windows does on a new form, b/c the form never changes.
29 Sep 2012 by OriginalGriff
The problem is that anything which "properly" demonstrates those is either going to be small - as you have probably seen - in order to highlight those specific features, or large (because it is real world and thus not trying to show you anything).You are probably best off looking a a book,...
5 Oct 2012 by Bryan Lyman
Generic list wrapper that returns a smaller strongly typed sub-list which modifies the parent-list when changed, without using events
4 Nov 2012 by Valery Possoz
Hello.You are asking a very tricky question and it is quite hard to give an answer, but it seems that what you want to do is ok.According to the wikipedia article on LGPL:http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License[^]The non-(L)GPLed program can then be...
3 Jan 2013 by Sander Rossel
So I'm having a relatively simple task of looping through all Controls on a Form, something I've done many times before without troubles. This time I do have a problem though. The Form I'm passing to my function has a base Form which already has some Controls on it. Now the problem is that my...
3 Jan 2013 by Sander Rossel
I found my own solution to this one. Sooner than expected too (although it still cost me an entire morning...).What I was looking at were the fields of my Form, all TextBox fields, Button fields, etc.However, they weren't placed on my Form yet, so they were also not yet added to the Controls...
11 Apr 2013 by Sergey Alexandrovich Kryukov
Attributes in .NET is something completely different: please read on attributes to understand it: http://msdn.microsoft.com/en-us/library/z0w1kczw%28v=vs.110%29.aspx[^].What you call "attributes" are more like the UML meaning of this word (do you know UML?). In .NET, the attributes in UML...
12 Apr 2013 by Philippe Mori
By doing that, you are going against the design principles of STL.Maybe you can consider doing something like:template void Iterate(const T &container, F func, bool forward){ if (forward) { std::for_each(container.begin(), container.end(), func); } else ...
19 Jul 2013 by Gaurav_Chhatbar
Object oriented implementation of basic language processing / parsing leveraging LINQ / PRISM / UnityContainer.
22 Jul 2013 by Sarin VT
Is it a good coding practice to use inheritance of Interfaces.the IBird interface has many bird behaviours defined along with the Fly() behaviour. Now, if a Bird class (say, Ostrich) implements this interface, it has to implement the Fly() behaviour unnecessarily (Ostrich doesn't...
17 Oct 2013 by johannesnestler
use the protected keyword if you have access to the code you want to derive from. In General, a look at http://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx[^] is maybe a good idea.You don't have the code you want to derive (because it's in closed source lib) - you are out of look. The only...
23 Dec 2013 by TrushnaK
try this:-namespace ConsoleApplication1{ class baseClass { protected int i = 13; } class prog : baseClass { int i = 9; int b = 9; public void printMethod() { Console.WriteLine(i); //this will give 9 ...
26 Feb 2014 by CPallini
Quote:1. Why I am not able to access S class method. You actually can.Since, by the very inheritance concept, M is S, you may call it.However, M::myFunc hides S::myFunc, so you need a workaround, e.g.:int k = (mm as S).myFunc(1,2); Quote:2. And why am I able to create the method...
7 Mar 2014 by Snehasish_Nandy
You can refer below link..it's a nice explanation providedprototypal[^]even you can refer this alsoprototypal inheritance[^]
9 Mar 2014 by OriginalGriff
It's just for illustration.It doesn't really work as an example is you haveBaseClass bc = new BaseClass();bc.MyMethod();DerivedClass dc = new DerivedClass();dc.MyMethod();Giving:BaseClass MyMethod calledDerivedClass MyMethod calledBecause you could get that result without deriving...
24 Apr 2014 by Sanket Saxena
You should try Google first.Try the below link hope it helps.Practicle example
5 Aug 2014 by Stefan_Lang
Change i_temp = sale_list.at(i);to i_temp = s_temp->sale_list.at(i);
25 Sep 2014 by BillWoodruff
Your test program 'printf method gets a single parameter of Type Base: so, even if a valid instance of Class A, or Class B, is passed to it, it will always call the 'printf method defined in Base.By declaring the parameter of Type Base, you essentially down-cast the instance of A, or B, to...
3 Dec 2014 by Sergey Alexandrovich Kryukov
It looks like the title and the body of the question are different post.Not only what is you say in the title is impossible, these words simply make no sense. Same goes to the combination of tags "inheritance", "types" and "override". "Override" is a central concept of OOP, it is only...
15 Feb 2015 by Zoltán Zörgő
You can access any object using a reference of it's ancerstor's (parent or above) type. Of course in this case you have access only to the fields defined at that level. That's the difference. BMW myBMW = new BMW();You can access all field defined in Object, Car and BMW.Car myCar = new...
9 Nov 2015 by xszaboj
Well your best option is stick to principles like SOLID.And also use design patterns:http://www.dofactory.com/net/design-patterns[^]In you case I would suggest patterns like Builder, Factory Method, Decorator, Template Method or Visitor.Just try to make a quick look on them and think...
9 Nov 2015 by Sergey Alexandrovich Kryukov
Sorry that I'm not giving you any definitive advice. Without knowing all essential detail of your project, it would be simply impossible. Only a very general advice could be given. I think you do not expect such advice yourself. If feels like you just need some reassurance.I want to say...
18 Nov 2015 by CPallini
Try:void Agent::delete(int flightNumber){ vector::iterator ptr; for(ptr=flightList.begin();ptr!=flightList.end();ptr++) { if( ptr->FlightNumber == flightNumber) { flightList.erase(ptr); return; } } if ((ptr)...
13 Jul 2016 by Bernhard Hiller
Depends.You could say: not at all, as multiple inheritance does not exist in C#.You could say: let's use some tricks. Like that:Interface IA{ Method A();}Interface IB{ Method B();}Then let's add some wrappers which implement the interfaces and just pass thru to the...
13 Jul 2016 by F-ES Sitecore
My answer would be that you can't. Some interviewers will ask you these kinds of questions to test your confidence and see if you have genuine knowledge or are just trying to game the interview process.
4 Aug 2016 by Wastedtalent
You should be passing all the parameters to the Student:public Student(string name, int age, string speciality, int facultynumber) : base(name,age) { this.facultynumber = facultynumber; this.speciality = speciality; }Also, consider...
4 Aug 2016 by Animesh Datta
Hello ,you cannot do this . It can bepublic Student(string name, int age, string speciality, int facultynumber) : base("SomeName",10)orit can bepublic Student(string speciality, int facultynumber) : base(speciality, facultynumber)Thanks
10 Dec 2016 by gfazzola
In this article I will explain the implementation of an infrastructure to host and manage windows services in a practical and interactive way.As a practical example of the solution will be implemented a dynamic ip update client of DucDNS
11 Jun 2017 by OriginalGriff
Declare the method as returning an instance of the base class: Public Function MyMethod() As CodeElement ... End Function It can then return any value which is derived from CodeElement
16 Jan 2018 by Thomas Daniels
You can keep track of a counter variable, which you increase when you come across a C# programmer while iterating over all items in the array. This would be your loop: int counter = 0; foreach (Developer item in d) { if (item.Language == "C#") // change 'Language' into the correct...
17 Feb 2018 by BillWoodruff
What's the point of deriving from a class, if you have to assign its members? Inheritance in C# is a compile-time "copying," or transmission, of structure. It is not a copying of an instance of a Class, and the current values of Fields and/or Properties of the Class instance, to another...
10 Jul 2020 by OriginalGriff
What is Polymorphism? Webopedia Definition[^]: Generally, the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or...
15 Dec 2021 by OriginalGriff
To be honest, I'm not going to go into details because that would mean a close inspection of that code, and what I can see from a cursory glance is that it's ... pretty poor quality. It's pretty much monolithic, it's full of duplicated code and...
16 Dec 2021 by Greg Utas
Once you're finished converting this code to classes, you should have learned that you should design that way from the beginning. Rewriting the code later is a lot of work and is prone to error as you cut and paste fragments into various classes,...
21 Dec 2021 by Gerry Schmitz
You need a "standard" / baseline for inflicting damage; then you vary the damage as the strength varies. e.g. One company (64 men), lying down, open formation, firing, can inflict a loss of 5, in one minute, on the party fired on under similar...
24 Feb 2022 by OriginalGriff
Think about it: all cars have a private glovebox: unless you are the owner of the car you have no idea what is in it. But that doesn't stop the driver opening it and putting his mobile in there, or grabbing a face mask! If A is the base class...
3 Mar 2022 by CPallini
You correctly pass the reference, but didn't use a static field (as explicitly required) for storing the balance. Moreover I suppose it's best to work with integers (using cents of dollar as unit of measure) instead of doubles. Try...
2 Jul 2022 by OriginalGriff
Let's think about what your code does. We have two cars between us: my car (a black Mercedes) and your car (a green BMW). They have a lot of attributes in common: they both have four wheels, the both have a drivers seat, they both have a...
20 Sep 2022 by OriginalGriff
Use a switch rather than if - it's "tidier" code. Then just use an initialiser: switch (discountType) { default: throw new ArgumentException($"Unknown discount type \"{discountType}\""); case PERCENTAGEDISCOUNT: return new...
13 Jul 2023 by Samriddha Chowdhury
class Rectangle:Shape { double height; double width; public Rectangle(double height,double width) { this.height=height; this.width=width; } } class Rectangle:Shape { double rec_Height; double...
13 Jul 2023 by FreedMalloc
The keyword 'this' tells the compiler that you are dealing with a class attribute and not some other variable of the same name. It also tells someone else reading your code that a variable being used is a class attribute and not some other...
13 Jul 2023 by Graeme_Grant
Here is the link to the official documentation for the above usage: this keyword - C# Reference | Microsoft Learn[^] Quote: The this keyword refers to the current instance of the class.