I have a base class A. Another class B derived from base class A.
Class A does not have a default constructor because it is class defined in the c++ library. I am trying to overload a function of class A in class B.it gives me an error sying no deafult constructor available in class A. How can i solve this problem?
class A // defined in the library...which i cant edit it
{
//no default constructor defined like A(){}
//there are other constructors with input arguments define like
A(int i) { };
//function in this class
int wait()
{
//do something
}
}
//header file of class B
class B: public A
{
public:
//overload the wait function
using A::wait;
int wait(int tokens);
}
//cpp file of class B
int B::wait(int tokens)
{
//do something different from other wait function
}
In the above example...since class A doesnt have a default constructor it gives me an error saying default construtor not available...how can i solve this
You have to define a constructor within class B that calls one of the constructors of class A. The compiler will generate a default constructor for class B but since B inherits from A, you must call one of A's defined constructors. The only way to do that is by defining one in B. Since A has a custom constructor it has no compiler generated default constructor. Therefore its constructor must be called manually and supplied with an appropiate argument. In this case I simply passed it a 0 but you'd need to pass it whatever value makes sense for your application.
1 2 3 4 5 6 7 8 9 10
class B: public A
{
public:
B() : A(0) {}
//overload the wait function
using A::wait;
int wait(int tokens);
}