"Mangabasi" <[EMAIL PROTECTED]> wrote: > Hi there, > > I need to translate the following code (rather something similar) to > C++. I have been studying C++ for the last two days but I could not > find an easy way to do the following Python snippet. > > > class A: > def __init__(self, x): > self.x = x > def methodA(): > pass # Ignore the details > class B: > def __init__(self, x): > self.x = x > def methodB(): > def methodB(): > pass # Ignore the details > class C: > def __init__(self, A, B): > self.A = A > self.B = B > > a = A(5) > b = B(5.5) > c = C(a, b) > print c.A.x > print c.B.x > #so far I can do it in C++ > #how do I do the following in C++? > d = C(b, a) > print d.A.x > print d.B.x
In python this works thanks to "duck typing"; as long as both A and B instances have an attribute 'x', A.x and B.x work as expected without the need for type declarations. In C++ (and other statically typed languages) there is no duck typing, so you can't translate it from python verbatim. The typical (if not only) way to achieve the same in C++ is to have A and B inherit from a common parent class, say X, and drag the common interface and implementation of A and B to X. Of course you could (or perhaps should) do the same in python: class X: def __init__(self, x): self.x = x class A(X): def methodA(): pass # Ignore the details class B(X): def methodB(): pass # Ignore the details class C: def __init__(self, x1, x2): self.x1 = x1 self.x2 = x2 So the constructor of C would take two X instances, and the respective attributes x1 and x2 would be declared as pointers to X. HTH George -- http://mail.python.org/mailman/listinfo/python-list