#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class A{
public:
A(string a){ cout << "lovely me "; }
};
class B{
A a1;
string name;
};
int _tmain(int argc, _TCHAR* argv[])
{
B b1;
return 0;
}
Output :
Error 1 error C2512: 'B' : no appropriate default constructor available
Explanation :
There are four types of compiler generated functions :
1.)Copy Constructor
2.)Assignment Operator
3.) Default constructor
4.) Default destructor.
And these functions are generated only if there is need for it.
For example, like in the code given above, compiler would try to generate a default constructor for B ( B b1)
which in turn would call the default constructor for its data members i.e. for the statement A a1.
So In class A, compiler would try to find for a default constructor, but it finds one constructor there with a parameter. So it is not able to find a default constructor for A. and hence it fails to generate a default constructor for B as well. Hence the error.
Some compilers may throw an information like the
candidates are B::B(const B&)
This is for the reason that compiler would find copy constructor as the next possible match as copy constructor is also generated by compiler itself.
To remove the error :
class A{
public:
A(){ cout << "lovely me "; }
};
#include<string>
#include<iostream>
using namespace std;
class A{
public:
A(string a){ cout << "lovely me "; }
};
class B{
A a1;
string name;
};
int _tmain(int argc, _TCHAR* argv[])
{
B b1;
return 0;
}
Output :
Error 1 error C2512: 'B' : no appropriate default constructor available
Explanation :
There are four types of compiler generated functions :
1.)Copy Constructor
2.)Assignment Operator
3.) Default constructor
4.) Default destructor.
And these functions are generated only if there is need for it.
For example, like in the code given above, compiler would try to generate a default constructor for B ( B b1)
which in turn would call the default constructor for its data members i.e. for the statement A a1.
So In class A, compiler would try to find for a default constructor, but it finds one constructor there with a parameter. So it is not able to find a default constructor for A. and hence it fails to generate a default constructor for B as well. Hence the error.
Some compilers may throw an information like the
candidates are B::B(const B&)
This is for the reason that compiler would find copy constructor as the next possible match as copy constructor is also generated by compiler itself.
To remove the error :
class A{
public:
A(){ cout << "lovely me "; }
};
No comments:
Post a Comment