Copy constructor needs base constructor with no arguments [duplicate] - c++

Why aren't copy constructors chained (like default ctors or dtors) so that before the derived class's copy constructor is called, the base class's copy constructor is called? With default constructors and destructors, they are called in a chain from base-to-derived and derived-to-base, respectively. Why isn't this the case for copy constructors? For example, this code:
class Base {
public:
Base() : basedata(rand()) { }
Base(const Base& src) : basedata(src.basedata) {
cout << "Base::Base(const Base&)" << endl;
}
void printdata() {
cout << basedata << endl;
}
private:
int basedata;
};
class Derived : public Base {
public:
Derived() { }
Derived(const Derived& d) {
cout << "Derived::Derived(const Derived&)" << endl;
}
};
srand(time(0));
Derived d1; // basedata is initialised to rand() thanks to Base::Base()
d1.printdata(); // prints the random number
Derived d2 = d1; // basedata is initialised to rand() again from Base::Base()
// Derived::Derived(const Derived&) is called but not
// Base::Base(const Base&)
d2.printdata(); // prints a different random number
The copy constructor doesn't (can't) really make a copy of the object because Derived::Derived(const Derived&) can't access basedata to change it.
Is there something fundamental I'm missing about copy constructors so that my mental model is incorrect, or is there some arcane (or not arcane) reason for this design?

The copy constructor doesn't (can't) really make a copy of the object because Derived::Derived(const Derived&) can't access pdata to change it.
Sure it can:
Derived(const Derived& d)
: Base(d)
{
cout << "Derived::Derived(const B&)" << endl;
}
If you don't specify a base class constructor in the initializer list, its default constructor is called. If you want a constructor other than the default constructor to be called, you must specify which constructor (and with which arguments) you want to call.
As for why this is the case: why should a copy constructor be any different from any other constructor? As an example of a practical problem:
struct Base
{
Base() { }
Base(Base volatile&) { } // (1)
Base(Base const&) { } // (2)
};
struct Derived : Base
{
Derived(Derived&) { }
};
Which of the Base copy constructors would you expect the Derived copy constructor to call?

You can:
Derived(const Derived& d) : Base(d) {
cout << "Derived::Derived(const B&)" << endl;
}
This calls the Base copy constructor on the Base sub-object of d.
The answer for 'why' I don't know. But usually there's no answer. The committee just had to choose one option or the other. This seems more consistent with the rest of the language, where e.g. Derived(int x) won't automatically call Base(x).

That's because every constructor calls by default the default base constructor:
Derived(const Derived& d) {
cout << "Derived::Derived(const B&)" << endl;
}
will call Base().
This is defined by the standard. I for one prefer it like this rather than calling the copy constructor on the class. You can of course call it explicitly.

Related

How to get the move constructor calling deliberately [duplicate]

This question already has answers here:
What are copy elision and return value optimization?
(5 answers)
Closed 7 years ago.
Consider following code:
class Base {
public:
int bi;
Base() : bi(100) {std::cout << "\nBase default constructor ...";}
Base(int i) : bi(i) {std::cout << "\nBase int constructor: "<< bi;}
Base(const Base& b) {std::cout << "\nBase copy constructor";}
Base(Base&& b) {std::cout << "\nBase move constructor";}
};
Base getBase() {
cout << "\nIn getBase()";
return Base();
}
int main() {
Base b2(getBase());
Base b3 = Base(2);
Base b4 = getBase();
}
In spite of rvalues being given, none of the above constructions in main are calling the move constructor. Is there a way to ensure that user defined move constructor is called?
Here is what I am getting:
In getBase()
Base default constructor ...
Base int constructor: 2
In getBase()
Base default constructor ...
Base destructor: 100
Base destructor: 2
Base destructor: 100
You can use std::move() method:
Base b4 = std::move(getBase());
This ensures that move constructor is called, but in this line it prevents copy-elision to optimalize copy constructor out of there. There is no need to call any constructor, so this is more example how to not use std::move().

Why doesn't a derived class use the base class operator= (assignment operator)?

Following is a simplified version of an actual problem. Rather than call Base::operator=(int), the code appears to generate a temporary Derived object and copy that instead. Why doesn't the base assignment operator get used, since the function signature seems to match perfectly? This simplified example doesn't display any ill effects, but the original code has a side-effect in the destructor that causes all kinds of havoc.
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base()\n";
}
Base(int)
{
cout << "Base(int)\n";
}
~Base()
{
cout << "~Base()\n";
}
Base& operator=(int)
{
cout << "Base::operator=(int)\n";
return *this;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived()\n";
}
explicit Derived(int n) : Base(n)
{
cout << "Derived(int)\n";
}
~Derived()
{
cout << "~Derived()\n";
}
};
class Holder
{
public:
Holder(int n)
{
member = n;
}
Derived member;
};
int main(int argc, char* argv[])
{
cout << "Start\n";
Holder obj(1);
cout << "Finish\n";
return 0;
}
The output is:
Start
Base()
Derived()
Base(int)
Derived(int)
~Derived()
~Base()
Finish
~Derived()
~Base()
http://ideone.com/TAR2S
This is a subtle interaction between a compiler-generated operator= method and member function hiding. Since the Derived class did not declare any operator= members, one was implicitly generated by the compiler: Derived& operator=(const Derived& source). This operator= hid the operator= in the base class so it couldn't be used. The compiler was still able to complete the assignment by creating a temporary object using the Derived(int) constructor and copy it with the implicitly generated assignment operator.
Because the function doing the hiding was generated implicitly and wasn't part of the source, it was very hard to spot.
This could have been discovered by using the explicit keyword on the int constructor - the compiler would have issued an error instead of generating the temporary object automatically. In the original code the implicit conversion is a well-used feature, so explicit wasn't used.
The solution is fairly simple, the Derived class can explicitly pull in the definition from the Base class:
using Base::operator=;
http://ideone.com/6nWmx

I'm receiving error when calling base copy constructor

Im receiving error C2082: redefinition of formal parameter 'rval' in this code while trying to call base copy ctor explicitly:
#include <iostream>
using namespace std;
class Base
{
public:
Base(const Base& rhs){ cout << "base copy ctor" << endl; }
};
class Derived : public Base
{
public:
Derived(const Derived& rval) { Base(rval) ; cout << "derived copy ctor" << endl; }
// error C2082: redefinition of formal parameter 'rval'
};
int main()
{
Derived a;
Derived y = a; // invoke copy ctor
cin.ignore();
return 0;
}
However if do it like this:
Derived(const Derived& rval) { Base::Base(rval) ; cout << "derived copy ctor" << endl; }
then is OK.
Why am I asking this?
according to the answers on StackOwerflow
I do not have to use operator :: to access base copy ctor,
so why do I receive this error?
btw: I'm using visual studio 2010.
I'm having one more question:
Do I have to call base's move constructor in user defined move constructor of derived class?
To call the base constructor you need to put the call in the member initalization list
class Derived : public Base
{
public:
Derived(const Derived& rval) : Base(rval)
{
cout << "derived copy ctor" << endl;
}
};
Assuming that you mean 'move' constructor is the copy constructor - Yes. You will have to call the Base's constructor. Otherwise the definition if the base object within the derived object will not be complete. You can either call a copy constructor or a normal constructor of the base class.

Why aren't copy constructors "chained" like default constructors and destructors?

