Reputation: 9866
I know it's frequently asked question but I can't figure out a way for my code to work, so I'll be glad to get some help.Here's the code:
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cmath"
#include "ctime"
using namespace std;
class quad{
int Lice;
public:
quad(int x, int z){
Lice = x*z;
}
int ShowLice(){
return Lice;
}
};
class tri : public quad{
int Lice;
public:
tri(int a, int b, int c){
Lice = a*b*c;
}
};
int main(){
quad ob1(2,2);
tri ob2(2,2,2);
cout<<ob1.ShowLice();
cout<<ob2.ShowLice();
return 0;
}
I use VS2008 and the error from the compiler is :
project1.cpp(20) : error C2512: 'quad' : no appropriate default constructor available
Thanks, Leron.
Upvotes: 3
Views: 2586
Reputation: 24403
Change it to
class quad{
protected:
int Lice;
public:
quad(int x, int z){
Lice = x*z;
}
int ShowLice(){
return Lice;
}
};
class tri : public quad{
public:
tri(int a, int b, int c) : quad(a,b) {
Lice *= c;
}
};
No point in having a Lice member in both derived and base class. Make it protected so that both derived and child classes reuse the same field.
If you have a non default constructor in base class you have to invoke the base class constructor with the right arguments from the derived class constructor like i have shown above.
Also if you use inheritance it is a good idea to provide a virtual destructor in base class. The problem might not be apparent in your example code.
Upvotes: 3
Reputation: 62472
You're tri
constructor is trying to call the default constructor in quad
. You didn't add this code, the compiler did it for you to ensure that the base class is correctly initialized.
Since there's no default constructor you'll have to explicitly call the constructor in the base that you want to use, even though there's only one. You'll do it like this:
tri(int a, int b, int c) : quad(a,b){
Lice = a*b*c;
}
Or whatever are the appropriate arguments you want to pass to quad
.
Upvotes: 0
Reputation: 6208
When you construct a class of type tri it goes up the inheritance tree and tries to create a quad. It can't because quad has no default constructor. To fix this error you can either explicitly call quad's constructor or provide a default constructor that will be called.
In C++ a default constructor is automatically generated when no constructor is given, but as soon as any constructor is defined the default constructor is no longer auto generated. This occurs even if no default constructor is defined.
Upvotes: 2
Reputation: 121971
You need to call the constructor of quad
from the initializer list of tri
:
tri(int a, int b, int c) : quad(a,b) {...
Upvotes: 2