-3

I'm pretty new to C++ and I am just experimenting it so I was looking through an exercise book on C++ and I found an interesting problem where you have to use classes. I figured out a solution to it but my solution is writen like I would write it in Javascript. So I started writing it in C++ but I don't know if is it possible and if yes , how to create a member of a class as an object of another class dynamically inside a member function of the same class.In Javascript , I could do this with constructors :

   function AConstructor() {
   this.method = function() {
   this.property = new OtherConstructor() 
   }
   }

Is this possible in C++?

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
Alfi Louis
  • 105
  • 1
  • 2
  • 5
  • 3
    The short answer is: no. C++ does not work this way. – Sam Varshavchik Feb 18 '17 at 15:00
  • You can probably use a `std::map>` as a data member to emulate it. – skypjack Feb 18 '17 at 15:02
  • Maybe there are some tricks or hacks I could use to achieve this functionality. – Alfi Louis Feb 18 '17 at 15:02
  • The way you'd normally do this to another class in C++ is a free function: `void extension(Class c) { ... }` and `foo(instance);`. You don't directly add anything to the class. As said, to do this at runtime, you can map names to functions. – chris Feb 18 '17 at 15:11

1 Answers1

0

Yes, but it won't be actuall method, std::function<void()> is an object with overloaded () operator. Btw keep in mind that this is a pointer, not a reference so you access it members trough ->, not . operator.

#include <iostream>
#include <functional>

class C {
private:
    std::function<void()> default_method = []() { std::cout << "X"; };

public:
    std::function<void()> method = default_method;

    void change_method() {
        method = []() { std::cout << "Y"; };
    }
};

int main() {
    C object;
    object.method();
    object.change_method();
    object.method();

    return 0;
}

It will print XY.

Kamil Koczurek
  • 696
  • 5
  • 15