C
C#13mo ago
Finnland

I cant figure out constructor inheritance

how do i inherit classes, including their constructors? no matter what i try i get a wide variety of different errors. i have tried just:
public class SubClass : Superclass {

}
public class SubClass : Superclass {

}
but then i get the error
'SuperClass' does not contain a constructor that takes 0 arguments
'SuperClass' does not contain a constructor that takes 0 arguments
so then i tried adding
public class SubClass : Superclass {
public SubClass(arg) : base(arg)
{

}
}
public class SubClass : Superclass {
public SubClass(arg) : base(arg)
{

}
}
but that gives me an error that i need a method body. How do i inherit the constructors in addition to the rest of the class?
5 Replies
Jimmacle
Jimmacle13mo ago
your example looks mostly correct, are you missing a data type for your subclass constructor arguments in your actual code?
Finnland
FinnlandOP13mo ago
ohhh yes thats it thank you i was so confused by the vsc errors (which didnt say anything like that) that i completely missed it
Odd_Dev_404
Odd_Dev_40413mo ago
@SyncRооt - I have a question. In the first code it has just inherited from the base class. public class SubClass : Superclass { } I'm bit confused why it's giving an error as 'SuperClass' does not contain a constructor that takes 0 arguments Any idea?
Odd_Dev_404
Odd_Dev_40413mo ago
@SyncRооt - Got it thanks! I was aware about that "No constructor, so the compiler places an implicit public empty constructor" But wasn't aware constructor inheritance is not supported within C# at this moment until you mentioned that. In this link's first example - https://www.geeksforgeeks.org/c-sharp-inheritance-in-constructors/ isn't an example related to constructor inheritance?
GeeksforGeeks
C# | Inheritance in Constructors - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Odd_Dev_404
Odd_Dev_40413mo ago
@SyncRооt - Now got it. Thanks again. Although it's almost similar the wordings "inheritance and constructors" and "constructor inheritance", thos two are different concepts right?
Want results from more Discord servers?
Add your server