• Advertisement
Sign in to follow this  

[solved. and I thought I wasn't a n00b, hah] "no appropriate default constructor"

This topic is 3659 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

MSVC++ express 2005 confuses me. I get this damn error, apparently for no reason. Just look at the code & comments. What's wrong?

class B
{
	class C
	{
	};


public:
	B(const B& b)
	{
		_val = b._val;
	}


private:
	B(C* val)
		:	_val(val)
	{
	}


	C*    _val;

};


//--------------------------------------------------------

class A
{
public:
	//
	// works just fine. if the c'tor below is commented out,
	// the program compiles and runs.
	//
	A&	operator=	(const A& a)
	{
		_i   = a._i;
		_val = a._val;
	 return *this;
	}


	//
	// does the same as above operator, BUT:
        // "error C2512: 'B' : no appropriate default constructor available"	
        // WHY ???
	// (why should it need a default c'tor here anyway???)
	//
	A(const A& a)
	{
		_i   = a._i;
		_val = a._val;
	}



private:
	A(int i, A& a)
		:	_val(a),
			_i(i)
	{
	}


        B    _val;
        int  _i; 
};	




[Edited by - UnshavenBastard on February 13, 2008 12:01:04 AM]

Share this post


Link to post
Share on other sites
Advertisement
Quote:
//
// does the same as above operator, BUT:
// "error C2512: 'B' : no appropriate default constructor available"
// WHY ???
// (why should it need a default c'tor here anyway???)
//
A(const A& a)
{
_i = a._i;
_val = a._val;
}


Because in order to assign to _val, it must first be constructed using default constructor, and then assigned to this instance. The above does the following:
B _val; // default constructor
_val = a._val;


Solution: use initializer lists:

A(const A& a)
: _val(a._val) // use same order as the one your variables are declared in
, _i(a._i)
{}


It's also more efficient.

Share this post


Link to post
Share on other sites
lol, thanks man. I normally always do it with initializer lists, I guess I've never tried it this way under such circumstances before. It's funny, I use C++ now for ~10 years and never screwed that one up, lol. Might have been due to copy-&-paste'ritis.
Although I never thought about this detail how c++ does this.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement