Skip to content
Advertisement

c++ equivalent to python self.attribute = ObjectInstance()

i want to know if there is an equivalent way of doing this in c++:

class B:
    def foo(self,parameter):
        print("B method call from A, with non static method",parameter)

class A:
    def __init__(self):
        self.b = B()

parameter = 10
a = A()
a.b.foo(parameter)

Advertisement

Answer

self.b in C++ could be this->b, but also just b as this is implicit in C++.

However, in C++, you have to declare (member) variables, while in Python you create them by assigning to them and the type of the variable is determinated by this assignment and can be changed. So next code is similar (not compiled, tested):

#include <iostream>

class B { public: void foo(int x) { std::cout << x << "n"; } };

class A { public: B b; }

int main() { A a; a.b.foo(3); }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement