I have two classes Base
and Derived
from it:
class Base{
public:
Base(int = 0);
Base(Base&);
Base& operator=(const Base&);
protected:
int protectedData;
private:
int baseData;
};
/////////////DERIVED CLASS
class Derived: public Base{
public:
Derived(int = 0);
Derived(Derived&);
Derived(Base&);
Derived& operator=(const Derived&);
private:
int derivedData;
};
implementation of the functions
///////////BASE FUNCTIONS
Base::Base(int value): protectedData(value), baseData(value)
{
cout << "base C'tor" << endl;
}
Base::Base(Base& base)
{
baseData = base.baseData;
protectedData = base.protectedData;
cout << "base Copy C'tor" << endl;
}
Base& Base::operator=(const Base& base)
{
if(this == &base) return *this;
baseData = base.baseData;
protectedData = base.protectedData;
cout << "Base::operator=" << endl;
return *this;
}
///////////DERIVED FUNCTIONS
Derived::Derived(int value): Base(value), derivedData(value)
{
cout << "derived C'tor" << endl;
}
Derived::Derived(Derived& derived)
: Base(derived)
{
derivedData = derived.derivedData;
cout << "derived Copy C'tor" << endl;
}
Derived::Derived(Base& base)
: Base(base), derivedData(0)
{
cout << " Derived(Base&) is called " << endl;
}
Derived& Derived::operator=(const Derived& derived)
{
if(this == &derived) return *this;
derivedData = derived.derivedData;
cout << "Derived::operator=" << endl;
return *this;
}
With the following in my main:
Base base(1);
Derived derived1 = base;
the compiler gives me an error:
..\main.cpp:16: error: no matching function for call to `Derived::Derived(Derived)'
..\base.h:34: note: candidates are: Derived::Derived(Base&)
..\base.h:33: note: Derived::Derived(Derived&)
..\base.h:32: note: Derived::Derived(int)
..\main.cpp:16: error: initializing temporary from result of `Derived::Derived(Base&)'
but when I have this in main:
Base base(1);
Derived derived1(base);
it works perfectly. Why?
EDITED
so ok thanks for everybody, I checked it with const and all works good, BUT
I check also all calls and in both cases I receive:
base C'tor
base Copy C'tor
Derived(Base&)
my question is, why? You said that I actually call:
Derived(Derived(Base&))
so I must have
base C'tor
base Copy C'tor
Derived(Base&)
Derived copy c'tor //<-note, why this one is missing?