Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
programming:cpp-style-tips [2009/10/08 09:49] cyril |
programming:cpp-style-tips [2013/09/19 16:41] (current) |
||
---|---|---|---|
Line 248: | Line 248: | ||
===== Copy of abstract objects ===== | ===== Copy of abstract objects ===== | ||
+ | |||
+ | ==== Clone function ==== | ||
You have an abstract class, and several implementations of this class. You have a pointer to the abstract class, but you don't know which implementations it is, and you want to make a copy of this object. The solution is to use a '' | You have an abstract class, and several implementations of this class. You have a pointer to the abstract class, but you don't know which implementations it is, and you want to make a copy of this object. The solution is to use a '' | ||
Line 258: | Line 260: | ||
}; | }; | ||
- | class Type1Descriptor | + | class Type1Descriptor: public Descriptor |
{ | { | ||
| | ||
virtual Descriptor* clone() | virtual Descriptor* clone() | ||
{ | { | ||
- | | + | |
- | return result; | + | |
} | } | ||
}; | }; | ||
Line 275: | Line 276: | ||
{ | { | ||
my_descriptor = modelDescriptor-> | my_descriptor = modelDescriptor-> | ||
- | // I want a copy of the object, and not a reference, eg because I will customize it | ||
} | } | ||
}; | }; | ||
</ | </ | ||
+ | ==== Factory model ==== | ||
+ | |||
+ | If you just want to copy the configuration parameters of the class, you can create a Factory class that will have the same constructor parameters than your class and will store them internally, and that has a '' | ||
+ | |||
+ | <code cpp> | ||
+ | class Descriptor | ||
+ | { | ||
+ | | ||
+ | virtual void describe() = 0; | ||
+ | Descriptor(int param1, int param2): param1(param1), | ||
+ | }; | ||
+ | |||
+ | class DescriptorFactory | ||
+ | { | ||
+ | | ||
+ | virtual Descriptor* create() const = 0; | ||
+ | } | ||
+ | |||
+ | class Type1Descriptor: | ||
+ | { | ||
+ | int param1; | ||
+ | int param2; | ||
+ | int internalData; | ||
+ | | ||
+ | Descriptor(int param1, int param2): param1(param1), | ||
+ | virtual void describe() { ... } | ||
+ | }; | ||
+ | |||
+ | class Type1DescriptorFactory: | ||
+ | { | ||
+ | int param1; | ||
+ | int param2; | ||
+ | | ||
+ | Descriptor(int param1, int param2): param1(param1), | ||
+ | virtual Descriptor* create() const | ||
+ | { | ||
+ | return new Type1Descriptor(param1, | ||
+ | } | ||
+ | } | ||
+ | |||
+ | |||
+ | class AnotherClass | ||
+ | { | ||
+ | Descriptor *my_descriptor; | ||
+ | | ||
+ | AnotherClass(DescriptorFactory *descriptorFactory) | ||
+ | { | ||
+ | my_descriptor = descriptorFactory-> | ||
+ | } | ||
+ | }; | ||
+ | </ | ||
===== Inherited parameters ===== | ===== Inherited parameters ===== |