I dont understand why, when i try to create a object of a base class, i can, but only without declaring derived class, and when declare Derived i need to set argument value to "= 0" in base class constructor?
#include <cstdlib>
using namespace std;
class Base {
public:
int m_nValue;
Base(int nValue=0) //<--- why here i need = 0 ?
: m_nValue(nValue)
{}
};
class Derived: public Base {
public:
double m_dValue;
Derived(double dValue)
: m_dValue(dValue)
{}
};
int main(int argc, char** argv) {
Base cBase(5); // use Base(int) constructor
return 0;
}
No you don't. The problem is that when you subclass, you never give any value to the base class ctor, something like this:
Derived(double dValue) : Base(0), m_dValue(dValue) {}
So the compiler looks at the base class and search either: a ctor with no argument, or a ctor with default values (he doesn't look at the default ctor as defining a ctor removes the default ctor). Either:
class Base {
public:
int m_nValue;
Base() : m_nValue(0) {}
Base(int nValue) : m_nValue(nValue) {}
};
or
class Base {
public:
int m_nValue;
Base(int nValue=0) : m_nValue(nValue) {}
};
Base(int nValue = 0)
will also act as the default constructor, since a default value for nValue
has been supplied. Currently, your Derived
constructor will call this constructor implicitly, with nValue
set to 0.
Formally you don't actually need to do that - but that would mean that the user of your class would have to supply an explicit value for nValue
and you would have to write a default constructor . You could achieve the latter by writing Base() = default;
although then the member m_nValue
will not be initialised unless you use the C++11 curly brace notation (eg Base b{};
). (Note that the behaviour on reading an uninitialised variable is undefined .)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.