0

From what I've understood a Copy Constructer is called when an object is passed by value in a method.

So if I implement my own Copy Constructer, is there a way to avoid slicing when I pass an object by value in a method?

Example :

// in headers file
// for A
class A
{ 
    public :
        virtual void Display() const
         { cout << "A::Display() was called << endl; }
};

// for B
class B : public A
{ 
    public :
        void Display() const
         { cout << "B::Display() was called << endl; }

//---> here I would created a copy constructer
};

in a main.cpp file I do this :

void f( A anA)
{
    anA.Display();
}

int main() 
{
    B anB; 
    f ( anB );
    return 0;
}

From what I understand, when this is done, anB is copied into anA ( the formal parameter of the method f) :

f ( anB );

Is there a way for it to output "B::Display() was called" (without passing by reference or using a pointer)?

Thanks!

CSstudZ
  • 101
  • 10
  • There isn't. If you want to pass by value you need to construct `B` from `A` in `f()`. But that is just awkward since you do have `B` to begin with... You do have that method virtual so to make use of it you would need to at least use `const &` or perhaps more readable `const *` to `A` as argument to `f()`. Why do you want to pass by value? – Resurrection Dec 13 '19 at 06:36
  • Nope, an object declared as a class will always be exactly that class you can't make it into a subclass. Is there a reason you're against using a reference here? – Alan Birtles Dec 13 '19 at 06:36
  • It's of course possible (e.g. by adding a layer of indirection to these classes) ... but doesn't make much sense. seems like an XY problem to me. what are you trying to accomplish? – Daniel Jour Dec 13 '19 at 07:27
  • @CSstudZ you're missing a virtual destructor too – Moia Dec 13 '19 at 10:35

1 Answers1

0

No, there isn't. When you declare void f(A anA) f gets it's own fresh A. There isn't a B there.

You can prevent slicing by deleting As copy constructor. Then no-one can slice calling f, because no-one can call f.

Caleth
  • 52,200
  • 2
  • 44
  • 75