locked
Is it possible to call a function just using a class declaration? RRS feed

  • Question

  • I've created a class, within which I've defined an "init" function. But this requires me to call the function manually: 
    CLASS instance;
    
    instance.init();
    I'd like to be able to just declare the instance, and automatically execute everything in the init function. How do I do this?
    Friday, January 22, 2016 1:41 PM

Answers

All replies

  • Call init within the class constructor.
    Friday, January 22, 2016 1:55 PM
  • I've created a class, within which I've defined an "init" function. But this requires me to call the function manually: 
    CLASS instance;
    
    instance.init();
    I'd like to be able to just declare the instance, and automatically execute everything in the init function. How do I do this?

    There are a lot of things wrong with this code

    1. "instance" seems to be the name of the class (not a good name), not an object so you cannot call init() using the "." operator.

    2. Where is this code? You cannot have executable statements outside a function.

    3. In order to call a class function you need the full definition of the class, not just a declaration.

    RLWA32's suggestion to call init() in the class constructor is likely a good one.


    David Wilkinson | Visual C++ MVP

    Friday, January 22, 2016 2:59 PM
  • Hi ,

    You can call init function in class construct . about the class construct you can refer to the link:

    https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx?f=255&MSPPError=-2147217396

    Best Regards,

    Hart

    Sunday, January 24, 2016 10:31 AM
  • It is almost same as Initializing your class member variable in your constructor. What is your requirement here , what you are doing inside your init() function.  Because this is all depend on your class design and your requirement .As we can treat this function as a static function as well in that case you don't even have to create instance of the class as well. So it's all about your requirement.

    Thanks


    Rupesh Shukla

    Monday, January 25, 2016 3:50 AM