Why aren't copy constructors chained (like default ctors or dtors) so that before the derived class's copy constructor is called, the base class's copy constructor is called? With default constructors and destructors, they are called in a chain from base-to-derived and derived-to-base, respectively. Why isn't this the case for copy constructors? For example, this code:
class Base {
public:
Base() : basedata(rand()) { }
Base(const Base& src) : basedata(src.basedata) {
cout << "Base::Base(const Base&)" << endl;
}
void printdata() {
cout << basedata << endl;
}
private:
int basedata;
};
class Derived : public Base {
public:
Derived() { }
Derived(const Derived& d) {
cout << "Derived::Derived(const Derived&)" << endl;
}
};
srand(time(0));
Derived d1; // basedata is initialised to rand() thanks to Base::Base()
d1.printdata(); // prints the random number
Derived d2 = d1; // basedata is initialised to rand() again from Base::Base()
// Derived::Derived(const Derived&) is called but not
// Base::Base(const Base&)
d2.printdata(); // prints a different random number
The copy constructor doesn't (can't) really make a copy of the object because Derived::Derived(const Derived&) can't access basedata to change it.
Is there something fundamental I'm missing about copy constructors so that my mental model is incorrect, or is there some arcane (or not arcane) reason for this design?
The copy constructor doesn't (can't) really make a copy of the object because Derived::Derived(const Derived&) can't access pdata to change it.
Sure it can:
Derived(const Derived& d)
: Base(d)
{
cout << "Derived::Derived(const B&)" << endl;
}
If you don't specify a base class constructor in the initializer list, its default constructor is called. If you want a constructor other than the default constructor to be called, you must specify which constructor (and with which arguments) you want to call.
As for why this is the case: why should a copy constructor be any different from any other constructor? As an example of a practical problem:
struct Base
{
Base() { }
Base(Base volatile&) { } // (1)
Base(Base const&) { } // (2)
};
struct Derived : Base
{
Derived(Derived&) { }
};
Which of the Base copy constructors would you expect the Derived copy constructor to call?
You can:
Derived(const Derived& d) : Base(d) {
cout << "Derived::Derived(const B&)" << endl;
}
This calls the Base copy constructor on the Base sub-object of d.
The answer for 'why' I don't know. But usually there's no answer. The committee just had to choose one option or the other. This seems more consistent with the rest of the language, where e.g. Derived(int x) won't automatically call Base(x).
That's because every constructor calls by default the default base constructor:
Derived(const Derived& d) {
cout << "Derived::Derived(const B&)" << endl;
}
will call Base().
This is defined by the standard. I for one prefer it like this rather than calling the copy constructor on the class. You can of course call it explicitly.

logic of calling copy constructor

class base {
public:
base(){
cout << "base constructor" << endl;
}
base(const base& rh) {
cout << "base copy constructor" << endl;
}
};
//case 1:
class der : public base {
};
//case 2:
class der : public base {
public:
der(){
cout << "der constructor" << endl;
}
der(const der& rh) {
cout << "der copy constructor" << endl;
}
};
int main() {
der d;
der d1(d);
}
case 1: der d1(d); invokes base class copy constructor whereas in
case-2, base class default constructor and der class copy constructor
is invoked.
Can anyone explain the logic?
In case 1, you get the default copy constructor synthesized by the compiler. This is defined to copy bases and members.
In case 2, you defined your own copy constructor, which does what you tell it to do. You didn't put anything in the initializer list for the base class, so the base is default-constructed[*], same as any other constructor that doesn't explicitly initialize the base. If der had any data members, those would not be copied either.
[*] or one of the other kinds of initialization that amounts to the same thing for non-POD classes. I can never remember those details.
Derived copy constructor will not call base class copy constructor itself by default. When you don't tell the derived class copy constructor to call the base class copy constructor , it will still need to construct the base sub-object, so it will have to call the base default constructor.
But in the example below you , you will see you can add calling to base copy constructor in the member initilize list explicitly of derived class:
class base {
public:
base(int i):m_i(i){
cout << "base constructor" << endl;
}
base(const base& rh) {
m_i = rh.m_i;
cout << "base copy constructor" << endl;
}
private:
int m_i;
};
//case 2:
class der : public base {
public:
der(int i,int j):base(i),m_j(j){
cout << "der constructor" << endl;
}
der(const der& rh):base(rh) {
m_j = rh.m_j;
cout << "der copy constructor" << endl;
}
private:
int m_j;
};
int main() {
der d(1,2);
der d1(d); //d1.m_i = 1, d1.m_j = 2
}
//result
//base copy constructor
//der copy constructor
In the first case, you are not specifying constructors for der, therefore the compiler decides for you, that is copy the data of d to d1 individually, invoking copy constructor of base in the process.
In the second case, you have specified the copy constructor, in which you do not invoke the copy constructor of base yourself. Since you have overridden the copy constructor of der (which tells the compiler to do what you say, not what it wants), the compiler cannot assume you intended to invoke the copy constructor of base too.
Basically there is a call to one copy-con. So in case-2 the copy-con of der is called, and if you like you can use the copy-con of the base in the code. In case one, since you didn't implemented the copy-con in der it calls the function from his base, like it would do with any function that is only implemented in a base class.