Search code examples
c++classobjectmethodsavr

Can I automatically call a method of a class on object declaration in C++?


Lets say I have a class with a private setup function. Is there a way to automatically call the function whenever I declare an object of this class?

bus.h:

class BUS
{
  private:
    void setup();
  public:
    void someOtherFunction(); 
};

main.cpp:

BUS bus; //automatically call setup() here
bus.someOtherFunction();

Solution

  • This is what a constructor is for. If setup() should always be called when an object is created then we would use the constructor to call setup() so it is done without any user intervention.

    class BUS
    {
      private:
        void setup();
      public:
        Bus() { setup(); }
        void someOtherFunction(); 
    };
    

    Now BUS bus; will call setup().