Reputation: 11
The __new__
override in Python allows you to construct an object of a completely different class using the constructor of one class. Was wondering if there was any way to achieve this in C++, or any other language for that matter? Writing a certain solving software, originally in Python, then moved to Java for speed reasons and also clarity of structure, and had a pseudo way of achieving this for Java, but since C++ is more flexible and versatile maybe the real thing might be possible. Thanks the consideration
Upvotes: 0
Views: 214
Reputation: 2117
A literal translation of what you want to do would probably go like this:
class A {};
class B {};
class C {};
void* create_object(char class_letter) {
switch (class_letter) {
case 'A': return new A;
case 'B': return new B;
case 'C': return new C;
default: return new A;
}
}
Everyone who had his first C++ lessons including the usual recommendations knows this is bound to explode. Why? Look: You could call this function like this:
void* ptr = create_object('B');
You get a void*
which is not a nice thing to have, because now it's your duty to cast it to the correct type for example by doing:
B* b_ptr = (B*)ptr; // eww!
and equally important - now it's also your duty to delete
it (yuck!), which is a popular thing us coders tend to forget.
Bottom line is, it's doable - as always, but ugly. So use a different design pattern if you plan on implementing this in C++.
Upvotes: 0
Reputation: 5222
Memory for an object is allocated before the constructor is called.
And since C++ is not a dynamically typed system, you cannot change the type of the object at runtime.
Use a factory function instead.
Upvotes: 5