I have those two classes
///////////BASE CLASS
class Base{
public:
Base(int = 0);
~Base();
Base(Base&);
Base(Derived&); ////<-may be problem here?, note: I tried without this function
int valueOfBase();
protected:
int protectedData;
private:
int baseData;
};
/////////////DERIVED CLASS
class Derived: public Base{
public:
Derived(int);
//Derived(Derived&);
~Derived();
private:
int derivedData;
};
and here my main
int main(){
Base base(1);
Derived derived = base;
return 0;
}
I read that if my derived class doesn't have copy c'tor copy c'tor of the base will be called
but every time I receive conversion from Base to non-scalar type Derived requested
who is wrong? my compiler or my book, or I've just misunderstood? thanks in advance
class some_class { public : some_class(some_class const &instance_); // Copy-constructor some_class(some_class &instance_); // Default constructor }; When dealing with inheritance, be sure to invoke the base-copy-constructor, because otherwise, the base will not be affected.
Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.
Copy constructor is not inherited.
Just a hint.
Does the following code give the same error?
class base{};
class derived: public base{};
int main()
{
derived d= base();
}
Yes? Why? Because there is no conversion from the base class to the derived class. You should define this conversion if you want your code to compile.
How about adding this to the derived class ?
derived(const base &b){}
Makes sense, huh?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With