Thread: Constructors/Destructors

  1. #1
    Aspiring "Software Guy"
    Join Date
    Aug 2005
    Posts
    46

    Question Constructors/Destructors

    Just verifying, ...
    A non-member function cannot create an object of a class that has either it's constructor or destructor or both in private section?Not even in main()?
    Also then, it is essential that i do not inline the class's function right?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    A non-member function can create an object of a class whose constructor is public and destructor is private by using new.

    >> Also then, it is essential that i do not inline the class's function right?
    Essential for what? Can you expand on your questions, perhaps with examples, or at least more context?

  3. #3
    Aspiring "Software Guy"
    Join Date
    Aug 2005
    Posts
    46
    What i meant was, that since the member function creates an object of the class, i cant define the function within the class definition because the class hasnt been defined yet. Is this correct.?

    Also could you explain : "A non-member function can create an object of a class whose constructor is public and destructor is private by using new."

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Also could you explain : "A non-member function can create an object of a class whose constructor is public and destructor is private by using new."
    Code:
    class bad_example
    {
    private:
      ~bad_example() { }
    };
    
    int main()
    {
      bad_example* b = new bad_example;
    }
    In that code a non-member function created an object whose destructor is private. I'm pretty sure that's legal. It is also not a good idea because you leak the memory and the destructor is never called, but it is an example of an exception to the rule in your first question. If you don't understand the code, don't worry about it for now, wait until you get to that type of code.

    As for an inline function, it doesn't matter if it is inline or not. All member functions other than a constructor (and maybe a destructor) can create a local object of that type. A constructor or destructor doing so might lead to infinite recursion.

Popular pages Recent additions subscribe to a feed