Sign in to follow this  
tendifo

default constructor

Recommended Posts

Can someone explain why this works...
class A
{
public:
	A() {}
};

class B : public A
{
public:
	B() {}
	B(int a) {}
};

class C : public B
{
public:
	C() {}
	C(int a, float b) {}
};

int main()
{
	C j(0, 1);
	system("pause");
	return 0;
}
but this doesn't?
class A
{
public:
	A() {}
};

class B : public A
{
public:
	B(int a) {}
};

class C : public B
{
public:
	C(int a, float b) {}
};

int main()
{
	C j(0, 1);
	system("pause");
	return 0;
}
I'm using MSVS 2002. My error is: "error 2512: 'B' : no appropriate default constructor availible." Why do I need a a default constructor when the instance I'm declaring doesn't use it? Thanks.

Share this post


Link to post
Share on other sites
In an inheritence tree, you actually generate an object that is a valid X for any X in the tree.

so all of these are valid in your example
A *x = &j;
B *x = &j;
C *x = &j;

That means that you need a default constructor for each object. If you dont want them accessable you can put them in the protected: section of the class definition.

Share this post


Link to post
Share on other sites
by declaring a constructor at all for B you disable the "default" constructor. the default constructor is one that doesn't take any arguments. to fix your compile error you want this:


class B : public A
{
public:
B(int a) {}
};

class C : public B
{
public:
C(int a, float b): B(a) {}
};

int main()





note the addition of : B(a) after C's constructor. that says, construct me using this specific constructor of my parent class.


Quote:

Why do I need a a default constructor when the instance I'm declaring doesn't use it?

ahhh! but you ARE using the B constructor. when a class gets constructed, the whole chain of parent class constructors also need to get called. If you declare B to have a constructor that takes a manditory argument "int a", then you have to tell the compiler how B's constructor should get called. That little text i added explains to the compiler how to execute the construction of B within a C object.

-me

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