#include <iostream>
class MyAbstract
{
public:
MyAbstract()
{
}
MyAbstract& operator=(const MyAbstract & other)
{
if (this != &other)
{
copy(other); //invoke the subclass copy method
}
return *this;
}
virtualvoid copy(const MyAbstract & other) = 0;
virtualvoid abstractMethod() const = 0;
};
class Implement : public MyAbstract
{
public:
int a_;
Implement(int a)
{
a_ = a;
}
Implement(const Implement &other)
{
copy(other);
}
/*!
* This method is called from the parent operator=
*/
void copy(const MyAbstract & other)
{
const Implement *aux = (const Implement *) & other;
a_ = aux->a_;
}
void abstractMethod() const
{
std::cout << "value of a_ = " << a_ << std::endl;
}
};
class UseAbstract
{
public:
UseAbstract(MyAbstract *abstract)
{
abstract_ = abstract;
}
UseAbstract& operator=(const UseAbstract &other)
{
if (this != &other)
{
*abstract_ = *(other.abstract_);
}
return *this;
}
void useAbstractMethod()
{
abstract_->abstractMethod();
}
private:
//private because abstract_ is uninitialized
UseAbstract(const UseAbstract &other)
{
//this causes a crash
//*abstract_ = *(other.abstract_);
}
MyAbstract *abstract_;
};
int main()
{
Implement * abstract1 = new Implement(1);
Implement * abstract2 = new Implement(2);
UseAbstract useabstract1(abstract1);
UseAbstract useabstract2(abstract2);
useabstract2.useAbstractMethod();
useabstract2 = useabstract1;
useabstract2.useAbstractMethod();
delete abstract1;
delete abstract2;
return 1;
}
The management of the memory is done by the client code, in this case 'main'.
What are your thoughts about this code?
Be aware that the copy constructor is private in UseAbstract. Because I do not want the client code to do something like this
UseAbstract useabstract3 = useabstract2; //crash
JLBorges the clone idiom you talk about is very interesting, but I do not want to use it because I want the memory be managed by the client of the class ('main' here).
Ok, so UseAbstract::abstract_ is just a pointer to something external. It's not managing an allocated object or block of memory, so the copy constructor is:
The management of the memory is done by the client code, in this case 'main'.
What are your thoughts about this code?
Thoughts; manual memory management is a bad thing. I think it should be heavily, heavily avoided. Create objects on the stack where you can, manage them with smart pointers where you must, and use raw memory management carefully wrapped in thin manager classes where you have to work with legacy (i.e. manual memory management relying on meatspace enforcement). Writing brand new legacy code, such as this, is bad.