Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, does a constructor that takes the base class count as a copy constructor?

For example:

class Derived : public Base
{
    Derived(const Base &rhs)
    {
        // Is this a copy constructor?
    }
    const Derived &operator=(const Base &rhs)
    {
        // Is this a copy assignment operator?
    }
};
  1. Does the constructor shown count as a copy constructor?
  2. Does the assignment operator shown count as a copy assignment operator?
like image 240
Matt Avatar asked Feb 17 '23 12:02

Matt


1 Answers

Does the constructor shown count as a copy constructor?

No. It does not count as a copy constructor.
It is just a conversion constructor not a copy constructor.

C++03 Standard Copying class objects Para 2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.


Does the assignment operator shown count as a copy assignment operator?

No, it doesn't.

C++03 Standard 12.8 Copying class objects Para 9:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.


Online Sample:

#include<iostream>
class Base{};
class Derived : public Base
{
   public:
    Derived(){}
    Derived(const Base &rhs)
    {
       std::cout<<"\n In conversion constructor";
    }
    const Derived &operator=(const Base &rhs)
    {
        std::cout<<"\n In operator=";
        return *this;
    }
};

void doSomething(Derived obj)
{
    std::cout<<"\n In doSomething";
}
int main()
{
    Base obj1;
    doSomething(obj1);


    Derived obj2;
    obj2 = obj1;    
    return 0;
}

Output:

In conversion constructor
In doSomething
In operator=
like image 79
Alok Save Avatar answered Apr 06 '23 05:04

Alok Save