Re: new Class(*this)
On Thursday, 9 April 2015 01:25:18 UTC+3, Christopher Pisz wrote:
On 4/8/2015 4:01 PM, Doug Mika wrote:
On Wednesday, April 8, 2015 at 2:28:26 PM UTC-6, Doug Mika wrote:
I have the following two classes:
class Fish{
public:
virtual Fish* Clone()=0;
virtual void Swim()=0;
};
class Tune:public Fish{
public:
Fish* Clone(){
return new Tuna(*this);
}
void Swim(){
cout<<"Tuna swims fast in the sea"<<endl;
}
};
my question is, what is new Tuna(*this) when Tuna doesn't define a constructor that takes a parameter. It only has the default parameterless constructor! So what is: new Tuna(*this);
Much thanks
Doug
so the "new" keyword can invoke the copy constructor?
You get a default constructor, copy constructor, deconstructor if one is
not defined.
Default constructor you get only if there are no constuctors defined
whatsoever. You mean destructor or move constructor with that
"deconstructor"? Destructor will be always made implicitly.
Copy and move assignment and copy and move constructor will be made
if possible.
It is legacy from C and cause serious amount of confusion among
novices. Abstract base classes that do not declare all the five
(besides default constuctor that won't be generated) let that
legacy from C to manifest itself by casual object slicing.
To make object slicing way harder we should either make destructor
of base class that won't be instantiated as separate object either
virtual or protected. Assignments we should make deleted.
If copy and/or move is planned to be possible then we should make
according constructor protected, otherwise deleted.
It is not the "new" keyword, but the fact that you are creating a Tuna.
You could also have created it on the stack and had the same effect,
although its lifetime would have ended when it went out of scope.
It is also unwise to implement such methods as "Clone". Silly methods
like those are often carried over from people who want to shape and mold
C++ to be like Java or wherever they came from. We don't need a clone
method, because we already have the means to make a copy...via the copy
constructor:
It is not silly. Sometimes we need dynamic polymorphism in C++.
Often we need it for components of bigger object to be dynamically
polymorphic. Sometimes we later need a deep copy made from object that
contains dynamically polymorphic components. Lack of such 'virtual clone'
will cause that deep copy to be a big silly mess.