Sign in to follow this  
gameXcore

quick question about inheritance and constructors in c#

Recommended Posts

Hi, i just hit a snag while learning C#, im not really too sure how to explain the problem so ill show what i would have done in C++:
[source language="cpp"]

class class1
{
private:
	int myInt;

public:
	class1(int someInt)
	{
		myInt = someInt;
	}
};

class class2 : public class1
{
public:
	class2() : class1(1);
}


As you can see class 1 has a single constructor that takes an int and stores it, class 2 inherits from class1 but doesnt need to have an int specified when its created because it always uses "1". I cant seem to recreate this in C# though, it wont compile with the error given that there is no overloaded constructor that takes 0 arguments, currently ive hacked around it by including a 0 argument constructor into my base class however there must be a way to do this in c#, can anyone help me out with this? Thanks, Scott (on side question, when people post example classes like those up there, they always call them "foo" and "bar", what exactly do they stand for? =])

Share this post


Link to post
Share on other sites
Use the "base" keyword to call the base class constructor.

class class1 {
private int myInt;

public class1(int someInt){
myInt = someInt;
}
}

class class2 : class1 {

public class2() : base(1){
}
}




Quote:

(on side question, when people post example classes like those up there, they always call them "foo" and "bar", what exactly do they stand for? =])

Metasyntactic Variables

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this